fix(etl & ocr): stabilize scud_export syntax/imports, revert to qwen2.5vl:7b-q8_0

This commit is contained in:
2026-09-28 11:59:26 +03:00
parent 11691701e1
commit a64f708b35
15 changed files with 1409 additions and 593 deletions
+412 -210
View File
@@ -12,6 +12,7 @@ ROLE: Нативный оркестратор диалога, диспетчер
===============================================================================
"""
import os
import sys
import json
import logging
@@ -150,6 +151,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"
@@ -320,6 +322,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)
@@ -767,6 +809,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
@@ -943,6 +1013,23 @@ def inject_tools_if_needed(user_message: str, raw_reply: str, existing_tool_call
Любые синтетические перехваты текста регулярными выражениями отключены согласно ROADMAP.
"""
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
```
## File: `./modules/web_api/llm/db/connection.py`
@@ -1442,94 +1529,133 @@ def db_delete_snapshots(snapshot_id: str = None, snapshot_ids: List[str] = None,
## File: `./modules/web_api/llm/file_parser.py`
```py
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"}
```
## File: `./modules/web_api/llm/schemas.py`
@@ -1790,6 +1916,28 @@ 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)"
}
}
}
}
}
]
```
@@ -2130,21 +2278,22 @@ def change_password(req: ChangePasswordRequest, current_user: Dict[str, Any] = D
"""
===============================================================================
FILE: modules/web_api/routers/chat.py
ROLE: Полнофункциональный роутер чата с извлечением текста из PDF и сканов,
поддержкой Function Calling, Fast-Path и оптического распознавания OCR.
ROLE: Роутер чата с чистым разделением:
- Диалог и команды СКУД/1С (через agent.py).
- Парсинг и извлечение документов без обрезания (через file_parser.py).
===============================================================================
"""
import os
import shutil
import base64
import logging
from typing import Optional, List, Dict, Any
from typing import Optional
from fastapi import APIRouter, Header, HTTPException, UploadFile, File, Form
from pydantic import BaseModel
from llm.agent import process_chat_message
from llm.file_parser import parse_uploaded_file
from config import BASE_DIR
logger = logging.getLogger("CHAT_API")
@@ -2168,11 +2317,6 @@ def resolve_user_id(authorization: Optional[str] = None, explicit_user_id: Optio
token = authorization.replace("Bearer ", "").strip()
if token.isdigit():
return int(token)
elif token.startswith("dev_token_"):
try:
return int(token.replace("dev_token_", ""))
except ValueError:
pass
return 1
@@ -2185,8 +2329,6 @@ async def chat_endpoint(payload: ChatMessageRequest, authorization: Optional[str
if not user_msg:
raise HTTPException(status_code=400, detail="Пустое сообщение")
logger.info(f"Сообщение от user_id={user_id}, session_id={session_id}: {user_msg}")
reply_text, history, action_payload = process_chat_message(
user_id=user_id,
user_message=user_msg,
@@ -2215,60 +2357,60 @@ async def chat_upload_endpoint(
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
file_context = ""
image_b64 = None
user_msg = (message or "").strip()
msg_lower = user_msg.lower()
fn_lower = file.filename.lower()
# 1. Текстовые форматы
if fn_lower.endswith((".txt", ".csv", ".log", ".md")):
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
file_context = f.read(6000)
except Exception as e:
logger.warning(f"Не удалось прочитать текст: {e}")
# ⭐️ 1. ПРЯМАЯ ИЗОЛИРОВАННАЯ ОБРАБОТКА PDF/СКАНОВ В WORD ЧЕРЕЗ OFFICE МОДУЛЬ
ocr_keywords = [
"распознай", "распознать", "в word", "в ворд", "для ворда", "для word",
"отформатируй", "текст для вставки", "извлеки текст", "сделай документ", "переведи в ворд"
]
if fn_lower.endswith(".pdf") and (any(k in msg_lower for k in ocr_keywords) or not user_msg):
logger.info(f"[Office] Прямой запуск распознавания PDF в Word: {file.filename}")
from services.office.service import convert_pdf_to_word_service
from modules.web_api.llm.db_tools import db_save_chat_message, db_get_chat_history
# 2. Изображения (прямой OCR)
elif fn_lower.endswith((".png", ".jpg", ".jpeg", ".webp")):
try:
with open(file_path, "rb") as f:
image_b64 = base64.b64encode(f.read()).decode("utf-8")
except Exception as e:
logger.warning(f"Ошибка кодирования картинки в base64: {e}")
# Сохраняем вопрос пользователя в историю
prompt_text = user_msg or f"Распознать документ {file.filename} для MS Word"
db_save_chat_message(session_id, "user", prompt_text, is_ephemeral=0)
# 3. PDF документы (текстовый слой + рендеринг скана при необходимости)
elif fn_lower.endswith(".pdf"):
# Попытка извлечь встроенный текстовый слой
try:
import pypdf
reader = pypdf.PdfReader(file_path)
extracted = []
for page in reader.pages:
t = page.extract_text()
if t:
extracted.append(t)
file_context = "\n".join(extracted).strip()
except Exception:
pass
# Вызываем офисный сервис постраничного OCR и сборки DOCX
office_res = convert_pdf_to_word_service(file_path, file.filename)
# Если текстового слоя мало (скан или фото документа), рендерим страницу в картинку для Vision OCR
if len(file_context) < 40:
try:
import fitz # PyMuPDF
doc = fitz.open(file_path)
if len(doc) > 0:
page = doc[0]
pix = page.get_pixmap(dpi=150)
img_bytes = pix.tobytes("png")
image_b64 = base64.b64encode(img_bytes).decode("utf-8")
file_context = ""
except Exception as e:
logger.warning(f"PyMuPDF не установлен или сбой рендеринга PDF: {e}")
reply_text = (
f"📄 **{office_res['message']}**\n\n"
f"**Фрагмент первой страницы документа:**\n"
f"```text\n{office_res['preview_text']}...\n```\n\n"
f"Файл готов к скачиванию и редактированию в MS Word."
)
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=0)
user_msg = message.strip() or f"Распознай и проанализируй прикрепленный документ {file.filename}"
action_payload = {
"type": "FILE_DOWNLOAD_CARD",
"filename": office_res["filename"],
"download_url": office_res["download_url"],
"tasks_count": f"{office_res['total_pages']} стр."
}
return {
"status": "success",
"user_id": user_id,
"session_id": session_id,
"response": reply_text,
"action_payload": action_payload
}
# 2. Если это не задача OCR в Word — отправляем файл в обычный диалог агента
parsed = parse_uploaded_file(file_path, file.filename)
file_context = parsed.get("context_text", "")
image_b64 = parsed.get("image_b64")
prompt_for_agent = user_msg or f"Проанализируй документ {file.filename}"
reply_text, history, action_payload = process_chat_message(
user_id=user_id,
user_message=user_msg,
user_message=prompt_for_agent,
file_context=file_context,
image_b64=image_b64,
session_id=session_id
@@ -2380,8 +2522,7 @@ def api_delete_exception(category: str, value: str):
"""
===============================================================================
FILE: modules/web_api/routers/files.py
ROLE: Раздача сформированных отчетов и выгрузок с сохранением оригинальных имен
через изолированные UUID-директории инструментов.
ROLE: Раздача сформированных отчетов и выгрузок с сохранением оригинальных имен.
===============================================================================
"""
@@ -2389,6 +2530,7 @@ import os
import time
import shutil
import urllib.parse
from typing import Optional
from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
@@ -2396,13 +2538,17 @@ router = APIRouter(prefix="/api/v1/files", tags=["Files"])
BASE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
WEB_OUTPUT_DIR = os.path.join(BASE_ROOT, "output", "web")
os.makedirs(WEB_OUTPUT_DIR, exist_ok=True)
REPORTS_DIR = os.path.join(BASE_ROOT, "output", "reports")
TEMP_REPORTS_DIR = "/tmp/scud_reports"
SESSION_TTL_HOURS = 24 # Срок жизни временных сессионных выгрузок
os.makedirs(WEB_OUTPUT_DIR, exist_ok=True)
os.makedirs(REPORTS_DIR, exist_ok=True)
os.makedirs(TEMP_REPORTS_DIR, exist_ok=True)
SESSION_TTL_HOURS = 24
def purge_old_tool_sessions(tool_dir_path: str):
"""Удаляет временные UUID-папки старше SESSION_TTL_HOURS внутри инструмента."""
if not os.path.exists(tool_dir_path):
return
now = time.time()
@@ -2419,9 +2565,6 @@ def purge_old_tool_sessions(tool_dir_path: str):
@router.get("/download/{tool_name}/{session_uuid}/{filename}")
async def download_file(tool_name: str, session_uuid: str, filename: str):
"""
Безопасная отдача файла с каноническим именем из изолированной директории.
"""
safe_tool = os.path.basename(tool_name)
safe_uuid = os.path.basename(session_uuid)
safe_filename = os.path.basename(filename)
@@ -2431,16 +2574,14 @@ async def download_file(tool_name: str, session_uuid: str, filename: str):
if not os.path.exists(file_path) or not os.path.isfile(file_path):
raise HTTPException(status_code=404, detail="Файл не найден или срок его действия истек")
# Определение MIME-типа
media_type = "application/octet-stream"
if safe_filename.endswith(".md") or safe_filename.endswith(".txt"):
if safe_filename.endswith((".md", ".txt")):
media_type = "text/markdown; charset=utf-8"
elif safe_filename.endswith(".xlsx"):
media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
elif safe_filename.endswith(".pdf"):
media_type = "application/pdf"
# Корректная кодировка для кириллических имен файлов
encoded_filename = urllib.parse.quote(safe_filename)
return FileResponse(
@@ -2451,19 +2592,40 @@ async def download_file(tool_name: str, session_uuid: str, filename: str):
}
)
@router.get("/download/reports/{filename}")
async def download_report_direct(filename: str):
"""Прямое скачивание отчетов из output/reports или /tmp/scud_reports."""
safe_filename = os.path.basename(filename)
# 1. Проверяем сетевую шару / постоянный каталог
target_path = os.path.join(BASE_ROOT, "output", "reports", safe_filename)
# 2. Если нет — проверяем временный буфер сборки
if not os.path.exists(target_path):
target_path = os.path.join("/tmp/scud_reports", safe_filename)
if not os.path.exists(target_path):
def _find_report_recursively(target_filename: str) -> Optional[str]:
"""Рекурсивный поиск файла отчета по имени в /tmp и во всех подпапках output/reports/."""
# 1. Проверяем /tmp/scud_reports
tmp_path = os.path.join(TEMP_REPORTS_DIR, target_filename)
if os.path.exists(tmp_path) and os.path.isfile(tmp_path):
return tmp_path
# 2. Проверяем прямой путь в output/reports
direct_path = os.path.join(REPORTS_DIR, target_filename)
if os.path.exists(direct_path) and os.path.isfile(direct_path):
return direct_path
# 3. Рекурсивный поиск по подкаталогам (год/месяц)
for root, _, files in os.walk(REPORTS_DIR):
if target_filename in files:
return os.path.join(root, target_filename)
return None
@router.get("/download/reports/{filename:path}")
async def download_report_direct(filename: str):
"""
Прямое скачивание отчетов:
- Декодирует UTF-8 URL (%20 -> пробел).
- Ищет файл в output/reports/{YEAR}/{MONTH} и во временном буфере /tmp/scud_reports.
"""
decoded_name = urllib.parse.unquote(filename).strip()
safe_filename = os.path.basename(decoded_name)
target_path = _find_report_recursively(safe_filename)
if not target_path or not os.path.exists(target_path):
raise HTTPException(status_code=404, detail="Отчет не найден")
encoded_filename = urllib.parse.quote(safe_filename)
@@ -2762,18 +2924,18 @@ def api_delete_remote_worker(fio: str, current_user = Depends(get_current_user))
"""
===============================================================================
FILE: modules/web_api/routers/reports.py
ROLE: REST API On-Demand генерации отчетов (Сводка, Детальный, Упрощенный)
с атомарной сборкой в /tmp и безопасной публикацией на сетевую шару.
ROLE: REST API On-Demand генерации отчетов:
- Сводка: за СЕГОДНЯ (оперативный контроль, текущий срез).
- Детальный и Упрощенный отчет: строго за ВЧЕРА по финальному срезу Y.
===============================================================================
"""
import os
import shutil
import logging
from datetime import datetime
from datetime import datetime, timedelta
from typing import Optional
from pydantic import BaseModel
from fastapi import APIRouter, HTTPException, Query
from fastapi import APIRouter, HTTPException
from config import DATE_TODAY, DATE_YESTERDAY
from services.scud_etl.svodka_generator import generate_svodka_service
@@ -2785,26 +2947,37 @@ from services.scud_etl.merger import merge_scud_and_1c
logger = logging.getLogger("REPORTS_API")
router = APIRouter(prefix="/api/v1/reports", tags=["Reports"])
TEMP_REPORTS_DIR = "/tmp/scud_reports"
os.makedirs(TEMP_REPORTS_DIR, exist_ok=True)
def get_previous_workday(target_date_str: str) -> str:
"""Вычисляет дату предыдущей рабочей смены (в понедельник возвращает пятницу)."""
clean_date = target_date_str.replace('_', '.')
try:
dt = datetime.strptime(clean_date, "%d.%m.%Y")
days_back = 3 if dt.weekday() == 0 else 1
return (dt - timedelta(days=days_back)).strftime("%d.%m.%Y")
except Exception:
return DATE_YESTERDAY
class GenerateReportRequest(BaseModel):
date: Optional[str] = None # ДД.ММ.ГГГГ
time: Optional[str] = None # ЧЧ:ММ (для сводки)
time: Optional[str] = None # ЧЧ:ММ
report_type: str # 'SVODKA', 'DETAILED', 'SIMPLIFIED', 'ALL'
@router.post("/generate")
def api_generate_report(req: GenerateReportRequest):
"""
Генерирует выбранный отчет на указанную дату/время и возвращает ссылки на скачивание.
Генерирует выбранный отчет:
- SVODKA: на текущую дату (date).
- DETAILED / SIMPLIFIED: строго за вчерашний рабочий день по финальному срезу Y.
"""
target_date = (req.date or DATE_TODAY).replace('_', '.')
yesterday_date = get_previous_workday(target_date)
r_type = req.report_type.upper()
results = []
# 1. Ежедневная сводка
# 1. Ежедневная сводка (за СЕГОДНЯ)
if r_type in ["SVODKA", "ALL"]:
res_svodka = generate_svodka_service(
target_date=target_date,
@@ -2824,9 +2997,9 @@ def api_generate_report(req: GenerateReportRequest):
"status": "error"
})
# 2. Детальный отчет
# 2. Детальный отчет (строго за ВЧЕРА по финальному срезу Y)
if r_type in ["DETAILED", "ALL"]:
res_det = generate_otchet_service(target_date=target_date)
res_det = generate_otchet_service(target_date=yesterday_date)
if res_det.get("status") == "success":
results.append({
"type": "Детальный отчет",
@@ -2841,14 +3014,14 @@ def api_generate_report(req: GenerateReportRequest):
"status": "error"
})
# 3. Упрощенный отчет
# 3. Упрощенный отчет (строго за ВЧЕРА по финальному срезу Y)
if r_type in ["SIMPLIFIED", "ALL"]:
try:
df_scud = load_best_snapshot_for_date(target_date, prefer_final_y=True)
if df_scud is not None and not df_scud.empty:
df_staff, df_abs = load_1c_files_for_date(target_date)
df_merged = merge_scud_and_1c(df_scud, df_staff, df_abs)
out_path = generate_simplified_excel(df_merged, date_str=target_date)
df_scud_y = load_best_snapshot_for_date(yesterday_date, prefer_final_y=True)
if df_scud_y is not None and not df_scud_y.empty:
df_staff_y, df_abs_y = load_1c_files_for_date(yesterday_date)
df_merged_y = merge_scud_and_1c(df_scud_y, df_staff_y, df_abs_y)
out_path = generate_simplified_excel(df_merged_y, date_str=yesterday_date)
filename = os.path.basename(out_path)
results.append({
"type": "Упрощенный отчет",
@@ -2859,10 +3032,11 @@ def api_generate_report(req: GenerateReportRequest):
else:
results.append({
"type": "Упрощенный отчет",
"error": f"Срез СКУД за {target_date} не найден.",
"error": f"Финальный срез СКУД (Y) за {yesterday_date} не найден.",
"status": "error"
})
except Exception as e:
logger.exception(f"Ошибка формирования упрощенного отчета: {e}")
results.append({
"type": "Упрощенный отчет",
"error": str(e),
@@ -2871,6 +3045,7 @@ def api_generate_report(req: GenerateReportRequest):
return {
"date": target_date,
"yesterday_date": yesterday_date,
"requested_type": r_type,
"reports": results
}
@@ -3469,16 +3644,32 @@ body {
* { overflow-anchor: none !important; }
#chat-messages-container, main { overflow-anchor: none !important; }
#chat-messages-container { padding-bottom: clamp(400px, 85vh, 900px) !important; }
/* ⭐️ Комфортный размер шрифта в стиле Gemini */
#chat-messages-container .message-content,
#chat-messages-container .text-sm,
#chat-messages-container .text-xs,
#chat-messages-container .text-sm {
font-size: 14.5px !important;
line-height: 1.6 !important;
#chat-messages-container p,
#chat-messages-container li {
font-size: 16px !important;
line-height: 1.65 !important;
color: #1e293b !important; /* slate-800 */
}
#chat-messages-container .user-chat-bubble .text-sm,
#chat-messages-container .user-chat-bubble p,
#chat-messages-container .user-chat-bubble div {
font-size: 16px !important;
line-height: 1.6 !important;
color: #ffffff !important;
}
#chat-messages-container pre,
#chat-messages-container code {
font-size: 13.5px !important;
font-size: 14.5px !important;
line-height: 1.5 !important;
}
.user-chat-bubble { scroll-margin-top: 24px !important; }
</style>
</head>
@@ -3692,12 +3883,12 @@ body {
<!-- ЛЕНТА ЧАТА -->
<div id="chat-messages-container" class="flex-1 overflow-y-auto p-4 md:p-6 flex flex-col gap-4">
<div class="flex gap-3 max-w-4xl mx-auto w-full">
<div class="w-7 h-7 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
<i class="fa-solid fa-robot text-xs"></i>
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
<i class="fa-solid fa-robot text-sm"></i>
</div>
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
<div class="text-[10px] font-bold text-indigo-600 uppercase tracking-wider mb-1">ИИ-ассистент SCUD Orion AI</div>
<div class="text-xs text-slate-700 leading-relaxed">
<div class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">ИИ-ассистент SCUD Orion AI</div>
<div class="text-sm text-slate-700 leading-relaxed">
Привет! Вы можете задавать вопросы ассистенту, управлять системным промптом, сверять кадровые нестыковки СКУД и 1С или формировать срезы и отчеты.
</div>
</div>
@@ -3716,24 +3907,35 @@ body {
</div>
<!-- СТРОКА ВВОДА -->
<div class="px-4 py-2 bg-white border-t border-slate-200">
<div id="chat-input-box" class="max-w-4xl mx-auto w-full flex items-center gap-2 bg-slate-50 border border-slate-300 rounded-xl px-2.5 py-1 transition focus-within:border-indigo-500 focus-within:bg-white focus-within:ring-1 focus-within:ring-indigo-100">
<button type="button" onclick="document.getElementById('file-upload-input').click()" class="text-slate-400 hover:text-indigo-600 p-1 transition shrink-0" title="Прикрепить файл">
<i class="fa-solid fa-paperclip text-xs"></i>
<div class="px-4 py-3 bg-white border-t border-slate-200">
<div id="chat-input-box" class="max-w-4xl mx-auto w-full flex items-end gap-3 bg-slate-50 border border-slate-300 rounded-2xl px-4 py-2.5 transition focus-within:border-indigo-500 focus-within:bg-white focus-within:ring-2 focus-within:ring-indigo-100 shadow-xs">
<button type="button" onclick="document.getElementById('file-upload-input').click()" class="text-slate-400 hover:text-indigo-600 p-1.5 transition shrink-0 mb-0.5" title="Прикрепить файл">
<i class="fa-solid fa-paperclip text-base"></i>
</button>
<input type="file" id="file-upload-input" class="hidden" />
<textarea id="user-input" rows="1" placeholder="Команда, вопрос (Enter - отправить, Shift+Enter - перенос строки)..."
class="flex-1 bg-transparent border-0 focus:outline-none text-xs text-slate-800 resize-none py-0 leading-5" style="height: 24px; line-height: 24px;"></textarea>
<textarea id="user-input" rows="1" placeholder="Задайте вопрос, отправьте команду (Enter — отправить, Shift+Enter — перенос)..."
class="flex-1 bg-transparent border-0 focus:outline-none text-[15.5px] text-slate-800 placeholder:text-slate-400 resize-none py-1 leading-6 min-h-[32px] max-h-36" style="height: 32px;"></textarea>
<button type="button" onclick="window.sendMessage()" class="w-6 h-6 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white flex items-center justify-center shrink-0 shadow-sm transition">
<i class="fa-solid fa-paper-plane text-[10px]"></i>
<button type="button" onclick="window.sendMessage()" class="w-8 h-8 rounded-xl bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white flex items-center justify-center shrink-0 shadow-sm transition mb-0.5">
<i class="fa-solid fa-paper-plane text-xs"></i>
</button>
</div>
</div>
</main>
</div>
<!-- ПОЛНОЭКРАННЫЙ ОВЕРЛЕЙ DRAG & DROP -->
<div id="global-drag-overlay" class="fixed inset-0 bg-indigo-950/70 backdrop-blur-xs z-50 flex items-center justify-center p-8 hidden pointer-events-none transition-all">
<div class="border-3 border-dashed border-indigo-300 rounded-3xl w-full h-full flex flex-col items-center justify-center text-white gap-4 bg-indigo-900/40">
<div class="w-20 h-20 rounded-2xl bg-white/10 flex items-center justify-center shadow-lg backdrop-blur-md border border-white/20">
<i class="fa-solid fa-cloud-arrow-up text-4xl text-indigo-200"></i>
</div>
<div class="text-xl font-bold tracking-wide">Перетащите файл в окно для загрузки</div>
<div class="text-sm text-indigo-200">Поддерживаются PDF (документы и сканы), изображения, Excel, CSV, TXT</div>
</div>
</div>
<!-- КОНТЕЙНЕР ДИНАМИЧЕСКИХ МОДАЛЬНЫХ ОКОН -->
<div id="modals-container"></div>
@@ -4153,8 +4355,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";
});
}
@@ -4309,7 +4511,7 @@ function updateInputHeightAndFade(textarea) {
if (!textarea) return;
if (!textarea.value || textarea.value.trim() === '') {
textarea.style.height = '24px';
textarea.style.height = '32px';
textarea.style.overflowY = 'hidden';
textarea.style.maskImage = 'none';
textarea.style.webkitMaskImage = 'none';
@@ -4317,8 +4519,8 @@ function updateInputHeightAndFade(textarea) {
}
textarea.style.height = 'auto';
const minHeight = 24;
const maxHeight = 120;
const minHeight = 32;
const maxHeight = 140;
const currentScrollHeight = textarea.scrollHeight;
if (currentScrollHeight <= minHeight + 2) {
@@ -4404,23 +4606,23 @@ function appendAssistantMessage(text, buttons = [], actionPayload = null) {
payloadHtml = renderInteractiveTaskCard(actionPayload.tasks);
} else if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
const dlUrl = actionPayload.download_url || '#';
const fName = actionPayload.filename || 'ROADMAP.md';
const fName = actionPayload.filename || 'document.docx';
const count = actionPayload.tasks_count || '';
payloadHtml = `
<div class="mt-3 p-3.5 bg-indigo-50/80 border border-indigo-200 rounded-xl flex items-center justify-between gap-3 shadow-sm">
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-200 rounded-xl flex items-center justify-between gap-3 shadow-xs">
<div class="flex items-center gap-3 min-w-0">
<div class="w-9 h-9 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm">
<i class="fa-solid fa-file-lines text-base"></i>
<div class="w-10 h-10 rounded-xl bg-blue-600 text-white flex items-center justify-center shrink-0 shadow-sm">
<i class="fa-solid fa-file-word text-lg"></i>
</div>
<div class="min-w-0">
<div class="text-sm font-bold text-slate-800 truncate">${escapeHtml(fName)}</div>
<div class="text-xs text-slate-500">Задач выгружено: ${count} шт. · Markdown</div>
<div class="text-xs text-slate-500">${count ? count + ' · ' : ''}Документ MS Word (.docx)</div>
</div>
</div>
<a href="${dlUrl}" download="${escapeHtml(fName)}" target="_blank"
class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white rounded-lg text-xs font-bold shadow-sm transition flex items-center gap-1.5 shrink-0">
<i class="fa-solid fa-download text-xs"></i>
<span>Скачать файл</span>
class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white font-bold rounded-xl text-xs shadow-sm transition flex items-center gap-2 shrink-0">
<i class="fa-solid fa-arrow-down-to-line text-sm text-white"></i>
<span class="text-white tracking-wide">Скачать файл</span>
</a>
</div>
`;
@@ -4624,7 +4826,7 @@ window.sendMessage = async function() {
saveCommandToHistory(messageText);
input.value = "";
input.style.height = '24px';
input.style.height = '32px';
input.style.overflowY = 'hidden';
input.style.maskImage = 'none';
input.style.webkitMaskImage = 'none';
@@ -4739,7 +4941,7 @@ document.addEventListener("DOMContentLoaded", () => {
if (input) {
input.style.lineHeight = '24px';
input.style.height = '24px';
input.style.height = '32px';
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
@@ -6546,8 +6748,8 @@ async function deleteSnapshotItem(snapshotId) {
// 7. Генерация отчетов On-Demand
window.generateReportDirect = async function(reportType) {
const dateInput = document.getElementById('manual-snapshot-date')?.value || '';
const timeInput = document.getElementById('manual-snapshot-time')?.value || '';
const fromInput = document.getElementById('snapshots-date-from');
const dateInput = fromInput ? isoToBackendFormat(fromInput.value) : '';
const labelMap = {
'SVODKA': 'Сводки',
@@ -6564,7 +6766,7 @@ window.generateReportDirect = async function(reportType) {
body: JSON.stringify({
report_type: reportType,
date: dateInput || null,
time: timeInput || null
time: null // ⭐️ Всегда берем последний готовый срез
})
});