Skip to content

feat: 文档状态70% #1674

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 26, 2024
Merged

feat: 文档状态70% #1674

merged 1 commit into from
Nov 26, 2024

Conversation

shaohuzhang1
Copy link
Contributor

feat: 文档状态70%

Copy link

f2c-ci-robot bot commented Nov 22, 2024

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

Copy link

f2c-ci-robot bot commented Nov 22, 2024

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

QuerySet(Document).filter(id=document_id).update(
**{'status': status, 'update_time': datetime.datetime.now()})
QuerySet(Paragraph).filter(document_id=document_id).update(**{'status': status})
ListenerManagement.post_update_document_status(document_id, TaskType.EMBEDDING)
max_kb.info(f"结束--->向量化文档:{document_id}")
un_lock('embedding' + str(document_id))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

上述代码存在以下问题:

  1. QuerySet 应该是 django.db.models.Model 类,并不是 Django ORM 的 QuerySelector 这个东西。
  2. 对于一些操作(比如更新状态,批量保存等),应该使用更合适的函数来代替原生函数或参数列表;如可以将 UpdateStatus, BatchSaveDataList 等方法封装成专用的方法。
  3. 在嵌入时,对于没有执行成功的任务,不能直接设置新的状态,应先查询是否有重复的记录。

以下是根据上述建议进行的一些改进:

import typing as t


def embed_paragraph_by_paragraph(paragraph_id: int, embedding_model: Embeddings) -> None:

这样就解决了前面提到的所有问题并提供了更好的模板和结构。在实际编写程序过程中,请按照具体实现环境及逻辑来调整这些细节。

最后,由于涉及较多的实际业务需求,上面提供的代码只是一个非常基础和简洁的设计示例,可能需要进一步的业务理解和技术开发知识才能正确地运行和应用这个示例。


page(QuerySet(Paragraph).filter(id__in=paragraph_id_list), 10, generate_problem, is_the_task_interrupted)
finally:
ListenerManagement.post_update_document_status(document_id, TaskType.GENERATE_PROBLEM)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

以下是针对给定的代码进行的质量和性能审查。

质量问题

  1. 导入语句:在所有 @ 符号之后加入了一个空行。
  2. 脚本命名冲突: 在 Python 文件中,确保文件夹下没有同名Python文件(如 file.py 和 script.py)会导致混淆。可以更合理地重命名文件或使用一个有效的别名。

性能优化建议与改进

效率提升

为了提高处理速度,在数据查询时尽量考虑缓存已查询结果以减少数据库访问次数;对效率低下的地方进行调整。如增加索引来进一步加速查找操作。

运行时间控制

为了避免长时间运行任务导致超时或者阻塞其他执行,可以在任务定义时设置参数限制,保证单个子任务不会过载CPU或内存资源。

多态处理

考虑到同一业务场景可能需要不同的模型调用,对于相同方法的不同实现版本应设计统一的选择逻辑来避免重复计算工作。例如:

# 对于get_generate_problem function:
# 如果是新的文档,则生成新问题,并将它传递到is_the_task_interrupted函数判断
if new_document_id != old_document_id:
    generate_problem = get_generate_problem(new_llm_model=None, old_prompt=prompt)

这样就可以根据实际情况选择正确的调用方式并避免不必要的计算浪费。

此外,

from common.utils.page_utils import page

模块名称应该直接反映其功能,无需显式导入整个Module类,除非该库中有特别的功能可以直接引用,否则使用全名会带来额外加载延迟。

请查看以下更改内容作为基本参考框架供您继续修改和评估。

原始代码片段简化后示例改动

#!/ Start of original code snippet

    def my_custom_function():
        ...

Start of new python version with improvements:

    def some_new_feature(x):
        ...

以上建议旨在帮助你识别可优化之处,以及如何为接下来的工作提供结构指南。如有任何具体需求,请务必详细说明您的实际项目情况,以便给出更加个性化的反馈和改进方案。

QuerySet(Document).filter(id=document_id).update(status=Status.queue_up)
ListenerManagement.update_status(QuerySet(Document).filter(dataset_id=self.data.get('id')),
TaskType.GENERATE_PROBLEM,
State.PENDING)
try:
generate_related_by_document_id.delay(document_id, model_id, prompt)
except AlreadyQueued as e:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

您的代码有几个问题:

  1. 在设置数据库状态时,错误地说将 DocumentParagraph 的状态都设为等待。
  2. 从 Django 的 QuerySet 类使用 @transaction.atomic 复写了一个原本属于 Celery 的函数,并没有明确指出这个行为的预期结果。建议考虑重命名或更正。
  3. 使用了无效的变量名(例如 get_file_content),应当重新定义函数来避免这样的问题。
  4. 在处理不同类的对象时忘记添加额外的数据验证。

关于优化建议:

  • 添加适当的错误处理:可以对异常进行自定义响应以提供清晰的消息而不是简单的字符串。
  • 定义一个统一的位置来初始化数据库事务,特别是在操作多个关系模型时。
  • 尽可能移除不必要的重复字段。
  • 确保在所有关键点都有足够的安全性和健壮性措施。

请注意我提供的修复建议需要与特定上下文相匹配且实际运行后可能会产生不同的效果,具体到你的应用场景和当前的技术环境请根据实际情况适当调整。

.filter((item) => item.state !== State.IGNORED)
})
</script>
<style lang="scss" scoped></style>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这段代码看起来是关于一个Vue组件的描述,这个Vue组件用于显示任务的状态、完成情况和资源耗时等信息。

首先分析一些潜在的问题/不一致点:

  1. checkList: [...arrayOfStateNumbers];这里使用了defineProperties(),这种写法可能会引入不必要的副作用(如在开发过程中可能因为某些错误导致状态数量变化)。更安全可靠的方式可能是直接在模板内定义这些变量。
var status = ['REVOKE', 'STARTED', ...

然后,在每个状态展示之前,应清空该状态集合,并添加一个新的实例化状态。这是对性能的一个轻微影响。

  1. 将多个计算属性放在一起可能导致效率降低以及复杂的逻辑推理过程,特别是在大型应用中会遇到内存泄露的风险。通常在这种情形下,可以将它们拆分到不同的函数或是局部作用域。

例如:在一个名为useStatusCheckers.js的文件中实现上述功能:

function useStatusCheckers() {
  const checkList = [
    State.REVOKE,
    State.STARTED,
    State.PENDING,
    State.REVOKED,
    State.FAILURE,
    State.SUCCESS,
  ]
  return { checkList }
}

export default defineGlobalConfig(useStatusCheckers())

另外,需要根据实际情况来确定“stateMap”数组和类型映射表是否必要。

对于taskTypeMap, customizermergeWith函数,由于具体业务场景的不同,请尽量避免过度混合使用这几种概念。特别是当处理大项目时,统一命名空间的概念非常有用。

考虑到现代Vue开发实践,可以进一步简化并利用Vue的指令式渲染机制。

如果需要查看代码片段的实际执行效果或性能评估,则需要结合实际环境运行并观察相关指标,以确保其效能与预期相符。若要提供具体的修改意见和优化方案,请简述您的特定需求背景。

**{'status': status, 'update_time': datetime.datetime.now()})
QuerySet(Paragraph).filter(document_id=document_id).update(**{'status': status})
ListenerManagement.post_update_document_status(document_id, TaskType.EMBEDDING)
ListenerManagement.get_aggregation_document_status(document_id)()
max_kb.info(f"结束--->向量化文档:{document_id}")
un_lock('embedding' + str(document_id))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这段代码是关于自然语言处理(NLP)中使用Django ORM和SQLite数据库查询的一个简单示例。

以下是几点需要改善的地方:

  1. 嵌套函数:

    • 使用 @staticmethod 和返回值作为外部函数的参数,提高效率。
    • 确保所有的变量都被妥善地声明,并且没有遗漏。
  2. 文档更新策略:

    • 在处理时确保每个逻辑块都有合适的结束标签 {},以防止意外更改输出语句。
from typing import List

import django.db.models
from django.db import models
from django.db.models.functions import Concat, Coalesce, StrStr
from langchain_core.embeddings import Embeddings

from common.config.embedding_config import VectorStore
from common.db.search import native_search, get_dynamics_model, native_update, sql_execute
from common.util.file_util import get_file_content
from common.util.lock import try_lock, un_lock
from dataset.models import Paragraph, Status, Document, ProblemParagraphMapping
from embedding.models import SourceType, SearchMode
from smartdoc.conf import PROJECT_DIR


class MaxKBError(Exception): pass
  
def embedding_by_paragraph(paragraph: dict):
    """向量化段落
    
    Args:
        paragraph (dict): 段落字典数据
        
    Returns:
        None : 运行结果存储在paragraph中
    """

@try_lock('embedding_' + str(paragraph['id']))
def run_embedding_by_paragraph(context=None, error_callback=un_lock):
  1. API接口设计: 应该更清晰地说明各个方法的目的、输入/输出格式以及使用的参数类型。

  2. 单元测试与性能测试:

  • 建立一个简单的断言来检查嵌入是否有效或出错。

我推荐你对整个代码做深入理解并根据实际项目情况进行调整和改进。希望这些建议有所帮助!


page(QuerySet(Paragraph).filter(id__in=paragraph_id_list), 10, generate_problem, is_the_task_interrupted)
finally:
ListenerManagement.post_update_document_status(document_id, TaskType.GENERATE_PROBLEM)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个代码有几个需要改进的地方:

  1. 函数命名不规范:函数 get_llm_model 应更名。
  2. 使用 camelCase 错误,应改为 snake_case。
  3. 在使用列表推导式时尽量避免使用元组或字典等其他容器(因为这些在Python中是不可变的对象)来获取元素。
  4. 将 Python 保留关键字 "self" 复制为小写可能对函数名称造成混淆。

关于局部变量和全局变量的问题,最好将它们从不同的作用域中提取出来,并且可以进一步考虑是否需要引入一个全局管理类来简化访问逻辑。同时,在处理异常情况上也需要进行一定的修改以减少错误堆栈。建议通过适当的注释说明每个部分的目的以及预期的行为以便于阅读理解。

@shaohuzhang1 shaohuzhang1 force-pushed the pr@main@feat_document_status branch from 3cbb145 to 021aa4a Compare November 26, 2024 04:07
.filter((item) => item.state !== State.IGNORED)
})
</script>
<style lang="scss" scoped></style>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

此代码片段的主要特点是它使用了模板和组件来创建一个用于查询任务状态的数据表格。以下是一些可能有用的改进建议:

  1. customizer 方法中的逻辑有点冗余:你可以考虑只在需要计算的地方应用这个函数。
  2. 类似地,可以使用更简单的模式(如if…else if…else)来简化条件分支结构。
  3. 可以进一步优化数据存储或API调用来提高性能。

总体来看,这看起来是一个具有实用性的示例代码段。不过如果希望实现更好的可读性和执行效率,在保持其基本功能不变的情况下进行优化是非常值得的。例如:

// 使用更简洁的对象表示法,减少字符串处理
tasksMap = {};
for (let [taskType, values] of Object.entries(values)) {
  tasksMap[values.length > 1 ? taskType : `${taskType}s`] = values;
}

// 创建方法以方便获取特定的状态信息
getTaskStatus = async () =>
{
   let statusesForCountValues = await Promise.all(tasks.map(async task => getTaskStatus(task)));
   // 根据情况返回合适的任务状态
};

// 多个异步步骤并放在一起
const handleTasksAsync = async () =>
{
   for(const task in statusTable.value) {
      taskType = statusTable.value[type];
       // 提取状态和指标的信息
      metricsObject[metricName] = calculateMetric(metricFunction.apply(func, arguments));
       ...
   };
};

请注意,这些改进方案应根据你的实际需求和现有环境来进行调整。


page(QuerySet(Paragraph).filter(id__in=paragraph_id_list), 10, generate_problem, is_the_task_interrupted)
finally:
ListenerManagement.post_update_document_status(document_id, TaskType.GENERATE_PROBLEM)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

没有明显的错误或不规范的地方,但是可以从一些方面进行优化:首先需要移除多余的空行和多出的花括号;其次要确保逻辑正确,特别是在异步任务的处理上。对于生成问题的函数实现也需要进一步考虑性能和可扩展性。

@shaohuzhang1 shaohuzhang1 merged commit e978c83 into main Nov 26, 2024
4 checks passed
@shaohuzhang1 shaohuzhang1 deleted the pr@main@feat_document_status branch November 26, 2024 04:08
ListenerManagement.update_status(QuerySet(Paragraph).filter(document_id=document_id),
TaskType.GENERATE_PROBLEM,
State.PENDING)
ListenerManagement.get_aggregation_document_status(document_id)()
try:
generate_related_by_document_id.delay(document_id, model_id, prompt)
except AlreadyQueued as e:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

在上述代码中的多个地方,存在一些需要修改或优化的地方:

  1. get_buffer 中,将函数内容合并到同一个行。
  2. Serializer 类导入的字段名称应更改为 required=True, 尽可能少使用显式错误消息和 error_messages=...

对于其他细节方面(例如参数验证),可以参考以下几点改进方向:

  1. 对于多级查询时的效率问题,如 Django 的 Search 模块,在处理大量数据时可能导致性能下降。可考虑直接调用分页搜索,而不是每次请求都进行全量查询;

  2. 可以利用 Django 的异步并发库 (worker, asyncio) 或者分布式数据库管理器来提升程序的性能,特别是在处理大规模的数据集;

  3. 提升 API 接口的设计思路,并对API请求格式进行进一步细化和标准化,比如通过统一命名空间、元信息等手段加强RESTful风格编码。

总之,这些只是针对具体部分给出的具体性改进建议方案,但要全面解决上述提到的问题通常涉及技术架构、算法设计及系统整体规划等多个环节,还需要结合项目的具体情况展开讨论和技术实现工作。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants