From e916f8807842dbf3eed681adbbb3b77f38f1dac5 Mon Sep 17 00:00:00 2001 From: HuangHai <10402852@qq.com> Date: Thu, 27 Mar 2025 09:53:56 +0800 Subject: [PATCH] 'commit' --- AI/WxMini/Utils/ImageUtil.py | 40 +++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/AI/WxMini/Utils/ImageUtil.py b/AI/WxMini/Utils/ImageUtil.py index aadddc39..18ecac21 100644 --- a/AI/WxMini/Utils/ImageUtil.py +++ b/AI/WxMini/Utils/ImageUtil.py @@ -1,6 +1,8 @@ import time import re +from WxMini.Utils.MySQLUtil import save_chat_to_mysql + async def is_text_dominant(client, image_url): """ @@ -35,9 +37,14 @@ async def is_text_dominant(client, image_url): return True -async def recognize_text(client, pool,person_id, image_url): +async def recognize_text(client, pool, person_id, image_url): """ - 识别图片中的文字,流式输出 + 识别图片中的文字,流式输出,并将结果记录到数据库 + :param client: AsyncOpenAI 客户端 + :param pool: 数据库连接池 + :param person_id: 用户 ID + :param image_url: 图片 URL + :return: 最终拼接的字符串 """ completion = await client.chat.completions.create( model="qwen-vl-ocr", @@ -57,15 +64,25 @@ async def recognize_text(client, pool,person_id, image_url): ], stream=True ) + + full_text = "" # 用于存储最终拼接的字符串 async for chunk in completion: if chunk.choices[0].delta.content is not None: for char in chunk.choices[0].delta.content: if char != ' ': - yield char - time.sleep(0.1) + yield char # 流式输出字符 + full_text += char # 拼接字符 + time.sleep(0.1) # 控制输出速度 + + # 记录到数据库 + try: + await save_chat_to_mysql(pool, person_id, f'![]({image_url})', full_text, "", 0) + except Exception as e: + print(f"记录到数据库时出错:{e}") -async def recognize_content(client, pool,person_id, image_url): + +async def recognize_content(client, pool, person_id, image_url): """ 识别图片中的内容,流式输出 """ @@ -77,8 +94,17 @@ async def recognize_content(client, pool,person_id, image_url): ]}], stream=True ) + full_text = "" # 用于存储最终拼接的字符串 async for chunk in completion: if chunk.choices[0].delta.content is not None: for char in chunk.choices[0].delta.content: - yield char - time.sleep(0.1) + if char != ' ': + yield char # 流式输出字符 + full_text += char # 拼接字符 + time.sleep(0.1) # 控制输出速度 + + # 记录到数据库 + try: + await save_chat_to_mysql(pool, person_id, f'![]({image_url})', full_text, "", 0) + except Exception as e: + print(f"记录到数据库时出错:{e}")