Spaces:
Running
Running
maxiaolong03
commited on
Commit
·
9f279fb
1
Parent(s):
054b506
add files
Browse files- .gitignore +1 -0
- Dockerfile +68 -0
- app.py +882 -0
- assets/logo.png +0 -0
- bot_requests.py +390 -0
- crawl_utils.py +96 -0
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
.idea
|
Dockerfile
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
# 1) Install dependencies for Dev Mode + Playwright
|
| 4 |
+
RUN apt-get update && \
|
| 5 |
+
apt-get install -y \
|
| 6 |
+
bash \
|
| 7 |
+
curl \
|
| 8 |
+
wget \
|
| 9 |
+
procps \
|
| 10 |
+
git \
|
| 11 |
+
git-lfs \
|
| 12 |
+
libnss3 \
|
| 13 |
+
libatk1.0-0 \
|
| 14 |
+
libatk-bridge2.0-0 \
|
| 15 |
+
libx11-6 \
|
| 16 |
+
libx11-xcb1 \
|
| 17 |
+
libxcomposite1 \
|
| 18 |
+
libxcursor1 \
|
| 19 |
+
libxdamage1 \
|
| 20 |
+
libxext6 \
|
| 21 |
+
libxfixes3 \
|
| 22 |
+
libxi6 \
|
| 23 |
+
libxrandr2 \
|
| 24 |
+
libxrender1 \
|
| 25 |
+
libxss1 \
|
| 26 |
+
libxtst6 \
|
| 27 |
+
libappindicator1 \
|
| 28 |
+
libsecret-1-0 \
|
| 29 |
+
fonts-ipafont-gothic && \
|
| 30 |
+
rm -rf /var/lib/apt/lists/*
|
| 31 |
+
|
| 32 |
+
# 2) Copy code into /app
|
| 33 |
+
WORKDIR /app
|
| 34 |
+
COPY . /app
|
| 35 |
+
ENV HOME=/app
|
| 36 |
+
|
| 37 |
+
# 3) Install Python dependencies
|
| 38 |
+
RUN pip install --upgrade pip
|
| 39 |
+
RUN pip install gradio==5.27.1
|
| 40 |
+
RUN pip install -U crawl4ai==0.6.3
|
| 41 |
+
|
| 42 |
+
# 4) Install Playwright browser(s)
|
| 43 |
+
RUN pip install playwright==1.53.0
|
| 44 |
+
RUN python -m playwright install --with-deps chromium
|
| 45 |
+
|
| 46 |
+
RUN pip install appbuilder_sdk==1.0.6 \
|
| 47 |
+
docx==0.2.4 \
|
| 48 |
+
faiss-cpu==1.9.0 \
|
| 49 |
+
jieba==0.42.1 \
|
| 50 |
+
mcp==1.9.4 \
|
| 51 |
+
numpy==2.2.6 \
|
| 52 |
+
openai==1.88.0 \
|
| 53 |
+
pdfplumber==0.11.7 \
|
| 54 |
+
python_docx==1.1.2 \
|
| 55 |
+
Requests==2.32.4 \
|
| 56 |
+
sse-starlette==2.3.6
|
| 57 |
+
|
| 58 |
+
# 5) Make /app owned by user 1000 (Dev Mode requirement)
|
| 59 |
+
RUN chown -R 1000 /app
|
| 60 |
+
|
| 61 |
+
# 6) Switch to user 1000
|
| 62 |
+
USER 1000
|
| 63 |
+
|
| 64 |
+
# 7) Expose port for Gradio
|
| 65 |
+
EXPOSE 7860
|
| 66 |
+
|
| 67 |
+
# 8) Start your Gradio app
|
| 68 |
+
CMD ["python", "app.py"]
|
app.py
ADDED
|
@@ -0,0 +1,882 @@
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
|
| 2 |
+
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""This script provides a simple web interface that allows users to interact with."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import asyncio
|
| 19 |
+
from collections import namedtuple
|
| 20 |
+
from datetime import datetime
|
| 21 |
+
from functools import partial
|
| 22 |
+
import json
|
| 23 |
+
import logging
|
| 24 |
+
import os
|
| 25 |
+
import base64
|
| 26 |
+
from argparse import ArgumentParser
|
| 27 |
+
import textwrap
|
| 28 |
+
from docx import Document
|
| 29 |
+
|
| 30 |
+
import gradio as gr
|
| 31 |
+
import pdfplumber
|
| 32 |
+
|
| 33 |
+
from bot_requests import BotClient
|
| 34 |
+
from crawl_utils import CrawlUtils
|
| 35 |
+
|
| 36 |
+
os.environ["NO_PROXY"] = "localhost,127.0.0.1" # Disable proxy
|
| 37 |
+
|
| 38 |
+
logging.root.setLevel(logging.INFO)
|
| 39 |
+
|
| 40 |
+
IMAGE_FILE_TYPE = [".png", ".jpeg", ".jpg"]
|
| 41 |
+
TEXT_FILE_TYPE = [".pdf", ".txt", ".md", ".docx"]
|
| 42 |
+
|
| 43 |
+
SEARCH_INFO_PROMPT = textwrap.dedent(
|
| 44 |
+
"""\
|
| 45 |
+
## 当前时间
|
| 46 |
+
{date}
|
| 47 |
+
|
| 48 |
+
## 对话
|
| 49 |
+
{context}
|
| 50 |
+
问题:{query}
|
| 51 |
+
|
| 52 |
+
根据当前时间和对话完成以下任务:
|
| 53 |
+
1. 查询判断:是否需要借助搜索引擎查询外部知识回答用户当前问题。
|
| 54 |
+
2. 问题改写:改写用户当前问题,使其更适合在搜索引擎查询到相关知识。
|
| 55 |
+
注意:只在**确有必要**的情况下改写,输出不超过 5 个改写结果,不要为了凑满数量而输出冗余问题。
|
| 56 |
+
|
| 57 |
+
## 输出如下格式的内容(只输出 JSON ,不要给出多余内容):
|
| 58 |
+
```json
|
| 59 |
+
{{
|
| 60 |
+
"is_search":true/false,
|
| 61 |
+
"query_list":["改写问题1","改写问题2"...]
|
| 62 |
+
}}```
|
| 63 |
+
"""
|
| 64 |
+
)
|
| 65 |
+
ANSWER_PROMPT = textwrap.dedent(
|
| 66 |
+
"""\
|
| 67 |
+
下面你会收到多段参考资料和一个问题。你的任务是阅读参考资料,并根据参考资料中的信息回答对话中的问题。
|
| 68 |
+
以下是当前时间和参考资料:
|
| 69 |
+
---------
|
| 70 |
+
## 当前时间
|
| 71 |
+
{date}
|
| 72 |
+
|
| 73 |
+
## 参考资料
|
| 74 |
+
{reference}
|
| 75 |
+
|
| 76 |
+
请严格遵守以下规则:
|
| 77 |
+
1. 回答必须结合问题需求和当前时间,对参考资料的可用性进行判断,避免在回答中使用错误或过时的信息。
|
| 78 |
+
2. 当参考资料中的信息无法准确地回答问题时,你需要在回答中提供获取相应信息的建议,或承认无法提供相应信息。
|
| 79 |
+
3. 你需要优先根据百度高权威信息、百科、官网、权威机构、专业网站等高权威性来源的信息来回答问题,
|
| 80 |
+
但务必不要用“(来源:xx)”这类格式给出来源,
|
| 81 |
+
不要暴露来源网站中的“_百度高权威信息”,
|
| 82 |
+
也不要出现'根据参考资料','根据当前时间'等表述。
|
| 83 |
+
4. 更多地使用参考文章中的相关数字、案例、法律条文、公式等信息,让你的答案更专业。
|
| 84 |
+
5. 只要使用了参考资料中的任何内容,必须在句末或段末加上资料编号,如 "[1]" 或 "[2][4]"。不要遗漏编号,也不要随意编造编号。编号必须来源于参考资料中已有的标注。
|
| 85 |
+
---------
|
| 86 |
+
下面请结合以上信息,回答问题,补全对话:
|
| 87 |
+
## 对话
|
| 88 |
+
{context}
|
| 89 |
+
问题:{query}
|
| 90 |
+
|
| 91 |
+
直接输出回复内容即可。
|
| 92 |
+
"""
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_args() -> argparse.Namespace:
|
| 97 |
+
"""
|
| 98 |
+
Parse and return command line arguments for the ERNIE chatbot demo.
|
| 99 |
+
Configures server settings, model endpoints, and operational parameters.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
argparse.Namespace: Parsed command line arguments containing all the above settings.
|
| 103 |
+
"""
|
| 104 |
+
parser = ArgumentParser(description="ERNIE models web chat demo.")
|
| 105 |
+
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"--server-port", type=int, default=7860, help="Demo server port."
|
| 108 |
+
)
|
| 109 |
+
parser.add_argument(
|
| 110 |
+
"--server-name", type=str, default="0.0.0.0", help="Demo server name."
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--max_char", type=int, default=20000, help="Maximum character limit for messages."
|
| 114 |
+
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--max_retry_num", type=int, default=3, help="Maximum retry number for request."
|
| 117 |
+
)
|
| 118 |
+
parser.add_argument(
|
| 119 |
+
"--model_map",
|
| 120 |
+
type=str,
|
| 121 |
+
default="{\"ernie-4.5-turbo-vl-32k\": \"https://qianfan.baidubce.com/v2\"}",
|
| 122 |
+
help="""JSON string defining model name to endpoint mappings.
|
| 123 |
+
Required Format:
|
| 124 |
+
{"ERNIE-4.5-VL": "http://localhost:port/v1"}
|
| 125 |
+
|
| 126 |
+
Note:
|
| 127 |
+
- Endpoint must be valid HTTP URL
|
| 128 |
+
- Specify ONE model endpoint in JSON format.
|
| 129 |
+
- Prefix determines model capabilities:
|
| 130 |
+
* ERNIE-4.5-VL: Multimodal models (image+text)
|
| 131 |
+
"""
|
| 132 |
+
)
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"--web_search_service_url",
|
| 135 |
+
type=str,
|
| 136 |
+
default="https://qianfan.baidubce.com/v2/ai_search/chat/completions",
|
| 137 |
+
help="Web Search Service URL."
|
| 138 |
+
)
|
| 139 |
+
parser.add_argument(
|
| 140 |
+
"--qianfan_api_key",
|
| 141 |
+
type=str,
|
| 142 |
+
default=os.environ.get('API_SEARCH_KEY'),
|
| 143 |
+
help="Web Search Service API key.",
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
args = parser.parse_args()
|
| 147 |
+
try:
|
| 148 |
+
args.model_map = json.loads(args.model_map)
|
| 149 |
+
|
| 150 |
+
# Validation: Check at least one model exists
|
| 151 |
+
if len(args.model_map) < 1:
|
| 152 |
+
raise ValueError("model_map must contain at least one model configuration")
|
| 153 |
+
except json.JSONDecodeError as e:
|
| 154 |
+
raise ValueError("Invalid JSON format for --model-map") from e
|
| 155 |
+
return args
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class GradioEvents(object):
|
| 159 |
+
"""
|
| 160 |
+
Handles Gradio UI events and manages chatbot interactions including conversation flow and file processing.
|
| 161 |
+
|
| 162 |
+
Provides methods for maintaining chat history, extracting text from files, and generating image URLs.
|
| 163 |
+
Supports both text and multimodal interactions with web search integration when needed.
|
| 164 |
+
|
| 165 |
+
Manages chatbot state including conversation history, file attachments and UI updates.
|
| 166 |
+
Includes utilities for reading various file formats and handling streaming AI responses.
|
| 167 |
+
"""
|
| 168 |
+
@staticmethod
|
| 169 |
+
def get_history_conversation(task_history: list, image_history: dict, file_history: dict) -> tuple:
|
| 170 |
+
"""
|
| 171 |
+
Constructs complete conversation history from stored components including text messages,
|
| 172 |
+
attached files and images. Processes each dialogue turn by combining the raw query/response
|
| 173 |
+
pairs with any associated multimedia attachments. For multimodal models, image URLs are
|
| 174 |
+
formatted with base64 encoding while text files have their content extracted inline.
|
| 175 |
+
|
| 176 |
+
Args:
|
| 177 |
+
task_history (list): List of tuples containing user queries and responses.
|
| 178 |
+
image_history (dict): Dictionary mapping indices to lists of image urls.
|
| 179 |
+
file_history (dict): Dictionary mapping indices to lists of file urls.
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
tuple: Tuple containing two elements:
|
| 183 |
+
- conversation (list): List of dictionaries representing the conversation history.
|
| 184 |
+
- conversation_str (str): String representation of the conversation history.
|
| 185 |
+
"""
|
| 186 |
+
conversation = []
|
| 187 |
+
conversation_str = ""
|
| 188 |
+
for idx, (query_h, response_h) in enumerate(task_history):
|
| 189 |
+
conversation_str += "user:\n{query}\nassistant:\n{response}\n".format(query=query_h, response=response_h)
|
| 190 |
+
if idx in file_history:
|
| 191 |
+
for file_url in file_history[idx]:
|
| 192 |
+
query_h += "参考资料[{idx}]:\n资料来源:用户上传\n{file_text}\n".format(
|
| 193 |
+
idx=idx + 1,
|
| 194 |
+
file_text=GradioEvents.get_file_text(file_url)
|
| 195 |
+
)
|
| 196 |
+
if idx in image_history:
|
| 197 |
+
content = []
|
| 198 |
+
for image_url in image_history[idx]:
|
| 199 |
+
content.append({
|
| 200 |
+
"type": "image_url",
|
| 201 |
+
"image_url": {"url": GradioEvents.get_image_url(image_url)}
|
| 202 |
+
})
|
| 203 |
+
content.append({"type": "text", "text": query_h})
|
| 204 |
+
conversation.append({"role": "user", "content": content})
|
| 205 |
+
else:
|
| 206 |
+
conversation.append({"role": "user", "content": query_h})
|
| 207 |
+
conversation.append({"role": "assistant", "content": response_h})
|
| 208 |
+
return conversation, conversation_str
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
def get_search_query(conversation: list, model_name: str, bot_client: BotClient) -> list:
|
| 212 |
+
"""
|
| 213 |
+
Processes conversation history to generate search queries by sending the conversation context
|
| 214 |
+
to the model and parsing its JSON response. Handles model output validation and extracts
|
| 215 |
+
structured search queries containing query lists. Raises Gradio errors for
|
| 216 |
+
invalid JSON responses from the model.
|
| 217 |
+
|
| 218 |
+
Args:
|
| 219 |
+
conversation (list): List of dictionaries representing the conversation history.
|
| 220 |
+
model_name (str): Name of the model being used.
|
| 221 |
+
bot_client (BotClient): An instance of BotClient.
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
list: List of strings representing the search query.
|
| 225 |
+
"""
|
| 226 |
+
req_data = {"messages": conversation}
|
| 227 |
+
try:
|
| 228 |
+
response = bot_client.process(model_name, req_data)
|
| 229 |
+
search_query = response["choices"][0]["message"]["content"]
|
| 230 |
+
start = search_query.find("{")
|
| 231 |
+
end = search_query.rfind("}") + 1
|
| 232 |
+
if start >= 0 and end > start:
|
| 233 |
+
search_query = search_query[start:end]
|
| 234 |
+
search_query = json.loads(search_query)
|
| 235 |
+
return search_query
|
| 236 |
+
except json.JSONDecodeError:
|
| 237 |
+
logging.error("error: model output is not valid JSON format ")
|
| 238 |
+
return None
|
| 239 |
+
|
| 240 |
+
@staticmethod
|
| 241 |
+
def process_files(
|
| 242 |
+
diologue_turn: int,
|
| 243 |
+
files_url: list,
|
| 244 |
+
file_history: dict,
|
| 245 |
+
image_history: dict,
|
| 246 |
+
bot_client: BotClient,
|
| 247 |
+
max_file_char: int
|
| 248 |
+
):
|
| 249 |
+
"""
|
| 250 |
+
Processes file URLs and generates input content for the model.
|
| 251 |
+
Handles both text and image files by:
|
| 252 |
+
1. For text files (PDF, TXT, MD, DOCX): extracts content and adds to file history with reference numbering
|
| 253 |
+
2. For image files (PNG, JPEG, JPG): generates base64 encoded URLs for model input
|
| 254 |
+
Maintains character limits for text references and ensures no duplicate file processing.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
diologue_turn (int): Index of the current dialogue turn.
|
| 258 |
+
files_url (list): List of uploaded file urls.
|
| 259 |
+
file_history (dict): Dictionary mapping indices to lists of file urls.
|
| 260 |
+
image_history (dict): Dictionary mapping indices to lists of image urls.
|
| 261 |
+
bot_client (BotClient): An instance of BotClient.
|
| 262 |
+
max_file_char (int): Maximum number of characters allowed for references.
|
| 263 |
+
|
| 264 |
+
Returns:
|
| 265 |
+
tuple: A tuple containing three elements:
|
| 266 |
+
- input_content (list): List of dictionaries representing the input content.
|
| 267 |
+
- file_contents (str): String representation of the file contents.
|
| 268 |
+
- ref_file_num (int): Number of reference files added.
|
| 269 |
+
"""
|
| 270 |
+
input_content = []
|
| 271 |
+
file_contents = ""
|
| 272 |
+
ref_file_num = 0
|
| 273 |
+
if not files_url:
|
| 274 |
+
return input_content, file_contents, ref_file_num
|
| 275 |
+
|
| 276 |
+
for file_url in files_url:
|
| 277 |
+
extionsion = "." + file_url.split(".")[-1]
|
| 278 |
+
if extionsion in TEXT_FILE_TYPE and (len(file_history) == 0
|
| 279 |
+
or file_url not in list(file_history.values())[-1]):
|
| 280 |
+
file_history[diologue_turn] = file_history.get(diologue_turn, []) + [file_url]
|
| 281 |
+
file_name = file_url.split("/")[-1]
|
| 282 |
+
file_contents_words = bot_client.cut_chinese_english(file_contents)
|
| 283 |
+
|
| 284 |
+
if len(file_contents_words) < max_file_char - 20:
|
| 285 |
+
ref_file_num += 1
|
| 286 |
+
file_content = "\n参考资料[{idx}]:\n资料来源:用户上传\n{file_name}\n{file_text}\n".format(
|
| 287 |
+
idx=len(file_history[diologue_turn]),
|
| 288 |
+
file_name=file_name,
|
| 289 |
+
file_text=GradioEvents.get_file_text(file_url)
|
| 290 |
+
)
|
| 291 |
+
file_content_words = bot_client.cut_chinese_english(file_content)
|
| 292 |
+
max_char = min(len(file_content_words), max_file_char - len(file_contents_words))
|
| 293 |
+
file_content_words = file_content_words[: max_char]
|
| 294 |
+
file_contents += "".join(file_content_words) + "\n"
|
| 295 |
+
elif extionsion in IMAGE_FILE_TYPE and (len(image_history) == 0
|
| 296 |
+
or file_url not in list(image_history.values())[-1]):
|
| 297 |
+
image_history[diologue_turn] = image_history.get(diologue_turn, []) + [file_url]
|
| 298 |
+
input_content.append({"type": "image_url", "image_url": {"url": GradioEvents.get_image_url(file_url)}})
|
| 299 |
+
return input_content, file_contents, ref_file_num
|
| 300 |
+
|
| 301 |
+
@staticmethod
|
| 302 |
+
async def chat_stream(
|
| 303 |
+
query: str,
|
| 304 |
+
task_history: list,
|
| 305 |
+
image_history: dict,
|
| 306 |
+
file_history: dict,
|
| 307 |
+
model_name: str,
|
| 308 |
+
files_url: list,
|
| 309 |
+
search_state: bool,
|
| 310 |
+
bot_client: BotClient,
|
| 311 |
+
max_ref_char: int=18000
|
| 312 |
+
) -> dict:
|
| 313 |
+
"""
|
| 314 |
+
Handles streaming chat queries with text and multimodal inputs.
|
| 315 |
+
Builds conversation history with attachments, checks if web search
|
| 316 |
+
is needed, and streams responses.
|
| 317 |
+
|
| 318 |
+
Args:
|
| 319 |
+
query (str): User input query string.
|
| 320 |
+
task_history (list): List of tuples containing user queries and responses.
|
| 321 |
+
image_history (dict): Dictionary mapping indices to lists of image urls.
|
| 322 |
+
file_history (dict): Dictionary mapping indices to lists of file urls.
|
| 323 |
+
model_name (str): Name of the model being used.
|
| 324 |
+
files_url (list): List of uploaded file urls.
|
| 325 |
+
search_state (bool): Whether to perform a search.
|
| 326 |
+
bot_client (BotClient): An instance of BotClient.
|
| 327 |
+
max_ref_char (int): Maximum number of characters allowed for references.
|
| 328 |
+
|
| 329 |
+
Returns:
|
| 330 |
+
dict: Dictionary containing the following keys:
|
| 331 |
+
- "type": The message type.
|
| 332 |
+
- "content": The content of the message.
|
| 333 |
+
"""
|
| 334 |
+
conversation, conversation_str = GradioEvents.get_history_conversation(
|
| 335 |
+
task_history,
|
| 336 |
+
image_history,
|
| 337 |
+
file_history
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
# Step 1: Determine whether a search is needed and obtain the corresponding query list
|
| 341 |
+
search_info_res = {}
|
| 342 |
+
if search_state:
|
| 343 |
+
search_info_message = SEARCH_INFO_PROMPT.format(
|
| 344 |
+
date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 345 |
+
context=conversation_str,
|
| 346 |
+
query=query
|
| 347 |
+
)
|
| 348 |
+
search_conversation = [{"role": "user", "content": search_info_message}]
|
| 349 |
+
search_info_res = GradioEvents.get_search_query(search_conversation, model_name, bot_client)
|
| 350 |
+
if search_info_res is None:
|
| 351 |
+
search_info_res = {"is_search": True, "query_list": [query]}
|
| 352 |
+
|
| 353 |
+
# Process files
|
| 354 |
+
diologue_turn = len(task_history)
|
| 355 |
+
if search_info_res.get("is_search", False) and search_info_res.get("query_list", []):
|
| 356 |
+
max_file_char = max_ref_char // 2
|
| 357 |
+
else:
|
| 358 |
+
max_file_char = max_ref_char
|
| 359 |
+
input_content, file_contents, ref_file_num = GradioEvents.process_files(
|
| 360 |
+
diologue_turn, files_url, file_history, image_history, bot_client, max_file_char
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
# Step 2: If a search is needed, obtain the corresponding query results
|
| 364 |
+
if search_info_res.get("is_search", False) and search_info_res.get("query_list", []):
|
| 365 |
+
search_result = bot_client.get_web_search_res(search_info_res["query_list"])
|
| 366 |
+
|
| 367 |
+
max_search_result_char = max_ref_char - len(bot_client.cut_chinese_english(file_contents))
|
| 368 |
+
complete_search_result = await GradioEvents.get_complete_search_content(
|
| 369 |
+
ref_file_num, search_result, bot_client, max_search_result_char
|
| 370 |
+
)
|
| 371 |
+
complete_ref = file_contents + "\n" + complete_search_result
|
| 372 |
+
|
| 373 |
+
query = ANSWER_PROMPT.format(
|
| 374 |
+
date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 375 |
+
reference=complete_ref,
|
| 376 |
+
context=conversation_str,
|
| 377 |
+
query=query
|
| 378 |
+
)
|
| 379 |
+
yield {"type": "search_result", "content": complete_ref}
|
| 380 |
+
else:
|
| 381 |
+
query += "\n" + file_contents
|
| 382 |
+
|
| 383 |
+
# Step 3: Answer the user's query
|
| 384 |
+
if image_history.get(diologue_turn, []):
|
| 385 |
+
input_content.append({"type": "text", "text": query})
|
| 386 |
+
conversation.append({"role": "user", "content": input_content})
|
| 387 |
+
else:
|
| 388 |
+
conversation.append({"role": "user", "content": query})
|
| 389 |
+
|
| 390 |
+
try:
|
| 391 |
+
req_data = {"messages": conversation}
|
| 392 |
+
for chunk in bot_client.process_stream(model_name, req_data):
|
| 393 |
+
if "error" in chunk:
|
| 394 |
+
raise Exception(chunk["error"])
|
| 395 |
+
|
| 396 |
+
message = chunk.get("choices", [{}])[0].get("delta", {})
|
| 397 |
+
content = message.get("content", "")
|
| 398 |
+
|
| 399 |
+
if content:
|
| 400 |
+
yield {"type": "answer", "content": content}
|
| 401 |
+
|
| 402 |
+
except Exception as e:
|
| 403 |
+
raise gr.Error("Exception: " + repr(e))
|
| 404 |
+
|
| 405 |
+
@staticmethod
|
| 406 |
+
async def predict(
|
| 407 |
+
query: str,
|
| 408 |
+
chatbot: list,
|
| 409 |
+
task_history: list,
|
| 410 |
+
image_history: dict,
|
| 411 |
+
file_history: dict,
|
| 412 |
+
model: str,
|
| 413 |
+
file_url: list,
|
| 414 |
+
search_state: bool,
|
| 415 |
+
bot_client: BotClient
|
| 416 |
+
) -> tuple:
|
| 417 |
+
"""
|
| 418 |
+
Processes user queries and generates responses through streaming interaction.
|
| 419 |
+
Handles both text and file inputs, manages conversation history updates,
|
| 420 |
+
and optionally performs web searches when enabled. Yields intermediate
|
| 421 |
+
answers as they become available.
|
| 422 |
+
|
| 423 |
+
Args:
|
| 424 |
+
query (str): User input query string.
|
| 425 |
+
chatbot (list): List of dictionaries representing the chatbot history.
|
| 426 |
+
task_history (list): List of tuples containing user queries and responses.
|
| 427 |
+
image_history (dict): Dictionary mapping indices to lists of image urls.
|
| 428 |
+
file_history (dict): Dictionary mapping indices to lists of file urls.
|
| 429 |
+
model (str): Name of the model being used.
|
| 430 |
+
file_url (list): List of uploaded file urls.
|
| 431 |
+
search_state (bool): Whether to perform a search.
|
| 432 |
+
bot_client (BotClient): An instance of BotClient.
|
| 433 |
+
|
| 434 |
+
Returns:
|
| 435 |
+
tuple: Tuple containing two elements:
|
| 436 |
+
- chatbot (list): Updated chatbot history after adding the user's query.
|
| 437 |
+
- search_result (str): Search result obtained from the AI search service.
|
| 438 |
+
"""
|
| 439 |
+
|
| 440 |
+
logging.info("User: {}".format(query))
|
| 441 |
+
# First yield the chatbot with user message
|
| 442 |
+
chatbot.append({"role": "user", "content": query})
|
| 443 |
+
yield chatbot, None
|
| 444 |
+
|
| 445 |
+
response = ""
|
| 446 |
+
search_result = None
|
| 447 |
+
async for new_text in GradioEvents.chat_stream(
|
| 448 |
+
query,
|
| 449 |
+
task_history,
|
| 450 |
+
image_history,
|
| 451 |
+
file_history,
|
| 452 |
+
model,
|
| 453 |
+
file_url,
|
| 454 |
+
search_state,
|
| 455 |
+
bot_client
|
| 456 |
+
):
|
| 457 |
+
if not isinstance(new_text, dict):
|
| 458 |
+
continue
|
| 459 |
+
|
| 460 |
+
if new_text.get("type") == "search_result":
|
| 461 |
+
search_result = new_text["content"]
|
| 462 |
+
yield chatbot, search_result
|
| 463 |
+
continue
|
| 464 |
+
elif new_text.get("type") == "answer":
|
| 465 |
+
response += new_text["content"]
|
| 466 |
+
|
| 467 |
+
# Remove previous message if exists
|
| 468 |
+
if chatbot[-1].get("role") == "assistant":
|
| 469 |
+
chatbot.pop(-1)
|
| 470 |
+
|
| 471 |
+
if response:
|
| 472 |
+
chatbot.append({"role": "assistant", "content": response})
|
| 473 |
+
yield chatbot, search_result
|
| 474 |
+
await asyncio.sleep(0) # Wait to refresh
|
| 475 |
+
|
| 476 |
+
logging.info("History: {}".format(task_history))
|
| 477 |
+
task_history.append((query, response))
|
| 478 |
+
logging.info("ERNIE models: {}".format(response))
|
| 479 |
+
|
| 480 |
+
@staticmethod
|
| 481 |
+
async def regenerate(
|
| 482 |
+
chatbot: list,
|
| 483 |
+
task_history: list,
|
| 484 |
+
image_history: dict,
|
| 485 |
+
file_history: dict,
|
| 486 |
+
model: str,
|
| 487 |
+
file_url: list,
|
| 488 |
+
search_state: bool,
|
| 489 |
+
bot_client: BotClient
|
| 490 |
+
) -> tuple:
|
| 491 |
+
"""
|
| 492 |
+
Regenerates the chatbot's last response by reprocessing the previous user query with current context.
|
| 493 |
+
Maintains conversation continuity by preserving history while removing the last interaction,
|
| 494 |
+
then reinvokes the prediction pipeline with identical parameters to generate a fresh response.
|
| 495 |
+
|
| 496 |
+
Args:
|
| 497 |
+
chatbot (list): List of dictionaries representing the chatbot history.
|
| 498 |
+
task_history (list): List of tuples containing user queries and responses.
|
| 499 |
+
image_history (dict): Dictionary mapping indices to lists of image urls.
|
| 500 |
+
file_history (dict): Dictionary mapping indices to lists of file urls.
|
| 501 |
+
model (str): Name of the model being used.
|
| 502 |
+
file_url (list): List of uploaded file urls.
|
| 503 |
+
search_state (bool): Whether to perform a search.
|
| 504 |
+
bot_client (Botclient): An instance of BotClient.
|
| 505 |
+
|
| 506 |
+
Returns:
|
| 507 |
+
tuple: Tuple containing two elements:
|
| 508 |
+
- chatbot (list): Updated chatbot history after removing the last user query and response.
|
| 509 |
+
- search_result (str): Search result obtained from the AI search service.
|
| 510 |
+
"""
|
| 511 |
+
if not task_history:
|
| 512 |
+
yield chatbot, None
|
| 513 |
+
return
|
| 514 |
+
# Pop the last user query and bot response from task_history
|
| 515 |
+
item = task_history.pop(-1)
|
| 516 |
+
dialogue_turn = len(task_history)
|
| 517 |
+
if (dialogue_turn) in image_history:
|
| 518 |
+
del image_history[dialogue_turn]
|
| 519 |
+
if (dialogue_turn) in file_history:
|
| 520 |
+
del file_history[dialogue_turn]
|
| 521 |
+
while len(chatbot) != 0 and chatbot[-1].get("role") == "assistant":
|
| 522 |
+
chatbot.pop(-1)
|
| 523 |
+
chatbot.pop(-1)
|
| 524 |
+
|
| 525 |
+
async for chunk, search_result in GradioEvents.predict(
|
| 526 |
+
item[0],
|
| 527 |
+
chatbot,
|
| 528 |
+
task_history,
|
| 529 |
+
image_history,
|
| 530 |
+
file_history,
|
| 531 |
+
model,
|
| 532 |
+
file_url,
|
| 533 |
+
search_state,
|
| 534 |
+
bot_client
|
| 535 |
+
):
|
| 536 |
+
yield chunk, search_result
|
| 537 |
+
|
| 538 |
+
@staticmethod
|
| 539 |
+
def reset_user_input() -> gr.update:
|
| 540 |
+
"""
|
| 541 |
+
Reset user input box content.
|
| 542 |
+
|
| 543 |
+
Returns:
|
| 544 |
+
gr.update: Update object indicating that the value should be set to an empty string
|
| 545 |
+
"""
|
| 546 |
+
return gr.update(value="")
|
| 547 |
+
|
| 548 |
+
@staticmethod
|
| 549 |
+
def reset_state() -> namedtuple:
|
| 550 |
+
"""
|
| 551 |
+
Reset the state of the chatbot.
|
| 552 |
+
|
| 553 |
+
Returns:
|
| 554 |
+
namedtuple: A namedtuple containing the following fields:
|
| 555 |
+
- chatbot (list): Empty list
|
| 556 |
+
- task_history (list): Empty list
|
| 557 |
+
- image_history (dict): Empty dictionary
|
| 558 |
+
- file_history (dict): Empty dictionary
|
| 559 |
+
- file_btn (gr.update): Value set to None
|
| 560 |
+
- search_result (gr.update): Value set to None
|
| 561 |
+
"""
|
| 562 |
+
GradioEvents.gc()
|
| 563 |
+
|
| 564 |
+
reset_result = namedtuple("reset_result",
|
| 565 |
+
["chatbot",
|
| 566 |
+
"task_history",
|
| 567 |
+
"image_history",
|
| 568 |
+
"file_history",
|
| 569 |
+
"file_btn",
|
| 570 |
+
"search_result"])
|
| 571 |
+
return reset_result(
|
| 572 |
+
[], # clear chatbot
|
| 573 |
+
[], # clear task_history
|
| 574 |
+
{}, # clear image_history
|
| 575 |
+
{}, # clear file_history
|
| 576 |
+
gr.update(value=None), # clear file_btn
|
| 577 |
+
gr.update(value=None) # reset search_result
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
@staticmethod
|
| 581 |
+
def gc():
|
| 582 |
+
"""Run garbage collection."""
|
| 583 |
+
import gc
|
| 584 |
+
|
| 585 |
+
gc.collect()
|
| 586 |
+
|
| 587 |
+
@staticmethod
|
| 588 |
+
def search_toggle_state(search_state: bool) -> bool:
|
| 589 |
+
"""
|
| 590 |
+
Toggle search state between enabled and disabled.
|
| 591 |
+
|
| 592 |
+
Args:
|
| 593 |
+
search_state (bool): Current search state
|
| 594 |
+
|
| 595 |
+
Returns:
|
| 596 |
+
bool: New search result visible state
|
| 597 |
+
"""
|
| 598 |
+
return gr.update(visible=search_state)
|
| 599 |
+
|
| 600 |
+
@staticmethod
|
| 601 |
+
def get_image_url(image_path: str) -> str:
|
| 602 |
+
"""
|
| 603 |
+
Encode image file to Base64 format and generate data URL.
|
| 604 |
+
Reads an image file from disk, encodes it as Base64, and formats it
|
| 605 |
+
as a data URL that can be used directly in HTML or API requests.
|
| 606 |
+
|
| 607 |
+
Args:
|
| 608 |
+
image_path (str): The path to the image file.
|
| 609 |
+
|
| 610 |
+
Returns:
|
| 611 |
+
str: The URL of the image file.
|
| 612 |
+
"""
|
| 613 |
+
base64_image = ""
|
| 614 |
+
extension = image_path.split(".")[-1]
|
| 615 |
+
with open(image_path, "rb") as image_file:
|
| 616 |
+
base64_image = base64.b64encode(image_file.read()).decode("utf-8")
|
| 617 |
+
url = "data:image/{ext};base64,{img}".format(ext=extension, img=base64_image)
|
| 618 |
+
return url
|
| 619 |
+
|
| 620 |
+
@staticmethod
|
| 621 |
+
def get_file_text(file_path: str) -> str:
|
| 622 |
+
"""
|
| 623 |
+
Get the contents of a file as plain text.
|
| 624 |
+
|
| 625 |
+
Args:
|
| 626 |
+
file_path (str): The path to the file to read.
|
| 627 |
+
|
| 628 |
+
Returns:
|
| 629 |
+
str: The contents of the file as plain text.
|
| 630 |
+
"""
|
| 631 |
+
if file_path is None:
|
| 632 |
+
return ""
|
| 633 |
+
if file_path.endswith(".pdf"):
|
| 634 |
+
return GradioEvents.read_pdf(file_path)
|
| 635 |
+
elif file_path.endswith(".docx"):
|
| 636 |
+
return GradioEvents.read_docx(file_path)
|
| 637 |
+
elif file_path.endswith(".txt") or file_path.endswith(".md"):
|
| 638 |
+
return GradioEvents.read_txt_md(file_path)
|
| 639 |
+
else:
|
| 640 |
+
return ""
|
| 641 |
+
|
| 642 |
+
@staticmethod
|
| 643 |
+
def read_pdf(pdf_path: str) -> str:
|
| 644 |
+
"""
|
| 645 |
+
Extracts text content from a PDF file using pdfplumber library. Processes each page sequentially
|
| 646 |
+
and concatenates all extracted text. Handles potential extraction errors gracefully by returning
|
| 647 |
+
an empty string and logging the error.
|
| 648 |
+
|
| 649 |
+
Args:
|
| 650 |
+
pdf_path (str): Path to the PDF file.
|
| 651 |
+
|
| 652 |
+
Returns:
|
| 653 |
+
str: Text extracted from the PDF file.
|
| 654 |
+
"""
|
| 655 |
+
try:
|
| 656 |
+
text = ""
|
| 657 |
+
with pdfplumber.open(pdf_path) as pdf:
|
| 658 |
+
for page in pdf.pages:
|
| 659 |
+
text += page.extract_text()
|
| 660 |
+
return text
|
| 661 |
+
except Exception as e:
|
| 662 |
+
logging.info("Error reading PDF file: {}".format(e))
|
| 663 |
+
return ""
|
| 664 |
+
|
| 665 |
+
@staticmethod
|
| 666 |
+
def read_docx(file_path: str) -> str:
|
| 667 |
+
"""
|
| 668 |
+
Extracts text content from a DOCX file using python-docx library. Processes all paragraphs
|
| 669 |
+
sequentially and joins them with newline characters. Handles potential file reading errors
|
| 670 |
+
gracefully by returning an empty string and logging the error.
|
| 671 |
+
|
| 672 |
+
Args:
|
| 673 |
+
file_path (str): Path to the DOCX file.
|
| 674 |
+
|
| 675 |
+
Returns:
|
| 676 |
+
str: Text extracted from the DOCX file.
|
| 677 |
+
"""
|
| 678 |
+
try:
|
| 679 |
+
doc = Document(file_path)
|
| 680 |
+
full_text = []
|
| 681 |
+
for paragraph in doc.paragraphs:
|
| 682 |
+
full_text.append(paragraph.text)
|
| 683 |
+
return "\n".join(full_text)
|
| 684 |
+
except Exception as e:
|
| 685 |
+
logging.info("Error reading DOCX file: {}".format(e))
|
| 686 |
+
return ""
|
| 687 |
+
|
| 688 |
+
@staticmethod
|
| 689 |
+
def read_txt_md(file_path: str) -> str:
|
| 690 |
+
"""
|
| 691 |
+
Read a TXT or MD file and extract its text content.
|
| 692 |
+
|
| 693 |
+
Args:
|
| 694 |
+
file_path (str): Path to the TXT or MD file.
|
| 695 |
+
|
| 696 |
+
Returns:
|
| 697 |
+
str: Text extracted from the TXT or MD file.
|
| 698 |
+
"""
|
| 699 |
+
try:
|
| 700 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 701 |
+
return f.read()
|
| 702 |
+
except Exception as e:
|
| 703 |
+
logging.info("Error reading TXT or MD file: {}".format(e))
|
| 704 |
+
return ""
|
| 705 |
+
|
| 706 |
+
@staticmethod
|
| 707 |
+
async def get_complete_search_content(
|
| 708 |
+
ref_file_num: int,
|
| 709 |
+
search_results: list,
|
| 710 |
+
bot_client: BotClient,
|
| 711 |
+
max_search_results_char
|
| 712 |
+
) -> str:
|
| 713 |
+
"""
|
| 714 |
+
Combines and formats multiple search results into a single string.
|
| 715 |
+
Processes each result, extracts URLs, crawls content, and enforces length limits.
|
| 716 |
+
|
| 717 |
+
Args:
|
| 718 |
+
ref_file_num (int): Reference file number
|
| 719 |
+
search_results (list): List of search results
|
| 720 |
+
bot_client (BotClient): Chatbot client instance
|
| 721 |
+
max_search_results_char (int): Maximum character length of each search result
|
| 722 |
+
|
| 723 |
+
Returns:
|
| 724 |
+
str: Complete search content string
|
| 725 |
+
"""
|
| 726 |
+
results = []
|
| 727 |
+
crawl_utils = CrawlUtils()
|
| 728 |
+
for search_res in search_results:
|
| 729 |
+
for item in search_res:
|
| 730 |
+
new_content = await crawl_utils.get_webpage_text(item["url"])
|
| 731 |
+
if not new_content:
|
| 732 |
+
continue
|
| 733 |
+
item_text = "Title: {title} \nURL: {url} \nContent:\n{content}\n".format(
|
| 734 |
+
title=item["title"], url=item["url"], content=new_content
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
# Truncate the search result to max_search_results_char characters
|
| 738 |
+
search_res_words = bot_client.cut_chinese_english(item_text)
|
| 739 |
+
res_words = bot_client.cut_chinese_english("".join(results))
|
| 740 |
+
if len(search_res_words) + len(res_words) > max_search_results_char:
|
| 741 |
+
break
|
| 742 |
+
|
| 743 |
+
results.append("参考资料[{idx}]:\n资料来源:素材检索\n{item_text}\n".format(
|
| 744 |
+
idx=len(results) + 1 + ref_file_num, item_text=item_text
|
| 745 |
+
))
|
| 746 |
+
|
| 747 |
+
return "".join(results)
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
def launch_demo(args: argparse.Namespace, bot_client: BotClient):
|
| 751 |
+
"""
|
| 752 |
+
Launch demo program
|
| 753 |
+
|
| 754 |
+
Args:
|
| 755 |
+
args (argparse.Namespace): argparse Namespace object containing parsed command line arguments
|
| 756 |
+
bot_client (BotClient): Bot client instance
|
| 757 |
+
"""
|
| 758 |
+
css = """
|
| 759 |
+
.input-textbox textarea {
|
| 760 |
+
height: 200px !important;
|
| 761 |
+
}
|
| 762 |
+
#file-upload {
|
| 763 |
+
height: 247px !important;
|
| 764 |
+
min-height: 247px !important;
|
| 765 |
+
max-height: 247px !important;
|
| 766 |
+
}
|
| 767 |
+
/* Hide original Chinese text */
|
| 768 |
+
#file-upload .wrap {
|
| 769 |
+
font-size: 0 !important;
|
| 770 |
+
position: relative;
|
| 771 |
+
display: flex;
|
| 772 |
+
flex-direction: column;
|
| 773 |
+
align-items: center;
|
| 774 |
+
justify-content: center;
|
| 775 |
+
}
|
| 776 |
+
|
| 777 |
+
/* Insert English prompt text below the SVG icon */
|
| 778 |
+
#file-upload .wrap::after {
|
| 779 |
+
content: "Drag and drop files here or click to upload";
|
| 780 |
+
font-size: 18px;
|
| 781 |
+
color: #555;
|
| 782 |
+
margin-top: 8px;
|
| 783 |
+
white-space: nowrap;
|
| 784 |
+
}
|
| 785 |
+
"""
|
| 786 |
+
|
| 787 |
+
with gr.Blocks(css=css) as demo:
|
| 788 |
+
logo_url = GradioEvents.get_image_url("assets/logo.png")
|
| 789 |
+
gr.Markdown("""\
|
| 790 |
+
<p align="center"><img src="{}" \
|
| 791 |
+
style="height: 60px"/><p>""".format(logo_url))
|
| 792 |
+
gr.Markdown(
|
| 793 |
+
"""\
|
| 794 |
+
<center><font size=3>This demo is based on ERNIE models. \
|
| 795 |
+
(本演示基于文心大模型实现。)</center>"""
|
| 796 |
+
)
|
| 797 |
+
|
| 798 |
+
chatbot = gr.Chatbot(
|
| 799 |
+
label="ERNIE",
|
| 800 |
+
elem_classes="control-height",
|
| 801 |
+
type="messages"
|
| 802 |
+
)
|
| 803 |
+
|
| 804 |
+
search_result = gr.Textbox(label="Search Result", lines=10, max_lines=10, visible=False)
|
| 805 |
+
|
| 806 |
+
with gr.Row():
|
| 807 |
+
search_check = gr.Checkbox(label="🌐 Search the web(联网搜索)")
|
| 808 |
+
|
| 809 |
+
with gr.Row():
|
| 810 |
+
query = gr.Textbox(label="Input", lines=1, scale=6, elem_classes="input-textbox")
|
| 811 |
+
file_btn = gr.File(
|
| 812 |
+
label="File upload (Accepted formats: PNG, JPEG, JPG, PDF, TXT, MD, DOC, DOCX)",
|
| 813 |
+
scale=4,
|
| 814 |
+
elem_id="file-upload",
|
| 815 |
+
file_types=IMAGE_FILE_TYPE + TEXT_FILE_TYPE,
|
| 816 |
+
file_count="multiple"
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
with gr.Row():
|
| 820 |
+
empty_btn = gr.Button("🧹 Clear History(清除历史)")
|
| 821 |
+
submit_btn = gr.Button("🚀 Submit(发送)")
|
| 822 |
+
regen_btn = gr.Button("🤔️ Regenerate(重试)")
|
| 823 |
+
|
| 824 |
+
task_history = gr.State([])
|
| 825 |
+
image_history = gr.State({})
|
| 826 |
+
file_history = gr.State({})
|
| 827 |
+
model_name = gr.State(list(args.model_map.keys())[0])
|
| 828 |
+
|
| 829 |
+
search_check.change(
|
| 830 |
+
fn=GradioEvents.search_toggle_state,
|
| 831 |
+
inputs=search_check,
|
| 832 |
+
outputs=search_result
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
predict_with_clients = partial(
|
| 836 |
+
GradioEvents.predict,
|
| 837 |
+
bot_client=bot_client
|
| 838 |
+
)
|
| 839 |
+
regenerate_with_clients = partial(
|
| 840 |
+
GradioEvents.regenerate,
|
| 841 |
+
bot_client=bot_client
|
| 842 |
+
)
|
| 843 |
+
query.submit(
|
| 844 |
+
predict_with_clients,
|
| 845 |
+
inputs=[query, chatbot, task_history, image_history, file_history, model_name, file_btn, search_check],
|
| 846 |
+
outputs=[chatbot, search_result],
|
| 847 |
+
show_progress=True
|
| 848 |
+
)
|
| 849 |
+
query.submit(GradioEvents.reset_user_input, [], [query])
|
| 850 |
+
submit_btn.click(
|
| 851 |
+
predict_with_clients,
|
| 852 |
+
inputs=[query, chatbot, task_history, image_history, file_history, model_name, file_btn, search_check],
|
| 853 |
+
outputs=[chatbot, search_result],
|
| 854 |
+
show_progress=True,
|
| 855 |
+
)
|
| 856 |
+
submit_btn.click(GradioEvents.reset_user_input, [], [query])
|
| 857 |
+
empty_btn.click(
|
| 858 |
+
GradioEvents.reset_state,
|
| 859 |
+
outputs=[chatbot, task_history, image_history, file_history, file_btn, search_result],
|
| 860 |
+
show_progress=True
|
| 861 |
+
)
|
| 862 |
+
regen_btn.click(
|
| 863 |
+
regenerate_with_clients,
|
| 864 |
+
inputs=[chatbot, task_history, image_history, file_history, model_name, file_btn, search_check],
|
| 865 |
+
outputs=[chatbot, search_result],
|
| 866 |
+
show_progress=True
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
demo.queue().launch(
|
| 870 |
+
server_port=args.server_port,
|
| 871 |
+
server_name=args.server_name
|
| 872 |
+
)
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def main():
|
| 876 |
+
"""Main function that runs when this script is executed."""
|
| 877 |
+
args = get_args()
|
| 878 |
+
bot_client = BotClient(args)
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
|
| 2 |
+
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""BotClient class for interacting with bot models."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import argparse
|
| 19 |
+
import logging
|
| 20 |
+
import traceback
|
| 21 |
+
import json
|
| 22 |
+
import jieba
|
| 23 |
+
from openai import OpenAI
|
| 24 |
+
|
| 25 |
+
import requests
|
| 26 |
+
|
| 27 |
+
class BotClient(object):
|
| 28 |
+
"""Client for interacting with various AI models."""
|
| 29 |
+
def __init__(self, args: argparse.Namespace):
|
| 30 |
+
"""
|
| 31 |
+
Initializes the BotClient instance by configuring essential parameters from command line arguments
|
| 32 |
+
including retry limits, character constraints, model endpoints and API credentials while setting up
|
| 33 |
+
default values for missing arguments to ensure robust operation.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
args (argparse.Namespace): Command line arguments containing configuration parameters.
|
| 37 |
+
Uses getattr() to safely retrieve values with fallback defaults.
|
| 38 |
+
"""
|
| 39 |
+
self.logger = logging.getLogger(__name__)
|
| 40 |
+
|
| 41 |
+
self.max_retry_num = getattr(args, 'max_retry_num', 3)
|
| 42 |
+
self.max_char = getattr(args, 'max_char', 8000)
|
| 43 |
+
|
| 44 |
+
self.model_map = getattr(args, 'model_map', {})
|
| 45 |
+
self.api_key = os.environ.get('API_KEY')
|
| 46 |
+
|
| 47 |
+
self.embedding_service_url = getattr(args, 'embedding_service_url', 'embedding_service_url')
|
| 48 |
+
self.embedding_model = getattr(args, 'embedding_model', 'embedding_model')
|
| 49 |
+
|
| 50 |
+
self.web_search_service_url = getattr(args, 'web_search_service_url', 'web_search_service_url')
|
| 51 |
+
self.max_search_results_num = getattr(args, 'max_search_results_num', 15)
|
| 52 |
+
|
| 53 |
+
self.qianfan_api_key = os.environ.get('API_SEARCH_KEY')
|
| 54 |
+
|
| 55 |
+
def call_back(self, host_url: str, req_data: dict) -> dict:
|
| 56 |
+
"""
|
| 57 |
+
Executes an HTTP request to the specified endpoint using the OpenAI client, handles the response
|
| 58 |
+
conversion to a compatible dictionary format, and manages any exceptions that may occur during
|
| 59 |
+
the request process while logging errors appropriately.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
host_url (str): The URL to send the request to.
|
| 63 |
+
req_data (dict): The data to send in the request body.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
dict: Parsed JSON response from the server. Returns empty dict
|
| 67 |
+
if request fails or response is invalid.
|
| 68 |
+
"""
|
| 69 |
+
try:
|
| 70 |
+
client = OpenAI(base_url=host_url, api_key=self.api_key)
|
| 71 |
+
response = client.chat.completions.create(
|
| 72 |
+
**req_data
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Convert OpenAI response to compatible format
|
| 76 |
+
return response.model_dump()
|
| 77 |
+
|
| 78 |
+
except Exception as e:
|
| 79 |
+
self.logger.error("Stream request failed: {}".format(e))
|
| 80 |
+
raise
|
| 81 |
+
|
| 82 |
+
def call_back_stream(self, host_url: str, req_data: dict) -> dict:
|
| 83 |
+
"""
|
| 84 |
+
Makes a streaming HTTP request to the specified host URL using the OpenAI client and yields response chunks
|
| 85 |
+
in real-time while handling any exceptions that may occur during the streaming process.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
host_url (str): The URL to send the request to.
|
| 89 |
+
req_data (dict): The data to send in the request body.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
generator: Generator that yields parsed JSON responses from the server.
|
| 93 |
+
"""
|
| 94 |
+
try:
|
| 95 |
+
client = OpenAI(base_url=host_url, api_key=self.api_key)
|
| 96 |
+
response = client.chat.completions.create(
|
| 97 |
+
**req_data,
|
| 98 |
+
stream=True,
|
| 99 |
+
)
|
| 100 |
+
for chunk in response:
|
| 101 |
+
if not chunk.choices:
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
# Convert OpenAI response to compatible format
|
| 105 |
+
yield chunk.model_dump()
|
| 106 |
+
|
| 107 |
+
except Exception as e:
|
| 108 |
+
self.logger.error("Stream request failed: {}".format(e))
|
| 109 |
+
raise
|
| 110 |
+
|
| 111 |
+
def process(
|
| 112 |
+
self,
|
| 113 |
+
model_name: str,
|
| 114 |
+
req_data: dict,
|
| 115 |
+
max_tokens: int=2048,
|
| 116 |
+
temperature: float=1.0,
|
| 117 |
+
top_p: float=0.7
|
| 118 |
+
) -> dict:
|
| 119 |
+
"""
|
| 120 |
+
Handles chat completion requests by mapping the model name to its endpoint, preparing request parameters
|
| 121 |
+
including token limits and sampling settings, truncating messages to fit character limits, making API calls
|
| 122 |
+
with built-in retry mechanism, and logging the full request/response cycle for debugging purposes.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
model_name (str): Name of the model, used to look up the model URL from model_map.
|
| 126 |
+
req_data (dict): Dictionary containing request data, including information to be processed.
|
| 127 |
+
max_tokens (int): Maximum number of tokens to generate.
|
| 128 |
+
temperature (float): Sampling temperature to control the diversity of generated text.
|
| 129 |
+
top_p (float): Cumulative probability threshold to control the diversity of generated text.
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
dict: Dictionary containing the model's processing results.
|
| 133 |
+
"""
|
| 134 |
+
model_url = self.model_map[model_name]
|
| 135 |
+
|
| 136 |
+
req_data["model"] = model_name
|
| 137 |
+
req_data["max_tokens"] = max_tokens
|
| 138 |
+
req_data["temperature"] = temperature
|
| 139 |
+
req_data["top_p"] = top_p
|
| 140 |
+
req_data["messages"] = self.truncate_messages(req_data["messages"])
|
| 141 |
+
for _ in range(self.max_retry_num):
|
| 142 |
+
try:
|
| 143 |
+
self.logger.info("[MODEL] {}".format(model_url))
|
| 144 |
+
self.logger.info("[req_data]====>")
|
| 145 |
+
self.logger.info(json.dumps(req_data, ensure_ascii=False))
|
| 146 |
+
res = self.call_back(model_url, req_data)
|
| 147 |
+
self.logger.info("model response")
|
| 148 |
+
self.logger.info(res)
|
| 149 |
+
self.logger.info("-" * 30)
|
| 150 |
+
except Exception as e:
|
| 151 |
+
self.logger.info(e)
|
| 152 |
+
self.logger.info(traceback.format_exc())
|
| 153 |
+
res = {}
|
| 154 |
+
if len(res) != 0 and "error" not in res:
|
| 155 |
+
break
|
| 156 |
+
|
| 157 |
+
return res
|
| 158 |
+
|
| 159 |
+
def process_stream(
|
| 160 |
+
self, model_name: str,
|
| 161 |
+
req_data: dict,
|
| 162 |
+
max_tokens: int=2048,
|
| 163 |
+
temperature: float=1.0,
|
| 164 |
+
top_p: float=0.7
|
| 165 |
+
) -> dict:
|
| 166 |
+
"""
|
| 167 |
+
Processes streaming requests by mapping the model name to its endpoint, configuring request parameters,
|
| 168 |
+
implementing a retry mechanism with logging, and streaming back response chunks in real-time while
|
| 169 |
+
handling any errors that may occur during the streaming session.
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
model_name (str): Name of the model, used to look up the model URL from model_map.
|
| 173 |
+
req_data (dict): Dictionary containing request data, including information to be processed.
|
| 174 |
+
max_tokens (int): Maximum number of tokens to generate.
|
| 175 |
+
temperature (float): Sampling temperature to control the diversity of generated text.
|
| 176 |
+
top_p (float): Cumulative probability threshold to control the diversity of generated text.
|
| 177 |
+
|
| 178 |
+
Yields:
|
| 179 |
+
dict: Dictionary containing the model's processing results.
|
| 180 |
+
"""
|
| 181 |
+
model_url = self.model_map[model_name]
|
| 182 |
+
req_data["model"] = model_name
|
| 183 |
+
req_data["max_tokens"] = max_tokens
|
| 184 |
+
req_data["temperature"] = temperature
|
| 185 |
+
req_data["top_p"] = top_p
|
| 186 |
+
req_data["messages"] = self.truncate_messages(req_data["messages"])
|
| 187 |
+
|
| 188 |
+
last_error = None
|
| 189 |
+
for _ in range(self.max_retry_num):
|
| 190 |
+
try:
|
| 191 |
+
self.logger.info("[MODEL] {}".format(model_url))
|
| 192 |
+
self.logger.info("[req_data]====>")
|
| 193 |
+
self.logger.info(json.dumps(req_data, ensure_ascii=False))
|
| 194 |
+
|
| 195 |
+
for chunk in self.call_back_stream(model_url, req_data):
|
| 196 |
+
yield chunk
|
| 197 |
+
return
|
| 198 |
+
|
| 199 |
+
except Exception as e:
|
| 200 |
+
last_error = e
|
| 201 |
+
self.logger.error("Stream request failed (attempt {}/{}): {}".format(_ + 1, self.max_retry_num, e))
|
| 202 |
+
|
| 203 |
+
self.logger.error("All retry attempts failed for stream request")
|
| 204 |
+
yield {"error": str(last_error)}
|
| 205 |
+
|
| 206 |
+
def cut_chinese_english(self, text: str) -> list:
|
| 207 |
+
"""
|
| 208 |
+
Segments mixed Chinese and English text into individual components using Jieba for Chinese words
|
| 209 |
+
while preserving English words as whole units, with special handling for Unicode character ranges
|
| 210 |
+
to distinguish between the two languages.
|
| 211 |
+
|
| 212 |
+
Args:
|
| 213 |
+
text (str): Input string to be segmented.
|
| 214 |
+
|
| 215 |
+
Returns:
|
| 216 |
+
list: A list of segments, where each segment is either a letter or a word.
|
| 217 |
+
"""
|
| 218 |
+
words = jieba.lcut(text)
|
| 219 |
+
en_ch_words = []
|
| 220 |
+
|
| 221 |
+
for word in words:
|
| 222 |
+
if word.isalpha() and not any("\u4e00" <= char <= "\u9fff" for char in word):
|
| 223 |
+
en_ch_words.append(word)
|
| 224 |
+
else:
|
| 225 |
+
en_ch_words.extend(list(word))
|
| 226 |
+
return en_ch_words
|
| 227 |
+
|
| 228 |
+
def truncate_messages(self, messages: list[dict]) -> list:
|
| 229 |
+
"""
|
| 230 |
+
Truncates conversation messages to fit within the maximum character limit (self.max_char)
|
| 231 |
+
by intelligently removing content while preserving message structure. The truncation follows
|
| 232 |
+
a prioritized order: historical messages first, then system message, and finally the last message.
|
| 233 |
+
|
| 234 |
+
Args:
|
| 235 |
+
messages (list[dict]): List of messages to be truncated.
|
| 236 |
+
|
| 237 |
+
Returns:
|
| 238 |
+
list[dict]: Modified list of messages after truncation.
|
| 239 |
+
"""
|
| 240 |
+
if not messages:
|
| 241 |
+
return messages
|
| 242 |
+
|
| 243 |
+
processed = []
|
| 244 |
+
total_units = 0
|
| 245 |
+
|
| 246 |
+
for msg in messages:
|
| 247 |
+
# Handle two different content formats
|
| 248 |
+
if isinstance(msg["content"], str):
|
| 249 |
+
text_content = msg["content"]
|
| 250 |
+
elif isinstance(msg["content"], list):
|
| 251 |
+
text_content = msg["content"][1]["text"]
|
| 252 |
+
else:
|
| 253 |
+
text_content = ""
|
| 254 |
+
|
| 255 |
+
# Calculate unit count after tokenization
|
| 256 |
+
units = self.cut_chinese_english(text_content)
|
| 257 |
+
unit_count = len(units)
|
| 258 |
+
|
| 259 |
+
processed.append({
|
| 260 |
+
"role": msg["role"],
|
| 261 |
+
"original_content": msg["content"], # Preserve original content
|
| 262 |
+
"text_content": text_content, # Extracted plain text
|
| 263 |
+
"units": units,
|
| 264 |
+
"unit_count": unit_count
|
| 265 |
+
})
|
| 266 |
+
total_units += unit_count
|
| 267 |
+
|
| 268 |
+
if total_units <= self.max_char:
|
| 269 |
+
return messages
|
| 270 |
+
|
| 271 |
+
# Number of units to remove
|
| 272 |
+
to_remove = total_units - self.max_char
|
| 273 |
+
|
| 274 |
+
# 1. Truncate historical messages
|
| 275 |
+
for i in range(len(processed) - 1, 1):
|
| 276 |
+
if to_remove <= 0:
|
| 277 |
+
break
|
| 278 |
+
|
| 279 |
+
# current = processed[i]
|
| 280 |
+
if processed[i]["unit_count"] <= to_remove:
|
| 281 |
+
processed[i]["text_content"] = ""
|
| 282 |
+
to_remove -= processed[i]["unit_count"]
|
| 283 |
+
if isinstance(processed[i]["original_content"], str):
|
| 284 |
+
processed[i]["original_content"] = ""
|
| 285 |
+
elif isinstance(processed[i]["original_content"], list):
|
| 286 |
+
processed[i]["original_content"][1]["text"] = ""
|
| 287 |
+
else:
|
| 288 |
+
kept_units = processed[i]["units"][:-to_remove]
|
| 289 |
+
new_text = "".join(kept_units)
|
| 290 |
+
processed[i]["text_content"] = new_text
|
| 291 |
+
if isinstance(processed[i]["original_content"], str):
|
| 292 |
+
processed[i]["original_content"] = new_text
|
| 293 |
+
elif isinstance(processed[i]["original_content"], list):
|
| 294 |
+
processed[i]["original_content"][1]["text"] = new_text
|
| 295 |
+
to_remove = 0
|
| 296 |
+
|
| 297 |
+
# 2. Truncate system message
|
| 298 |
+
if to_remove > 0:
|
| 299 |
+
system_msg = processed[0]
|
| 300 |
+
if system_msg["unit_count"] <= to_remove:
|
| 301 |
+
processed[0]["text_content"] = ""
|
| 302 |
+
to_remove -= system_msg["unit_count"]
|
| 303 |
+
if isinstance(processed[0]["original_content"], str):
|
| 304 |
+
processed[0]["original_content"] = ""
|
| 305 |
+
elif isinstance(processed[0]["original_content"], list):
|
| 306 |
+
processed[0]["original_content"][1]["text"] = ""
|
| 307 |
+
else:
|
| 308 |
+
kept_units = system_msg["units"][:-to_remove]
|
| 309 |
+
new_text = "".join(kept_units)
|
| 310 |
+
processed[0]["text_content"] = new_text
|
| 311 |
+
if isinstance(processed[0]["original_content"], str):
|
| 312 |
+
processed[0]["original_content"] = new_text
|
| 313 |
+
elif isinstance(processed[0]["original_content"], list):
|
| 314 |
+
processed[0]["original_content"][1]["text"] = new_text
|
| 315 |
+
to_remove = 0
|
| 316 |
+
|
| 317 |
+
# 3. Truncate last message
|
| 318 |
+
if to_remove > 0 and len(processed) > 1:
|
| 319 |
+
last_msg = processed[-1]
|
| 320 |
+
if last_msg["unit_count"] > to_remove:
|
| 321 |
+
kept_units = last_msg["units"][:-to_remove]
|
| 322 |
+
new_text = "".join(kept_units)
|
| 323 |
+
last_msg["text_content"] = new_text
|
| 324 |
+
if isinstance(last_msg["original_content"], str):
|
| 325 |
+
last_msg["original_content"] = new_text
|
| 326 |
+
elif isinstance(last_msg["original_content"], list):
|
| 327 |
+
last_msg["original_content"][1]["text"] = new_text
|
| 328 |
+
else:
|
| 329 |
+
last_msg["text_content"] = ""
|
| 330 |
+
if isinstance(last_msg["original_content"], str):
|
| 331 |
+
last_msg["original_content"] = ""
|
| 332 |
+
elif isinstance(last_msg["original_content"], list):
|
| 333 |
+
last_msg["original_content"][1]["text"] = ""
|
| 334 |
+
|
| 335 |
+
result = []
|
| 336 |
+
for msg in processed:
|
| 337 |
+
if msg["text_content"]:
|
| 338 |
+
result.append({
|
| 339 |
+
"role": msg["role"],
|
| 340 |
+
"content": msg["original_content"]
|
| 341 |
+
})
|
| 342 |
+
|
| 343 |
+
return result
|
| 344 |
+
|
| 345 |
+
def embed_fn(self, text: str) -> list:
|
| 346 |
+
"""
|
| 347 |
+
Generate an embedding for the given text using the QianFan API.
|
| 348 |
+
|
| 349 |
+
Args:
|
| 350 |
+
text (str): The input text to be embedded.
|
| 351 |
+
|
| 352 |
+
Returns:
|
| 353 |
+
list: A list of floats representing the embedding.
|
| 354 |
+
"""
|
| 355 |
+
client = OpenAI(base_url=self.embedding_service_url, api_key=self.qianfan_api_key)
|
| 356 |
+
response = client.embeddings.create(input=[text], model=self.embedding_model)
|
| 357 |
+
return response.data[0].embedding
|
| 358 |
+
|
| 359 |
+
def get_web_search_res(self, query_list: list) -> list:
|
| 360 |
+
"""
|
| 361 |
+
Send a request to the AI Search service using the provided API key and service URL.
|
| 362 |
+
|
| 363 |
+
Args:
|
| 364 |
+
query_list (list): List of queries to send to the AI Search service.
|
| 365 |
+
|
| 366 |
+
Returns:
|
| 367 |
+
list: List of responses from the AI Search service.
|
| 368 |
+
"""
|
| 369 |
+
headers = {
|
| 370 |
+
"Authorization": "Bearer " + self.qianfan_api_key,
|
| 371 |
+
"Content-Type": "application/json"
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
results = []
|
| 375 |
+
top_k = self.max_search_results_num // len(query_list)
|
| 376 |
+
for query in query_list:
|
| 377 |
+
payload = {
|
| 378 |
+
"messages": [{"role": "user", "content": query}],
|
| 379 |
+
"resource_type_filter": [{"type": "web", "top_k": top_k}]
|
| 380 |
+
}
|
| 381 |
+
response = requests.post(self.web_search_service_url, headers=headers, json=payload)
|
| 382 |
+
|
| 383 |
+
if response.status_code == 200:
|
| 384 |
+
response = response.json()
|
| 385 |
+
self.logger.info(response)
|
| 386 |
+
results.append(response["references"])
|
| 387 |
+
else:
|
| 388 |
+
self.logger.info(f"请求失败,状态码: {response.status_code}")
|
| 389 |
+
self.logger.info(response.text)
|
| 390 |
+
return results
|
crawl_utils.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
|
| 2 |
+
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
CrawlUtils is a class that provides utility methods for web crawling and processing.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import logging
|
| 20 |
+
import re
|
| 21 |
+
from crawl4ai import AsyncWebCrawler, CacheMode, CrawlerRunConfig, DefaultMarkdownGenerator, PruningContentFilter
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class CrawlUtils(object):
|
| 25 |
+
"""
|
| 26 |
+
Provides web crawling and content extraction utilities with intelligent filtering.
|
| 27 |
+
Features include asynchronous crawling, content pruning, markdown generation,
|
| 28 |
+
and configurable link/media filtering. Uses crawl4ai library for core functionality.
|
| 29 |
+
"""
|
| 30 |
+
def __init__(self):
|
| 31 |
+
"""Initialize the CrawlUtils instance."""
|
| 32 |
+
self.logger = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
# Configure content filter - uses pruning algorithm to filter page content
|
| 35 |
+
content_filter = PruningContentFilter(
|
| 36 |
+
threshold=0.48,
|
| 37 |
+
threshold_type="fixed"
|
| 38 |
+
)
|
| 39 |
+
# Configure markdown generator, apply the above content filter to generate "fit_markdown"
|
| 40 |
+
md_generator = DefaultMarkdownGenerator(
|
| 41 |
+
content_filter=content_filter
|
| 42 |
+
)
|
| 43 |
+
# Configure crawler run parameters
|
| 44 |
+
self.run_config = CrawlerRunConfig(
|
| 45 |
+
# 20 seconds page timeout
|
| 46 |
+
page_timeout=20000,
|
| 47 |
+
|
| 48 |
+
# Filtering
|
| 49 |
+
word_count_threshold=10,
|
| 50 |
+
excluded_tags=["nav", "footer", "aside", "header", "script", "style", "iframe", "meta"],
|
| 51 |
+
exclude_external_links=True,
|
| 52 |
+
exclude_internal_links=True,
|
| 53 |
+
exclude_social_media_links=True,
|
| 54 |
+
exclude_external_images=True,
|
| 55 |
+
only_text=True,
|
| 56 |
+
|
| 57 |
+
# Markdown generation
|
| 58 |
+
markdown_generator=md_generator,
|
| 59 |
+
|
| 60 |
+
# Cache
|
| 61 |
+
cache_mode=CacheMode.BYPASS
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
async def get_webpage_text(self, url: str) -> str:
|
| 65 |
+
"""
|
| 66 |
+
Asynchronously fetches and cleans webpage content from given URL using configured crawler.
|
| 67 |
+
Applies content filtering, markdown conversion, and text cleaning (removing undefined,
|
| 68 |
+
excess whitespace, tabs). Returns None if error occurs.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
url (str): The URL to retrieve the text from.
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
str: The plain text retrieved from the specified URL.
|
| 75 |
+
"""
|
| 76 |
+
try:
|
| 77 |
+
async with AsyncWebCrawler() as crawler:
|
| 78 |
+
result = await crawler.arun(
|
| 79 |
+
url=url,
|
| 80 |
+
config=self.run_config
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
webpage_text = result.markdown.fit_markdown
|
| 84 |
+
self.logger.info("Webpage Text: \n{}".format(webpage_text))
|
| 85 |
+
|
| 86 |
+
# Clean up the text
|
| 87 |
+
cleaned_text = webpage_text.replace("undefined", "")
|
| 88 |
+
cleaned_text = re.sub(r'(\n\s*){3,}', '\n\n', cleaned_text)
|
| 89 |
+
cleaned_text = re.sub(r'[\r\t]', '', cleaned_text)
|
| 90 |
+
cleaned_text = re.sub(r' +', ' ', cleaned_text)
|
| 91 |
+
cleaned_text = re.sub(r'^\s+|\s+$', '', cleaned_text, flags=re.MULTILINE)
|
| 92 |
+
return cleaned_text.strip()
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
self.logger.info("Error: {}".format(e))
|
| 96 |
+
return None
|