Merge branch 'dev' into hugo
This commit is contained in:
commit
3d4b2647ae
21 files changed
+491
-158
No files matched your search
+19
-6
@@ -1,4 +1,5 @@
|
||||
ARG PYTHON_BASE_IMAGE=python:3.12-slim
|
||||
# syntax=docker/dockerfile:1.4
|
||||
ARG PYTHON_BASE_IMAGE=python:3.12-slim-bookworm
|
||||
FROM ${PYTHON_BASE_IMAGE}
|
||||
|
||||
ARG APT_MIRROR=https://mirrors.aliyun.com
|
||||
@@ -7,7 +8,9 @@ ARG PIP_EXTRA_INDEX_URL
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN set -eux; \
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
--mount=type=cache,target=/var/lib/apt,sharing=locked \
|
||||
set -eux; \
|
||||
if [ -f /etc/apt/sources.list.d/debian.sources ]; then \
|
||||
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list.d/debian.sources; \
|
||||
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list.d/debian.sources; \
|
||||
@@ -16,19 +19,30 @@ RUN set -eux; \
|
||||
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list; \
|
||||
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list; \
|
||||
fi; \
|
||||
apt-get update && apt-get install -y \
|
||||
apt-get update && apt-get install -y --no-install-recommends \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
libxcb1 \
|
||||
libx11-6 \
|
||||
libxext6 \
|
||||
libreoffice \
|
||||
libreoffice-nogui \
|
||||
fonts-noto-cjk \
|
||||
curl \
|
||||
ca-certificates \
|
||||
gnupg \
|
||||
unixodbc-dev \
|
||||
&& install -d -m 0755 /etc/apt/keyrings \
|
||||
&& curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor -o /etc/apt/keyrings/microsoft-prod.gpg \
|
||||
&& chmod a+r /etc/apt/keyrings/microsoft-prod.gpg \
|
||||
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/microsoft-prod.gpg] https://packages.microsoft.com/debian/12/prod bookworm main" > /etc/apt/sources.list.d/mssql-release.list \
|
||||
&& apt-get update \
|
||||
&& ACCEPT_EULA=Y apt-get install -y --no-install-recommends msodbcsql18 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python dependencies
|
||||
COPY backend/requirements.txt .
|
||||
RUN set -eux; \
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
set -eux; \
|
||||
PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \
|
||||
if [ -n "${PIP_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \
|
||||
@@ -55,4 +69,3 @@ EXPOSE 5000
|
||||
# Start Gunicorn
|
||||
# Using the config file we created earlier
|
||||
CMD ["gunicorn", "-c", "deploy/gunicorn_config.py", "run:app"]
|
||||
|
||||
@@ -604,8 +604,11 @@ def chat_completions():
|
||||
return jsonify({'error': 'Missing user or agent context'}), 500
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.plm_oracle import PLMOracleService
|
||||
|
||||
if kb_type == 'ERP知识库':
|
||||
if PLMOracleService.supports(query, agent):
|
||||
generator = PLMOracleService.stream_chat(query, user, agent, conversation_id)
|
||||
elif kb_type == 'ERP知识库':
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ class HRLeaveSQLServerService:
|
||||
"明细",
|
||||
"查询",
|
||||
)
|
||||
_STRONG_BALANCE_PATTERNS = (
|
||||
r"(?:假期|年假|育儿假|休假).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少)",
|
||||
r"(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:假期|年假|育儿假|休假)",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def supports(query: str) -> bool:
|
||||
@@ -50,6 +54,8 @@ class HRLeaveSQLServerService:
|
||||
return False
|
||||
if any(keyword in text for keyword in HRLeaveSQLServerService._PROCESS_KEYWORDS):
|
||||
return False
|
||||
if any(re.search(pattern, text) for pattern in HRLeaveSQLServerService._STRONG_BALANCE_PATTERNS):
|
||||
return True
|
||||
if not any(keyword in text for keyword in HRLeaveSQLServerService._SELF_KEYWORDS):
|
||||
return False
|
||||
if any(keyword in text for keyword in HRLeaveSQLServerService._BALANCE_KEYWORDS):
|
||||
@@ -198,22 +204,14 @@ WHERE c002001 = ?
|
||||
return str(datetime.now().year)
|
||||
|
||||
@classmethod
|
||||
def _render_section(cls, title: str, record: dict | None, requested_year: int | None) -> str:
|
||||
def _render_table_row(cls, index: int, title: str, record: dict | None, requested_year: int | None) -> str:
|
||||
response_year = cls._resolve_response_year(record, requested_year)
|
||||
if not record:
|
||||
return (
|
||||
f"### {title}\n\n"
|
||||
f"暂未查询到您 {response_year} 年度的{title}记录。"
|
||||
)
|
||||
remaining = cls._format_quota(record.get("remaining_hours"))
|
||||
return (
|
||||
f"### {title}\n\n"
|
||||
f"您当前{title}剩余额度为 {remaining}。\n"
|
||||
f"- 年度:{response_year}\n"
|
||||
f"- 年度可休:{cls._format_quota(record.get('total_hours'))}\n"
|
||||
f"- 已休:{cls._format_quota(record.get('used_hours'))}\n"
|
||||
f"- 当前剩余:{remaining}"
|
||||
)
|
||||
return f"| {index} | {title} | {response_year} | 暂无数据 | 暂无数据 | 暂无数据 |"
|
||||
total = cls._format_quota(record.get('total_hours'))
|
||||
used = cls._format_quota(record.get('used_hours'))
|
||||
remaining = cls._format_quota(record.get('remaining_hours'))
|
||||
return f"| {index} | {title} | {response_year} | {total} | {used} | {remaining} |"
|
||||
|
||||
@classmethod
|
||||
def _build_result_text(cls, leave_type: str, requested_year: int | None, annual_result, childcare_result):
|
||||
@@ -235,11 +233,19 @@ WHERE c002001 = ?
|
||||
)
|
||||
sections = [
|
||||
f"您好,已为您查询到 {intro_year} 年度假期情况:",
|
||||
"",
|
||||
"| 序号 | 假别 | 年度 | 可休 | 已休 | 当前剩余 |",
|
||||
"| :---: | :---: | :---: | :---: | :---: | :---: |",
|
||||
]
|
||||
|
||||
index = 1
|
||||
if leave_type in ("annual", "all"):
|
||||
sections.extend(["", cls._render_section("年假", annual_record, requested_year)])
|
||||
sections.append(cls._render_table_row(index, "年假", annual_record, requested_year))
|
||||
index += 1
|
||||
if leave_type in ("childcare", "all"):
|
||||
sections.extend(["", cls._render_section("育儿假", childcare_record, requested_year)])
|
||||
sections.append(cls._render_table_row(index, "育儿假", childcare_record, requested_year))
|
||||
index += 1
|
||||
|
||||
sections.extend(
|
||||
[
|
||||
"",
|
||||
|
||||
@@ -214,6 +214,13 @@ class OALeaveWorkflowService:
|
||||
if show_node is None:
|
||||
show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue')
|
||||
show_node.text = str(show_value)
|
||||
|
||||
# 强制将字段设为可编辑和可见,防止OA流程节点中被配置为只读导致无法写入
|
||||
for tag in ['edit', 'view']:
|
||||
node = field.find(f'wf:{tag}', NS)
|
||||
if node is None:
|
||||
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
|
||||
node.text = 'true'
|
||||
|
||||
@classmethod
|
||||
def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None:
|
||||
@@ -290,11 +297,11 @@ class OALeaveWorkflowService:
|
||||
cls._set_text(request_info, './/wf:workflowBaseInfo/wf:workflowId', workflow_id)
|
||||
|
||||
cls._set_field(request_info, 'requestname', value=request_name, show_value=request_name)
|
||||
cls._set_field(request_info, 'tdrgh', value=filler['employee_id'], show_value=filler['employee_id'])
|
||||
cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'], show_value=applicant['employee_id'])
|
||||
cls._set_field(request_info, 'tdrgh', value=filler['employee_id'])
|
||||
cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'])
|
||||
cls._set_field(request_info, 'tdrxm', value=filler['user_id'], show_value=filler['name'])
|
||||
cls._set_field(request_info, 'sqrxm', value=applicant['user_id'], show_value=applicant['name'])
|
||||
cls._set_field(request_info, 'dlrgh', value=agent['employee_id'], show_value=agent['employee_id'])
|
||||
cls._set_field(request_info, 'dlrgh', value=agent['employee_id'])
|
||||
cls._set_field(request_info, 'dlrxm', value=agent['user_id'], show_value=agent['name'])
|
||||
cls._set_field(request_info, 'dlrlogid', value=agent['user_id'], show_value=agent['user_id'])
|
||||
cls._set_field(request_info, 'jb', value=leave_type_code, show_value=leave_type_label)
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ChatLog, db
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
|
||||
class PLMOracleService:
|
||||
_ALLOWED_AGENT_NAMES = {"通用入口", "生产sop"}
|
||||
_MAX_RESULT_ROWS = 50
|
||||
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
|
||||
_EXPLICIT_LABEL_PATTERN = re.compile(
|
||||
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_RELATIONAL_SQL = """
|
||||
select *
|
||||
from bi_file endb
|
||||
where endb.revisionguid in (
|
||||
select bb.revisionguid
|
||||
from (
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b
|
||||
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = cad.masterfk
|
||||
and cad.latestrevision like '%m%'
|
||||
and b.revisionguid = cad.guid
|
||||
union
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b
|
||||
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = cad.masterfk
|
||||
and cad.latestrevision like '%m%'
|
||||
and b.revisionguid = cad.guid
|
||||
union
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v,
|
||||
StructureObject_0 str,
|
||||
document_0 doc,
|
||||
bi_file b
|
||||
where v.name in ('RelatedDoc')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = doc.masterfk
|
||||
and doc.latestrevision like '%m%'
|
||||
and b.revisionguid = doc.guid
|
||||
) bb,
|
||||
item_0 i
|
||||
where bb.end1 = i.guid
|
||||
and i.id = :item_id
|
||||
and i.latestrevision like '%m%'
|
||||
)
|
||||
and endb.lastaccesstime is not null
|
||||
"""
|
||||
_FILENAME_SQL = """
|
||||
select *
|
||||
from bi_file
|
||||
where upper(name) like :name_pattern
|
||||
and lastaccesstime is not null
|
||||
order by lastaccesstime desc nulls last
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def supports(cls, query: str, agent) -> bool:
|
||||
return bool(cls.extract_material_no(query) and cls._is_supported_agent(agent))
|
||||
|
||||
@classmethod
|
||||
def extract_material_no(cls, query: str) -> str | None:
|
||||
text = str(query or "").strip().upper()
|
||||
if not text:
|
||||
return None
|
||||
|
||||
explicit = cls._EXPLICIT_LABEL_PATTERN.search(text)
|
||||
if explicit:
|
||||
return explicit.group(1).strip().upper()
|
||||
|
||||
direct_match = cls._MATERIAL_PATTERN.fullmatch(text)
|
||||
if direct_match:
|
||||
return direct_match.group(0).upper()
|
||||
|
||||
for match in cls._MATERIAL_PATTERN.finditer(text):
|
||||
candidate = match.group(0).upper()
|
||||
if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _is_supported_agent(cls, agent) -> bool:
|
||||
name = str(getattr(agent, "name", "") or "").strip().lower().replace(" ", "")
|
||||
return name in cls._ALLOWED_AGENT_NAMES
|
||||
|
||||
@staticmethod
|
||||
def _get_connect_kwargs() -> dict:
|
||||
dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip()
|
||||
host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip()
|
||||
port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip())
|
||||
service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip()
|
||||
sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip()
|
||||
|
||||
kwargs = {
|
||||
"user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(),
|
||||
"password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(),
|
||||
}
|
||||
if dsn:
|
||||
kwargs["dsn"] = dsn
|
||||
return kwargs
|
||||
|
||||
import oracledb
|
||||
|
||||
if service_name:
|
||||
kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name)
|
||||
else:
|
||||
kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid)
|
||||
return kwargs
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc
|
||||
|
||||
oracle_client_dir = Text2SQLService._get_oracle_client_dir()
|
||||
Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir)
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
return oracledb.connect(**cls._get_connect_kwargs())
|
||||
|
||||
@classmethod
|
||||
def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]:
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(sql, params)
|
||||
columns = [col[0] for col in cursor.description] if cursor.description else []
|
||||
rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1)
|
||||
return columns, rows
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]:
|
||||
try:
|
||||
columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no)
|
||||
if rows:
|
||||
return columns, rows, "relational"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc)
|
||||
|
||||
columns, rows = cls._execute_query(
|
||||
cls._FILENAME_SQL,
|
||||
name_pattern=f"{material_no.upper()}%",
|
||||
)
|
||||
return columns, rows, "filename_fallback"
|
||||
|
||||
@staticmethod
|
||||
def _format_datetime(value) -> str:
|
||||
if value is None:
|
||||
return "-"
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return str(value)
|
||||
|
||||
@staticmethod
|
||||
def _format_size(value) -> str:
|
||||
if value in (None, ""):
|
||||
return "-"
|
||||
try:
|
||||
size = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return str(value)
|
||||
if size < 1024:
|
||||
return f"{size} B"
|
||||
if size < 1024 * 1024:
|
||||
return f"{size / 1024:.1f} KB"
|
||||
return f"{size / 1024 / 1024:.2f} MB"
|
||||
|
||||
@classmethod
|
||||
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
|
||||
if not rows:
|
||||
return f"已在 PLM 中查询料号 `{material_no}`,未找到符合条件的相关资料。"
|
||||
|
||||
overflow = len(rows) > cls._MAX_RESULT_ROWS
|
||||
visible_rows = rows[: cls._MAX_RESULT_ROWS]
|
||||
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
|
||||
|
||||
def pick(row: tuple, column_name: str, default: str = "-") -> str:
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return default
|
||||
value = row[idx]
|
||||
if column_name.upper() in {"CREATETIME", "LASTACCESSTIME"}:
|
||||
return cls._format_datetime(value)
|
||||
if column_name.upper() == "FILESIZE":
|
||||
return cls._format_size(value)
|
||||
return "-" if value in (None, "") else str(value)
|
||||
|
||||
lines = [
|
||||
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
|
||||
+ ("(仅展示前 50 条)" if overflow else "。"),
|
||||
"",
|
||||
"| 序号 | 文件名 | 扩展名 | 文件类型 | 文件大小 | 相对路径 | 最后访问时间 |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- |",
|
||||
]
|
||||
for idx, row in enumerate(visible_rows, start=1):
|
||||
lines.append(
|
||||
f"| {idx} | {pick(row, 'NAME')} | {pick(row, 'EXTENTIONNAME')} | {pick(row, 'FILETYPE')} | "
|
||||
f"{pick(row, 'FILESIZE')} | {pick(row, 'RELATIVEPATH')} | {pick(row, 'LASTACCESSTIME')} |"
|
||||
)
|
||||
|
||||
if overflow:
|
||||
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
|
||||
return "\n".join(lines)
|
||||
|
||||
@classmethod
|
||||
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None):
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
|
||||
material_no = cls.extract_material_no(query)
|
||||
|
||||
try:
|
||||
if not material_no:
|
||||
raise RuntimeError("未识别到有效料号,请输入类似 F3-A12M290000019 的料号。")
|
||||
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': f'已识别料号 `{material_no}`,正在查询 PLM 资料,请稍候...\\n'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
columns, rows, query_mode = cls._query_files(material_no)
|
||||
answer = cls._build_answer(material_no, columns, rows)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=final_conversation_id,
|
||||
query=query,
|
||||
answer=answer,
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
payload={
|
||||
"material_no": material_no,
|
||||
"row_count": min(len(rows), cls._MAX_RESULT_ROWS),
|
||||
"query_mode": query_mode,
|
||||
},
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.error("Failed to log PLM chat: %s", exc)
|
||||
db.session.rollback()
|
||||
|
||||
end_data = {
|
||||
"event": "message_end",
|
||||
"answer": answer,
|
||||
"replace_answer": True,
|
||||
"chat_log_id": chat_log_id,
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception("[plm-oracle] stream_chat failed query=%s", query)
|
||||
error_data = {
|
||||
"event": "error",
|
||||
"message": str(exc) or "PLM 查询失败",
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
@@ -2,13 +2,11 @@ import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
class Text2SQLService:
|
||||
_schema_text = None
|
||||
_oracle_client_initialized = False
|
||||
_jdbc_driver_url = "https://repo1.maven.org/maven2/com/oracle/database/jdbc/ojdbc8/19.25.0.0/ojdbc8-19.25.0.0.jar"
|
||||
|
||||
@staticmethod
|
||||
def _backend_dir() -> str:
|
||||
@@ -18,12 +16,19 @@ class Text2SQLService:
|
||||
def _project_root(cls) -> str:
|
||||
return os.path.dirname(cls._backend_dir())
|
||||
|
||||
@classmethod
|
||||
def _resolve_project_path(cls, path_value: str) -> str:
|
||||
normalized = os.path.normpath(path_value)
|
||||
if os.path.isabs(normalized):
|
||||
return normalized
|
||||
return os.path.normpath(os.path.join(cls._project_root(), normalized))
|
||||
|
||||
@classmethod
|
||||
def _find_oracle_client_dir(cls) -> str | None:
|
||||
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
|
||||
candidate_roots = []
|
||||
if env_dir:
|
||||
candidate_roots.append(env_dir)
|
||||
candidate_roots.append(cls._resolve_project_path(env_dir))
|
||||
candidate_roots.extend([
|
||||
os.path.join(cls._backend_dir(), 'oracle_client'),
|
||||
os.path.join(cls._project_root(), 'oracle_client'),
|
||||
@@ -154,8 +159,10 @@ class Text2SQLService:
|
||||
@classmethod
|
||||
def _get_oracle_client_dir(cls) -> str | None:
|
||||
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
|
||||
if env_dir and os.path.exists(env_dir):
|
||||
return env_dir
|
||||
if env_dir:
|
||||
resolved_env_dir = cls._resolve_project_path(env_dir)
|
||||
if os.path.exists(resolved_env_dir):
|
||||
return resolved_env_dir
|
||||
|
||||
linux_candidates = [
|
||||
"/opt/oracle/instantclient",
|
||||
@@ -195,78 +202,6 @@ class Text2SQLService:
|
||||
oracledb.init_oracle_client()
|
||||
cls._oracle_client_initialized = True
|
||||
|
||||
@classmethod
|
||||
def _jdbc_dir(cls) -> Path:
|
||||
return Path(cls._backend_dir()) / "jdbc"
|
||||
|
||||
@classmethod
|
||||
def _ensure_jdbc_driver_jar(cls) -> str:
|
||||
env_path = (os.getenv("ERP_JDBC_JAR") or "").strip()
|
||||
if env_path and os.path.exists(env_path):
|
||||
return env_path
|
||||
|
||||
jar_dir = cls._jdbc_dir()
|
||||
jar_dir.mkdir(parents=True, exist_ok=True)
|
||||
jar_path = jar_dir / "ojdbc8-19.25.0.0.jar"
|
||||
if jar_path.exists():
|
||||
return str(jar_path)
|
||||
|
||||
import requests
|
||||
|
||||
driver_url = os.getenv("ERP_JDBC_JAR_URL", cls._jdbc_driver_url).strip() or cls._jdbc_driver_url
|
||||
with requests.get(driver_url, stream=True, timeout=120) as resp:
|
||||
resp.raise_for_status()
|
||||
with open(jar_path, "wb") as f:
|
||||
for chunk in resp.iter_content(chunk_size=1024 * 256):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
return str(jar_path)
|
||||
|
||||
@staticmethod
|
||||
def _dsn_to_jdbc_url(dsn: str) -> str:
|
||||
dsn = (dsn or "").strip()
|
||||
if not dsn:
|
||||
raise ValueError("ERP_DB_DSN is empty")
|
||||
if dsn.startswith("jdbc:oracle:thin:@"):
|
||||
return dsn
|
||||
if dsn.startswith("("):
|
||||
return f"jdbc:oracle:thin:@{dsn}"
|
||||
match = re.match(r"^(?P<host>[^:/]+)(?::(?P<port>\d+))?/(?P<service>.+)$", dsn)
|
||||
if match:
|
||||
host = match.group("host")
|
||||
port = match.group("port") or "1521"
|
||||
service = match.group("service")
|
||||
return f"jdbc:oracle:thin:@//{host}:{port}/{service}"
|
||||
return f"jdbc:oracle:thin:@{dsn}"
|
||||
|
||||
@classmethod
|
||||
def _execute_sql_via_jdbc(cls, sql: str, user: str, password: str, dsn: str):
|
||||
import jaydebeapi
|
||||
|
||||
jar_path = cls._ensure_jdbc_driver_jar()
|
||||
jdbc_url = cls._dsn_to_jdbc_url(dsn)
|
||||
connection = jaydebeapi.connect(
|
||||
"oracle.jdbc.OracleDriver",
|
||||
jdbc_url,
|
||||
{
|
||||
"user": user,
|
||||
"password": password,
|
||||
"oracle.jdbc.timezoneAsRegion": "false",
|
||||
},
|
||||
jar_path,
|
||||
)
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(sql)
|
||||
columns = [col[0] for col in cursor.description] if cursor.description else []
|
||||
rows = cursor.fetchall() if columns else []
|
||||
return columns, rows
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_schema(cls):
|
||||
if cls._schema_text is None:
|
||||
@@ -532,12 +467,7 @@ class Text2SQLService:
|
||||
except Exception as e:
|
||||
error_text = str(e)
|
||||
if current_app:
|
||||
current_app.logger.warning(f"Oracle direct query failed, trying JDBC fallback: {error_text}")
|
||||
if "DPY-3010" in error_text or "DPI-1047" in error_text:
|
||||
try:
|
||||
return cls._execute_sql_via_jdbc(sql, user, password, dsn)
|
||||
except Exception as jdbc_error:
|
||||
return ["Error"], [[f"{error_text} | JDBC fallback failed: {jdbc_error}"]]
|
||||
current_app.logger.warning(f"Oracle direct query failed: {error_text}")
|
||||
return ["Error"], [[error_text]]
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -15,7 +15,8 @@ worker_class = "gevent"
|
||||
|
||||
# 进程数
|
||||
# 公式: 2 * CPU核心数 + 1
|
||||
workers = multiprocessing.cpu_count() * 2 + 1
|
||||
# workers = multiprocessing.cpu_count() * 2 + 1
|
||||
min(int(os.getenv("GUNICORN_WORKERS", "9")), multiprocessing.cpu_count() * 2 + 1)
|
||||
|
||||
# 每个 Worker 的最大并发连接数
|
||||
worker_connections = 1000
|
||||
|
||||
@@ -4,6 +4,7 @@ backend/gunicorn_config.py
|
||||
生产环境 Gunicorn 配置 (支持高并发)
|
||||
"""
|
||||
import multiprocessing
|
||||
import os
|
||||
|
||||
# 绑定地址
|
||||
bind = "0.0.0.0:8000"
|
||||
@@ -12,7 +13,7 @@ bind = "0.0.0.0:8000"
|
||||
worker_class = "gevent"
|
||||
|
||||
# Worker 数量:通常 CPU 核数 * 2 + 1
|
||||
workers = multiprocessing.cpu_count() * 2 + 1
|
||||
workers = min(int(os.getenv("GUNICORN_WORKERS", "9")), multiprocessing.cpu_count() * 2 + 1)
|
||||
|
||||
# 核心:每个 Worker 最大并发连接数
|
||||
# Gevent 下这个值可以设置得很高,支持海量 SSE 连接
|
||||
|
||||
@@ -16,9 +16,8 @@ pycryptodome
|
||||
PyJWT
|
||||
cryptography
|
||||
oracledb
|
||||
jaydebeapi
|
||||
JPype1
|
||||
pyodbc
|
||||
pyodbc>=5.1.0
|
||||
zeep>=4.2.1
|
||||
pywin32; sys_platform == "win32"
|
||||
|
||||
# File Parsing & edkb_system dependencies from xinxin2
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
|
||||
|
||||
def test_supports_strong_leave_balance_intent_without_self_pronoun():
|
||||
assert HRLeaveSQLServerService.supports("假期还有多少")
|
||||
assert HRLeaveSQLServerService.supports("还有多少假期")
|
||||
assert HRLeaveSQLServerService.supports("年假还有多少天")
|
||||
assert HRLeaveSQLServerService.supports("还有多少年假")
|
||||
|
||||
|
||||
def test_supports_rejects_leave_process_questions():
|
||||
assert not HRLeaveSQLServerService.supports("假期怎么申请")
|
||||
assert not HRLeaveSQLServerService.supports("年假制度是什么")
|
||||
Reference in new issue
Block a user