fix(etl & ocr): stabilize scud_export syntax/imports, revert to qwen2.5vl:7b-q8_0
This commit is contained in:
@@ -8,6 +8,7 @@ ROLE: Нативный оркестратор диалога, диспетчер
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import logging
|
||||
@@ -146,6 +147,7 @@ def process_chat_message(
|
||||
f" - База знаний и регламенты -> db_get_rules\n"
|
||||
f" - Аномалии СКУД/1С -> db_get_anomalies\n"
|
||||
f" - Справка -> db_get_reference\n"
|
||||
f" - Распознавание PDF/сканов и экспорт в Word -> office_pdf_to_word\n"
|
||||
f"3. ЗАДАЧИ:\n"
|
||||
f" - При любых запросах на просмотр задач (включая опечатки вроде 'змдачи', 'таски', 'дела', 'покажи задачи') — "
|
||||
f"ТЫ ОБЯЗАН СРАЗУ ВЫЗВАТЬ db_get_tasks без лишних вопросов!\n"
|
||||
@@ -316,6 +318,46 @@ def process_chat_message(
|
||||
]
|
||||
}
|
||||
|
||||
# 4.1 Распознавание текста.
|
||||
elif fn_name == "office_pdf_to_word":
|
||||
# Извлекаем путь к файлу из сохраненных данных сессии
|
||||
attached_file_path = state_data.get("last_uploaded_filepath")
|
||||
original_name = state_data.get("last_uploaded_filename", "document.pdf")
|
||||
|
||||
# Страховочный fallback: если стейт очистился, ищем последний файл в data/uploads/
|
||||
if not attached_file_path or not os.path.exists(attached_file_path):
|
||||
from config import BASE_DIR
|
||||
uploads_dir = os.path.join(BASE_DIR, "data", "uploads")
|
||||
if os.path.exists(uploads_dir):
|
||||
files = [os.path.join(uploads_dir, f) for f in os.listdir(uploads_dir) if f.lower().endswith(".pdf")]
|
||||
if files:
|
||||
files.sort(key=os.path.getmtime, reverse=True)
|
||||
attached_file_path = files[0]
|
||||
original_name = os.path.basename(attached_file_path)
|
||||
|
||||
if not attached_file_path or not os.path.exists(attached_file_path):
|
||||
reply_text = "⚠️ Прикрепленный файл не найден. Пожалуйста, прикрепите PDF-файл к сообщению повторно."
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=1)[cite: 2]
|
||||
return reply_text, db_get_chat_history(session_id), None[cite: 2]
|
||||
|
||||
from services.office.service import convert_pdf_to_word_service
|
||||
office_res = convert_pdf_to_word_service(attached_file_path, original_name)
|
||||
|
||||
reply_text = (
|
||||
f"📄 **{office_res['message']}**\n\n"
|
||||
f"**Фрагмент первой страницы:**\n"
|
||||
f"```text\n{office_res['preview_text']}...\n```"
|
||||
)
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=0)[cite: 2]
|
||||
|
||||
action_payload = {
|
||||
"type": "FILE_DOWNLOAD_CARD",
|
||||
"filename": office_res["filename"],
|
||||
"download_url": office_res["download_url"],
|
||||
"tasks_count": f"{office_res['total_pages']} стр."
|
||||
}
|
||||
return reply_text, db_get_chat_history(session_id), action_payload[cite: 2]
|
||||
|
||||
# 5. Снапшоты СКУД
|
||||
elif fn_name == "db_get_snapshots":
|
||||
snapshots_res = db_get_snapshots(session_id=session_id, date_str=fn_args.get("date_str"), original_user_message=user_message)
|
||||
|
||||
@@ -244,6 +244,34 @@ def handle_fast_path_intercept(
|
||||
]
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 0.6 БЫСТРЫЙ ЭКСПОРТ PDF В WORD (FAST-PATH)
|
||||
# -------------------------------------------------------------------------
|
||||
fast_ocr_triggers = ["в ворд", "в word", "распознай в word", "распознай в ворд", "сделай ворд", "экспорт в word"]
|
||||
if any(msg_lower.startswith(t) or msg_lower == t for t in fast_ocr_triggers):
|
||||
state_data = session_state.get("data_json") if session_state else {}
|
||||
attached_file_path = state_data.get("last_uploaded_filepath")
|
||||
original_name = state_data.get("last_uploaded_filename", "document.pdf")
|
||||
|
||||
if attached_file_path and os.path.exists(attached_file_path) and original_name.lower().endswith(".pdf"):
|
||||
from services.office.service import convert_pdf_to_word_service
|
||||
office_res = convert_pdf_to_word_service(attached_file_path, original_name)
|
||||
|
||||
reply = (
|
||||
f"⚡ **[Fast-Path] {office_res['message']}**\n\n"
|
||||
f"**Фрагмент первой страницы:**\n"
|
||||
f"```text\n{office_res['preview_text']}...\n```"
|
||||
)
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=0)
|
||||
|
||||
action_payload = {
|
||||
"type": "FILE_DOWNLOAD_CARD",
|
||||
"filename": office_res["filename"],
|
||||
"download_url": office_res["download_url"],
|
||||
"tasks_count": f"{office_res['total_pages']} стр."
|
||||
}
|
||||
return reply, db_get_chat_history(session_id), action_payload
|
||||
|
||||
if not session_state:
|
||||
return None
|
||||
|
||||
|
||||
@@ -5,22 +5,23 @@ ROLE: Транспортный клиент HTTP взаимодействия с
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
# ANCHOR[OLLAMA_CLIENT_IMPORTS]
|
||||
import json
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import logging
|
||||
from typing import Dict, Any, Optional
|
||||
import config
|
||||
|
||||
logger = logging.getLogger("OLLAMA_CLIENT")
|
||||
|
||||
OLLAMA_URL = "http://10.121.17.227:11434/api/chat"
|
||||
TEXT_MODEL = "qwen2.5:14b"
|
||||
VISION_MODEL = "qwen2.5vl:7b-q8_0"
|
||||
# Чистый адрес API chat
|
||||
OLLAMA_URL = getattr(config, "OLLAMA_CHAT_URL", "http://10.121.17.227:11434/api/chat")
|
||||
TEXT_MODEL = getattr(config, "OLLAMA_MODEL", "qwen2.5:14b")
|
||||
VISION_MODEL = getattr(config, "VISION_MODEL", "qwen2.5vl:7b-q8_0")
|
||||
|
||||
LLM_OPTIONS = {
|
||||
"num_predict": 8192,
|
||||
"num_ctx": 8192,
|
||||
"num_ctx": 16384, # Увеличенный контекст под сканы высокого разрешения
|
||||
"temperature": 0.0,
|
||||
"repeat_penalty": 1.0,
|
||||
"presence_penalty": 0.0,
|
||||
@@ -28,18 +29,22 @@ LLM_OPTIONS = {
|
||||
}
|
||||
|
||||
|
||||
# ANCHOR[OLLAMA_REQUEST_DISPATCHER]
|
||||
def call_ollama_chat(
|
||||
messages: list,
|
||||
tools: Optional[list] = None,
|
||||
is_vision: bool = False,
|
||||
timeout: int = 120
|
||||
timeout: int = 240,
|
||||
model: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Отправляет подготовленный массив сообщений в API Ollama.
|
||||
Возвращает разобранный словарь сообщения ответа или генерирует исключение.
|
||||
Отправляет массив сообщений в API Ollama.
|
||||
Поддерживает явное указание модели (например, qwen3-vl:8b).
|
||||
"""
|
||||
model_name = VISION_MODEL if is_vision else TEXT_MODEL
|
||||
if model:
|
||||
model_name = model
|
||||
else:
|
||||
model_name = VISION_MODEL if is_vision else TEXT_MODEL
|
||||
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": messages,
|
||||
|
||||
@@ -33,4 +33,21 @@ def inject_tools_if_needed(user_message: str, raw_reply: str, existing_tool_call
|
||||
Модель управляется через TOOLS_SCHEMA и системный контекст.
|
||||
Любые синтетические перехваты текста регулярными выражениями отключены согласно ROADMAP.
|
||||
"""
|
||||
return existing_tool_calls
|
||||
return existing_tool_calls
|
||||
|
||||
def clean_output(text: str) -> str:
|
||||
"""Очищает маркеры форматирования и слова-паразиты."""
|
||||
if not text:
|
||||
return ""
|
||||
cleaned = text.strip()
|
||||
|
||||
# Жесткое пресечение слов-паразитов в начале сообщения
|
||||
bad_prefixes = [
|
||||
"почемучка,", "почемучка", "почемучто,", "почемучто",
|
||||
"спасибо за обращение", "здравствуйте, почемучка"
|
||||
]
|
||||
for bp in bad_prefixes:
|
||||
if cleaned.lower().startswith(bp):
|
||||
cleaned = cleaned[len(bp):].lstrip(" ,.:!\n")
|
||||
|
||||
return cleaned
|
||||
@@ -1,88 +1,127 @@
|
||||
import base64
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: modules/web_api/llm/file_parser.py
|
||||
ROLE: Изолированный сервис извлечения содержимого из PDF, таблиц и сканов.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import base64
|
||||
import logging
|
||||
import pandas as pd
|
||||
from typing import Dict, Any, List
|
||||
|
||||
logger = logging.getLogger("FILE_PARSER")
|
||||
|
||||
def extract_text_from_file(file_bytes: bytes, filename: str) -> dict:
|
||||
ext = os.path.splitext(filename)[1].lower()
|
||||
temp_filepath = f"/tmp/upload_{os.getpid()}_{filename}"
|
||||
|
||||
with open(temp_filepath, "wb") as f:
|
||||
f.write(file_bytes)
|
||||
|
||||
def extract_content_from_pdf(file_path: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Извлекает текст из многостраничного PDF.
|
||||
Если текстовый слой присутствует, собирает все страницы без обрезания.
|
||||
Если текст отсутствует (чистый скан), подготавливает страницы для Vision OCR.
|
||||
"""
|
||||
text_pages = []
|
||||
|
||||
# 1. Попытка чтения через pypdf
|
||||
try:
|
||||
# 1. ИЗОБРАЖЕНИЯ (.png, .jpg, .jpeg, .bmp, .webp) -> Кодируем в Base64 для Vision LLM
|
||||
if ext in ['.png', '.jpg', '.jpeg', '.bmp', '.webp']:
|
||||
b64_str = base64.b64encode(file_bytes).decode('utf-8')
|
||||
return {
|
||||
"text": f"[ПРИКРЕПЛЕНО ИЗОБРАЖЕНИЕ: {filename}]",
|
||||
"image_b64": b64_str
|
||||
}
|
||||
|
||||
# 2. PDF ДОКУМЕНТЫ (Конвертируем 1-ю страницу в картинку для Vision LLM)
|
||||
elif ext == '.pdf':
|
||||
cmd = ['pdftotext', temp_filepath, '-']
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
pdf_text = res.stdout.strip()
|
||||
|
||||
img_prefix = f"/tmp/pdf_preview_{os.getpid()}"
|
||||
subprocess.run(['pdftoppm', '-png', '-r', '200', '-f', '1', '-l', '1', temp_filepath, img_prefix], check=True)
|
||||
|
||||
page_png = f"{img_prefix}-1.png"
|
||||
b64_str = None
|
||||
if os.path.exists(page_png):
|
||||
with open(page_png, "rb") as pf:
|
||||
b64_str = base64.b64encode(pf.read()).decode('utf-8')
|
||||
os.remove(page_png)
|
||||
|
||||
context_text = f"[ПРИКРЕПЛЕН ДОКУМЕНТ PDF: {filename}]"
|
||||
if pdf_text:
|
||||
context_text += f"\n\n[ЭЛЕКТРОННЫЙ ТЕКСТОВЫЙ СЛОЙ PDF]:\n{pdf_text}"
|
||||
|
||||
return {
|
||||
"text": context_text,
|
||||
"image_b64": b64_str
|
||||
}
|
||||
|
||||
# 3. ЭЛЕКТРОННЫЕ ТАБЛИЦЫ (.xlsx, .xls, .csv)
|
||||
elif ext in ['.xlsx', '.xls', '.csv']:
|
||||
if ext == '.csv':
|
||||
df = pd.read_csv(temp_filepath)
|
||||
else:
|
||||
df = pd.read_excel(temp_filepath)
|
||||
|
||||
total_rows = len(df)
|
||||
df_preview = df.head(100)
|
||||
table_str = df_preview.to_string(index=False)
|
||||
note = f"\n(Показано первых 100 строк из {total_rows})" if total_rows > 100 else ""
|
||||
return {
|
||||
"text": f"[СОДЕРЖИМОЕ ТАБЛИЦЫ {filename}]:\n{table_str}{note}",
|
||||
"image_b64": None
|
||||
}
|
||||
|
||||
# 4. ТЕКСТОВЫЕ ФАЙЛЫ
|
||||
elif ext in ['.txt', '.log', '.json', '.xml', '.md']:
|
||||
with open(temp_filepath, 'r', encoding='utf-8', errors='replace') as tf:
|
||||
return {
|
||||
"text": tf.read().strip(),
|
||||
"image_b64": None
|
||||
}
|
||||
|
||||
else:
|
||||
return {
|
||||
"text": f"[ОШИБКА: Формат {ext} не поддерживается]",
|
||||
"image_b64": None
|
||||
}
|
||||
|
||||
import pypdf
|
||||
reader = pypdf.PdfReader(file_path)
|
||||
for idx, page in enumerate(reader.pages, start=1):
|
||||
t = page.extract_text() or ""
|
||||
if t.strip():
|
||||
text_pages.append(f"--- Страница {idx} ---\n{t.strip()}")
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при анализе файла {filename}: {e}")
|
||||
logger.warning(f"Ошибка pypdf при чтении {file_path}: {e}")
|
||||
|
||||
full_text = "\n\n".join(text_pages).strip()
|
||||
|
||||
# 2. Если текста достаточно — отдаем чистый извлеченный текст
|
||||
if len(full_text) > 100:
|
||||
return {
|
||||
"text": f"[ОШИБКА ОБРАБОТКИ ФАЙЛА: {str(e)}]",
|
||||
"image_b64": None
|
||||
"has_text": True,
|
||||
"text": full_text,
|
||||
"image_b64": None,
|
||||
"pages_count": len(text_pages)
|
||||
}
|
||||
finally:
|
||||
if os.path.exists(temp_filepath):
|
||||
os.remove(temp_filepath)
|
||||
|
||||
# 3. Если текста мало или это чистый скан — рендерим первую страницу через PyMuPDF для Vision
|
||||
image_b64 = None
|
||||
try:
|
||||
import fitz # PyMuPDF
|
||||
doc = fitz.open(file_path)
|
||||
if len(doc) > 0:
|
||||
page = doc[0]
|
||||
pix = page.get_pixmap(dpi=150)
|
||||
image_b64 = base64.b64encode(pix.tobytes("png")).decode("utf-8")
|
||||
except Exception as e:
|
||||
logger.warning(f"Ошибка PyMuPDF при рендеринге страницы: {e}")
|
||||
|
||||
return {
|
||||
"has_text": bool(full_text),
|
||||
"text": full_text,
|
||||
"image_b64": image_b64,
|
||||
"pages_count": len(text_pages) if text_pages else 1
|
||||
}
|
||||
|
||||
|
||||
def parse_uploaded_file(file_path: str, filename: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Главная точка входа разбора входящего файла.
|
||||
"""
|
||||
ext = os.path.splitext(filename)[1].lower()
|
||||
|
||||
# 1. PDF
|
||||
if ext == ".pdf":
|
||||
pdf_res = extract_content_from_pdf(file_path)
|
||||
return {
|
||||
"context_text": pdf_res["text"],
|
||||
"image_b64": pdf_res["image_b64"],
|
||||
"type": "PDF",
|
||||
"is_pure_text": pdf_res["has_text"] and not pdf_res["image_b64"]
|
||||
}
|
||||
|
||||
# 2. Изображения (сканы / фотографии)
|
||||
elif ext in [".png", ".jpg", ".jpeg", ".webp", ".bmp"]:
|
||||
try:
|
||||
with open(file_path, "rb") as f:
|
||||
b64 = base64.b64encode(f.read()).decode("utf-8")
|
||||
return {
|
||||
"context_text": f"[Прикреплено изображение: {filename}]",
|
||||
"image_b64": b64,
|
||||
"type": "IMAGE",
|
||||
"is_pure_text": False
|
||||
}
|
||||
except Exception as e:
|
||||
return {"context_text": "", "image_b64": None, "type": "ERROR", "error": str(e)}
|
||||
|
||||
# 3. Электронные таблицы Excel / CSV
|
||||
elif ext in [".xlsx", ".xls", ".csv"]:
|
||||
try:
|
||||
import pandas as pd
|
||||
df = pd.read_csv(file_path) if ext == ".csv" else pd.read_excel(file_path)
|
||||
rows_cnt = len(df)
|
||||
preview = df.head(150).to_string(index=False)
|
||||
note = f"\n(Показано первых 150 строк из {rows_cnt})" if rows_cnt > 150 else ""
|
||||
return {
|
||||
"context_text": f"[Таблица {filename}]:\n{preview}{note}",
|
||||
"image_b64": None,
|
||||
"type": "SPREADSHEET",
|
||||
"is_pure_text": True
|
||||
}
|
||||
except Exception as e:
|
||||
return {"context_text": "", "image_b64": None, "type": "ERROR", "error": str(e)}
|
||||
|
||||
# 4. Текстовые файлы
|
||||
elif ext in [".txt", ".log", ".md", ".json", ".xml"]:
|
||||
try:
|
||||
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
||||
content = f.read()
|
||||
return {
|
||||
"context_text": content,
|
||||
"image_b64": None,
|
||||
"type": "TEXT",
|
||||
"is_pure_text": True
|
||||
}
|
||||
except Exception as e:
|
||||
return {"context_text": "", "image_b64": None, "type": "ERROR", "error": str(e)}
|
||||
|
||||
return {"context_text": "", "image_b64": None, "type": "UNKNOWN"}
|
||||
@@ -254,5 +254,27 @@ TOOLS_SCHEMA = [
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "office_pdf_to_word",
|
||||
"description": (
|
||||
"Преобразование прикрепленного многостраничного PDF-документа или скана в файл Microsoft Word (.docx).\n"
|
||||
"Выполняет постраничное оптическое распознавание (OCR), форматирование по ГОСТ и формирует карточку скачивания.\n"
|
||||
"Вызывай этот инструмент ВСЕГДА, когда пользователь просит распознать документ, перевести PDF в Word, "
|
||||
"сделать редактируемый текст или оформить протокол в docx."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"format_style": {
|
||||
"type": "string",
|
||||
"enum": ["STANDARD_GOST", "RAW_TEXT"],
|
||||
"description": "Стиль оформления Word (по умолчанию STANDARD_GOST)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -393,8 +393,8 @@ document.addEventListener("DOMContentLoaded", async () => {
|
||||
const userInputEl = document.getElementById("user-input");
|
||||
if (userInputEl) {
|
||||
userInputEl.addEventListener("input", function() {
|
||||
this.style.height = "24px";
|
||||
const newHeight = Math.min(this.scrollHeight, 120);
|
||||
this.style.height = "32px";
|
||||
const newHeight = Math.min(this.scrollHeight, 140);
|
||||
this.style.height = newHeight + "px";
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user