fix(etl & ocr): stabilize scud_export syntax/imports, revert to qwen2.5vl:7b-q8_0
This commit is contained in:
Binary file not shown.
+518
-37
@@ -861,6 +861,38 @@ def init_all_tables() -> None:
|
|||||||
|
|
||||||
Все важные изменения проекта документируются в этом файле.
|
Все важные изменения проекта документируются в этом файле.
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
### ✨ Добавлено (Added)
|
||||||
|
- **Изолированный домен работы с документами (`services/office/`):**
|
||||||
|
- Создан специализированный пакет для постраничной обработки многостраничных PDF и сканов без ограничений контекста диалога.
|
||||||
|
- Автоматическая сборка распознанного текста в файл Microsoft Word (`.docx`) со стандартизированным оформлением.
|
||||||
|
- Интеграция с роутером чата и выдача контрастной карточки скачивания документа.
|
||||||
|
|
||||||
|
### 📝 Запланировано (Planned)
|
||||||
|
- **Двухфазный OCR-конвейер рукописных виз и резолюций (`services/office/`):**
|
||||||
|
- Рендеринг сканов в высоком разрешении (`250–300 DPI`) для точного захвата линий чернил.
|
||||||
|
- Фаза 2 (Refiner на `qwen2.5:14b`): автоматическое устранение артефактов OCR, склейка абзацев и преобразование списков в таблицы Word.
|
||||||
|
- Распознавание рукописных виз «Согласовано», подписей и дат руководства с выделением в блок `[Резолюция: ...]`.
|
||||||
|
|
||||||
|
## [3.4.0] — 2026-09-25
|
||||||
|
|
||||||
|
### ✨ Добавлено (Added)
|
||||||
|
- **Оперативная On-Demand генерация отчетов из сайдбара:**
|
||||||
|
- Мгновенная сборка книги «Ежедневная сводка» по последнему зафиксированному в SQLite срезу СКУД (без ожидания внешнего опроса Орион).
|
||||||
|
- Строгое разграничение временных рамок отчетов: «Сводка» формируется на текущую смену, а «Детальный» и «Упрощенный» отчеты — строго за прошедшую смену (ВЧЕРА / прошлая пятница) по итоговому срезу `Y`.
|
||||||
|
- **Фоновая полудневная синхронизация 1С (cron):**
|
||||||
|
- Интеграция вызова `copy_1c_files_from_share()` и опроса кадровых отсутствий из базы ЗУП (`ACCOUNT-01`) в цикл получасовых срезов.
|
||||||
|
|
||||||
|
### 🛡️ Исправлено (Fixed)
|
||||||
|
- **Ошибка 404 при скачивании отчетов (`download_report_direct`):**
|
||||||
|
- Добавлен рекурсивный поиск файлов в подпапках `output/reports/{ГОД}/{МЕСЯЦ}/` и декодирование процент-кодированных кириллических имен из URL.
|
||||||
|
- **Ошибки 500 и 0 по штату 1С при создании сводки:**
|
||||||
|
- Реализован каскадный fallback: если файл штата на текущий день еще не выложен на шару, данные штата берутся из последнего сохраненного среза `zup_staff` в SQLite (устранено ложное попадание всех сотрудников в «Нет в ЗУП»).
|
||||||
|
- Исправлены `NameError` импортов (`load_best_snapshot_for_date`, `load_1c_data_smart`).
|
||||||
|
- **Сбои инспекции срезов (`OperationalError: no such column: hoz_organ`):**
|
||||||
|
- Переход на динамический `SELECT *` в роутере инспекции срезов и расчет реального времени в здании до момента фиксации снапшота.
|
||||||
|
|
||||||
## [3.3.0] — 2026-09-24
|
## [3.3.0] — 2026-09-24
|
||||||
|
|
||||||
### ✨ Добавлено (Added)
|
### ✨ Добавлено (Added)
|
||||||
@@ -1298,22 +1330,19 @@ def init_all_tables() -> None:
|
|||||||
---
|
---
|
||||||
|
|
||||||
## 15. ПРИОРИТЕТ 1: Внутридневной контроль, экран «Кто в здании» и On-Demand генерация `[В РАБОТЕ]`
|
## 15. ПРИОРИТЕТ 1: Внутридневной контроль, экран «Кто в здании» и On-Demand генерация `[В РАБОТЕ]`
|
||||||
- [ ] **Оперативный контроль «Кто в здании прямо сейчас» (Live Presence):**
|
- [x] **Оперативный контроль «Кто в здании прямо сейчас» (Live Presence):**
|
||||||
- [ ] REST API эндпоинт `GET /api/v1/presence/live` на базе таблицы `scud_events_raw` и оконной функции последнего события прохода.
|
- [x] REST API эндпоинт `GET /api/v1/presence/live` на базе таблицы `scud_events_raw` и оконной функции последнего события прохода.
|
||||||
- [ ] Выделенная вкладка/панель в веб-интерфейсе:
|
- [x] Выделенная модальная панель в веб-интерфейсе:
|
||||||
- Метрики реального времени: *Всего по штату*, *В здании прямо сейчас*, *Вышли на перерыв/обед*, *На удаленке*, *В командировке/отпуске*, *Не пришли*.
|
- Метрики реального времени: *Штат 1С*, *В здании*, *Вышли*, *На удаленке*, *В командировке/отпуске*, *Не пришли*, *Исключения*.
|
||||||
- Быстрый поиск сотрудника и фильтрация по подразделениям.
|
- Быстрый поиск сотрудника и фильтрация по подразделениям.
|
||||||
- Детекция внутридневных аномалий (находится в здании без отметки утреннего входа, вход без выхода более 10 часов).
|
- Учет специфики служебных входов/выходов во двор (флигель/двор).
|
||||||
- [ ] **On-Demand генерация отчетов из UI и сайдбара:**
|
- [x] **On-Demand генерация отчетов из UI и сайдбара:**
|
||||||
- [ ] Кнопка **«Сводка на текущий момент»** в сайдбаре: фоновый вызов `svodka_generator.py` со срезом на текущую минуту без перезагрузки страницы.
|
- [x] Кнопка **«Сводка»** в сайдбаре: моментальный сбор книги по последнему готовому срезу SQLite без блокирующих опросов MS SQL.
|
||||||
- [ ] Модальное окно **«Сформировать отчеты за дату»** с выбором даты из календаря и чекбоксами формирования документов:
|
- [x] Кнопки **«Детальн.»** и **«Упрощ.»**: строгое формирование отчетов за **ВЧЕРА** (с учетом выходных) по финальному суточному срезу `Y` (23:59:59).
|
||||||
- [ ] Детальный отчет (`otchet_generator.py`)
|
- [x] Каскадный fallback кадровых файлов: при отсутствии свежего штата за текущее утро автоматическое использование актуального среза из `zup_staff` в SQLite.
|
||||||
- [ ] Упрощенный отчет (`simplified_builder.py`)
|
- [x] **Атомарная публикация и отдача файлов (Report Delivery Engine):**
|
||||||
- [ ] Сводка контроллинга (`svodka_generator.py`)
|
- [x] Устранение 404 ошибок: рекурсивный поиск файлов в иерархии `output/reports/{ГОД}/{МЕСЯЦ}/` и декодирование URL-имён.
|
||||||
- [ ] **Атомарная публикация и отдача файлов (Report Delivery Engine):**
|
- [x] Синхронизация при отдаче: автоматическая отдача прямой ссылки на скачивание в браузер.
|
||||||
- [ ] Сборка документов во временный каталог `/tmp/scud_reports/` для исключения блокировок SMB-шары открытыми процессами Excel.
|
|
||||||
- [ ] Безопасная синхронизация готовых файлов на сетевую шару `//storage/SCUD/Отчеты/`.
|
|
||||||
- [ ] Автоматическая выдача прямой ссылки на скачивание файла (`/api/v1/files/download/...`) в интерфейс.
|
|
||||||
- [ ] **Реестр «Графики работы» (Custom Work Schedules):**
|
- [ ] **Реестр «Графики работы» (Custom Work Schedules):**
|
||||||
- [ ] Таблица в SQLite `work_schedules_registry` (`fio_clean`, `department`, `schedule_type`, `norm_hours`, `time_start_window`, `time_end_window`, `valid_from`, `valid_to`).
|
- [ ] Таблица в SQLite `work_schedules_registry` (`fio_clean`, `department`, `schedule_type`, `norm_hours`, `time_start_window`, `time_end_window`, `valid_from`, `valid_to`).
|
||||||
- [ ] Интеграция индивидуальной нормы часов (4, 7, 11, 24 ч) в калькулятор выработки `calculators.py` вместо константы 8 ч.
|
- [ ] Интеграция индивидуальной нормы часов (4, 7, 11, 24 ч) в калькулятор выработки `calculators.py` вместо константы 8 ч.
|
||||||
@@ -1350,6 +1379,24 @@ def init_all_tables() -> None:
|
|||||||
- [ ] **Docker/gVisor контур:**
|
- [ ] **Docker/gVisor контур:**
|
||||||
- [ ] Изолированный контейнер без доступа к внешней сети (`network: none`) с жесткими cgroups-лимитами и монтированием данных в режиме Read-Only.
|
- [ ] Изолированный контейнер без доступа к внешней сети (`network: none`) с жесткими cgroups-лимитами и монтированием данных в режиме Read-Only.
|
||||||
- [ ] Генерация и выполнение Python/Pandas скриптов для построения сложных графиков и нестандартной статистики на лету.
|
- [ ] Генерация и выполнение Python/Pandas скриптов для построения сложных графиков и нестандартной статистики на лету.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 19. Доменный модуль канцелярии и документов (`services/office/`) `[В РАБОТЕ]`
|
||||||
|
- [x] **Изоляция офисного домена от кадрового ядра СКУД:**
|
||||||
|
- [x] Создание независимого пакета `services/office/` (`document_extractor.py`, `word_builder.py`, `service.py`).
|
||||||
|
- [x] Снятие ограничений контекста диалога: многостраничный постраничный обход PDF вместо обрезания первой страницы.
|
||||||
|
- [x] Генерация ГОСТ-документов Word (`.docx`) с выдачей контрастной карточки скачивания в интерфейс чата.
|
||||||
|
- [ ] **Двухфазный конвейер OCR и глубокая нормализация (Vision + LLM Refiner):**
|
||||||
|
- [ ] **Фаза 1 (Vision Extraction):** повышение разрешения рендеринга до `250–300 DPI` для чёткой отрисовки тонких линий шариковых ручек и штампов.
|
||||||
|
- [ ] **Фаза 2 (LLM Post-Processing Refiner):** вычитка текста через `qwen2.5:14b`:
|
||||||
|
- Устранение диалогового шума и случайных приветствий модели.
|
||||||
|
- Склейка разорванных строк внутри абзацев.
|
||||||
|
- Автоматическая сборка списков участников и табличных данных в полноценные таблицы Word (`Table Grid`).
|
||||||
|
- [ ] **Специализированное распознавание рукописных виз и резолюций канцелярии:**
|
||||||
|
- [ ] Распознавание наклонного и беглого почерка на полях и в шапке документов (визы «Согласовано», резолюции руководства, подписи, даты).
|
||||||
|
- [ ] Выделение рукописных пометок в стандартизированные структурные блоки: `[Резолюция: ...]` в начале страницы.
|
||||||
|
- [ ] **Two-Pass Context Injection:** перекрёстное сопоставление неразборчивых фамилий и инициалов с реестром участников совещания/штатом из тела самого документа.
|
||||||
```
|
```
|
||||||
|
|
||||||
## File: `./exceptions.json`
|
## File: `./exceptions.json`
|
||||||
@@ -3489,6 +3536,376 @@ def get_active_manual_absences_for_date(date_str: str) -> List[Dict[str, Any]]:
|
|||||||
return [dict(r) for r in cursor.fetchall()]
|
return [dict(r) for r in cursor.fetchall()]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## File: `./services/office/document_extractor.py`
|
||||||
|
```py
|
||||||
|
"""
|
||||||
|
===============================================================================
|
||||||
|
FILE: services/office/document_extractor.py
|
||||||
|
ROLE: Постраничный OCR без галлюцинаций резолюций.
|
||||||
|
===============================================================================
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import base64
|
||||||
|
import logging
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
import pymupdf as fitz
|
||||||
|
from modules.web_api.llm.core.ollama_client import call_ollama_chat
|
||||||
|
|
||||||
|
logger = logging.getLogger("OFFICE_EXTRACTOR")
|
||||||
|
|
||||||
|
|
||||||
|
def ocr_image_b64(image_b64: str, page_num: int = 1) -> str:
|
||||||
|
"""
|
||||||
|
Распознавание одного скана страницы через Qwen 2.5-VL.
|
||||||
|
"""
|
||||||
|
system_prompt = (
|
||||||
|
"Ты — строгий сканер оптического распознавания текста (OCR).\n"
|
||||||
|
"Твоя ЕДИНСТВЕННАЯ задача — переписать текст со скана СЛОВО В СЛОВО.\n\n"
|
||||||
|
"ЖЕСТКИЕ ПРАВИЛА:\n"
|
||||||
|
"1. Переписывай ТОЛЬКО то, что РЕАЛЬНО написано на картинке. Не придумывай даты, резолюции, фамилии или заголовки.\n"
|
||||||
|
"2. Если на странице есть рукописный синий/черный текст (только на титульных листах) — выпиши его первой строкой как: [Рукописный текст: ...].\n"
|
||||||
|
" ЕСЛИ РУКОПИСНОГО ТЕКСТА НЕТ — НЕ ПИШИ НИКАКИХ БЛОКОВ РЕЗОЛЮЦИЙ!\n"
|
||||||
|
"3. Сохраняй исходные формулировки, абзацы, пункты 1, 2, 3 и дефисы.\n"
|
||||||
|
"4. Запрещено добавлять приветствия, извинения и комментарии. Выводи строго распознанный текст."
|
||||||
|
)
|
||||||
|
user_message = {
|
||||||
|
"role": "user",
|
||||||
|
"content": f"Точно перепиши весь текст страницы {page_num} буква в букву без фантазий и без изменений.",
|
||||||
|
"images": [image_b64]
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
res = call_ollama_chat(
|
||||||
|
messages=[{"role": "system", "content": system_prompt}, user_message],
|
||||||
|
is_vision=True,
|
||||||
|
timeout=180
|
||||||
|
)
|
||||||
|
return (res.get("content") or "").strip()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"[Office OCR] Ошибка OCR страницы {page_num}: {e}")
|
||||||
|
return f"[Ошибка распознавания страницы {page_num}: {e}]"
|
||||||
|
|
||||||
|
|
||||||
|
def process_pdf_full(file_path: str, max_pages: Optional[int] = None) -> List[Dict[str, Any]]:
|
||||||
|
results = []
|
||||||
|
doc = fitz.open(file_path)
|
||||||
|
total_pages = len(doc)
|
||||||
|
limit = min(total_pages, max_pages) if max_pages else total_pages
|
||||||
|
|
||||||
|
logger.info(f"[Office] OCR обработка {os.path.basename(file_path)}: {limit} страниц (DPI=250)")
|
||||||
|
|
||||||
|
for idx in range(limit):
|
||||||
|
page_num = idx + 1
|
||||||
|
page = doc[idx]
|
||||||
|
|
||||||
|
pix = page.get_pixmap(dpi=250)
|
||||||
|
img_b64 = base64.b64encode(pix.tobytes("png")).decode("utf-8")
|
||||||
|
|
||||||
|
raw_text = ocr_image_b64(img_b64, page_num=page_num)
|
||||||
|
results.append({
|
||||||
|
"page": page_num,
|
||||||
|
"text": raw_text
|
||||||
|
})
|
||||||
|
|
||||||
|
doc.close()
|
||||||
|
return results
|
||||||
|
```
|
||||||
|
|
||||||
|
## File: `./services/office/service.py`
|
||||||
|
```py
|
||||||
|
"""
|
||||||
|
===============================================================================
|
||||||
|
FILE: services/office/service.py
|
||||||
|
ROLE: Детерминированная сборка Word без галлюцинаций.
|
||||||
|
===============================================================================
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import uuid
|
||||||
|
import logging
|
||||||
|
from typing import Dict, Any
|
||||||
|
|
||||||
|
from config import BASE_DIR
|
||||||
|
from .document_extractor import process_pdf_full
|
||||||
|
from .word_builder import build_docx_from_ocr
|
||||||
|
|
||||||
|
logger = logging.getLogger("OFFICE_SERVICE")
|
||||||
|
|
||||||
|
OFFICE_OUTPUT_DIR = os.path.join(BASE_DIR, "output", "web", "office")
|
||||||
|
os.makedirs(OFFICE_OUTPUT_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def clean_page_text(text: str, page_num: int) -> str:
|
||||||
|
"""Детерминированная очистка страницы от шума и галлюцинаций."""
|
||||||
|
lines = text.splitlines()
|
||||||
|
cleaned_lines = []
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
l = line.strip()
|
||||||
|
if not l:
|
||||||
|
cleaned_lines.append("")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 1. Срезаем фантомные резолюции со всех страниц, кроме 1 и 2
|
||||||
|
if page_num > 2 and any(k in l.lower() for k in ["резолюция:", "рукописный текст:"]):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 2. Срезаем приветствия
|
||||||
|
if any(l.lower().startswith(g) for g in ["спасибо за", "здравствуйте", "вот текст"]):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 3. Убираем markdown-обертки ```
|
||||||
|
if l.startswith("```"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
cleaned_lines.append(l)
|
||||||
|
|
||||||
|
return "\n".join(cleaned_lines).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def convert_pdf_to_word_service(file_path: str, original_filename: str) -> Dict[str, Any]:
|
||||||
|
session_id = str(uuid.uuid4())[:8]
|
||||||
|
base_name = os.path.splitext(os.path.basename(original_filename))[0]
|
||||||
|
out_docx_name = f"{base_name}_распознан.docx"
|
||||||
|
|
||||||
|
target_dir = os.path.join(OFFICE_OUTPUT_DIR, session_id)
|
||||||
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
|
out_docx_path = os.path.join(target_dir, out_docx_name)
|
||||||
|
|
||||||
|
# Постраничный честный OCR без фантазий
|
||||||
|
raw_pages = process_pdf_full(file_path)
|
||||||
|
|
||||||
|
sanitized_pages = []
|
||||||
|
for p in raw_pages:
|
||||||
|
p_num = p.get("page", 1)
|
||||||
|
cleaned = clean_page_text(p.get("text", ""), page_num=p_num)
|
||||||
|
sanitized_pages.append({
|
||||||
|
"page": p_num,
|
||||||
|
"text": cleaned
|
||||||
|
})
|
||||||
|
|
||||||
|
# Сборка в Word
|
||||||
|
build_docx_from_ocr(sanitized_pages, out_docx_path, doc_title=base_name)
|
||||||
|
|
||||||
|
preview_sample = sanitized_pages[0]["text"][:600] if sanitized_pages else "Документ распознан."
|
||||||
|
download_url = f"/api/v1/files/download/office/{session_id}/{out_docx_name}"
|
||||||
|
|
||||||
|
return {
|
||||||
|
"status": "success",
|
||||||
|
"total_pages": len(sanitized_pages),
|
||||||
|
"filename": out_docx_name,
|
||||||
|
"filepath": out_docx_path,
|
||||||
|
"download_url": download_url,
|
||||||
|
"preview_text": preview_sample,
|
||||||
|
"message": f"Документ точно распознан ({len(sanitized_pages)} стр.) без искажений."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## File: `./services/office/text_refiner.py`
|
||||||
|
```py
|
||||||
|
"""
|
||||||
|
===============================================================================
|
||||||
|
FILE: services/office/text_refiner.py
|
||||||
|
PROJECT: SCUD Orion AI (Office Domain)
|
||||||
|
ROLE: Фаза 2: Постобработка и вычитка текста через текстовую LLM (qwen2.5:14b).
|
||||||
|
Устранение артефактов OCR, склейка разорванных предложений,
|
||||||
|
удаление диалогового мусора и форматирование списков в Markdown-таблицы.
|
||||||
|
===============================================================================
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import logging
|
||||||
|
from modules.web_api.llm.core.ollama_client import call_ollama_chat
|
||||||
|
|
||||||
|
logger = logging.getLogger("TEXT_REFINER")
|
||||||
|
|
||||||
|
|
||||||
|
def refine_ocr_page_text(raw_text: str, page_num: int = 1) -> str:
|
||||||
|
"""
|
||||||
|
Нормализует черновой текст OCR:
|
||||||
|
- Очищает от приветствий и служебных фраз.
|
||||||
|
- Склеивает разорванные строки внутри предложений.
|
||||||
|
- Форматирует списки участников совещания в Markdown-таблицы.
|
||||||
|
- Сохраняет блоки [Резолюция: ...].
|
||||||
|
"""
|
||||||
|
if not raw_text or len(raw_text.strip()) < 10:
|
||||||
|
return raw_text
|
||||||
|
|
||||||
|
system_prompt = (
|
||||||
|
"Ты — строгий технический редактор и корректор официальных протоколов и документов.\n"
|
||||||
|
"Тебе передан черновой текст оптического распознавания (OCR) одной страницы документа.\n\n"
|
||||||
|
"ТВОИ ЗАДАЧИ:\n"
|
||||||
|
"1. УДАЛИ любой диалоговый шум: 'Спасибо за обращение', 'Здравствуйте', 'Вот текст' и т.п.\n"
|
||||||
|
"2. БЛОКИ РЕЗОЛЮЦИЙ: Если в тексте есть рукописная резолюция или блок '[Резолюция: ...]', "
|
||||||
|
"сохрани его в самом верху страницы.\n"
|
||||||
|
"3. СКЛЕЙКА АБЗАЦЕВ: Соединяй строки, разорванные при переносе, в связные абзацы. Не оставляй рваных строк.\n"
|
||||||
|
"4. СПИСКИ УЧАСТНИКОВ И ТАБЛИЦЫ: Если на странице идет перечисление участников совещания (ФИО, ведомство, должность), "
|
||||||
|
"ОБЯЗАТЕЛЬНО преобразуй их в ровную Markdown-таблицу:\n"
|
||||||
|
"| № | Ведомство / Организация | Должность | ФИО | Формат |\n"
|
||||||
|
"5. СОХРАНЯЙ все официальные заголовки ('ПРЕДСЕДАТЕЛЬСТВОВАЛ', 'РЕШИЛИ:', 'ОТМЕТИЛИ:').\n"
|
||||||
|
"6. Запрещено сокращать или пересказывать суть. Выводи полный текст документа."
|
||||||
|
)
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt},
|
||||||
|
{"role": "user", "content": f"Вычитай и приведи к стандарту делопроизводства страницу №{page_num}:\n\n{raw_text}"}
|
||||||
|
]
|
||||||
|
|
||||||
|
try:
|
||||||
|
res = call_ollama_chat(messages, is_vision=False, timeout=120)
|
||||||
|
refined = (res.get("content") or "").strip()
|
||||||
|
|
||||||
|
# Снимаем возможное оборачивание в ```markdown
|
||||||
|
refined = re.sub(r'^```[a-zA-Z]*\n', '', refined)
|
||||||
|
refined = re.sub(r'\n```$', '', refined)
|
||||||
|
|
||||||
|
# Страховочное отсечение фраз вежливости
|
||||||
|
for junk in ["Спасибо за обращение", "Здравствуйте", "Вот вычитанный текст"]:
|
||||||
|
if refined.startswith(junk):
|
||||||
|
refined = refined[len(junk):].lstrip(" ,.:!\n")
|
||||||
|
|
||||||
|
return refined
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[TextRefiner] Ошибка рефайнинга страницы {page_num}: {e}")
|
||||||
|
return raw_text
|
||||||
|
```
|
||||||
|
|
||||||
|
## File: `./services/office/word_builder.py`
|
||||||
|
```py
|
||||||
|
"""
|
||||||
|
===============================================================================
|
||||||
|
FILE: services/office/word_builder.py
|
||||||
|
PROJECT: SCUD Orion AI (Office Domain)
|
||||||
|
ROLE: Фаза 3: Сборка форматированного документа MS Word (.docx):
|
||||||
|
- Поддержка нативных таблиц Word (Table Grid) из Markdown.
|
||||||
|
- Специальное выделение блоков рукописных резолюций.
|
||||||
|
- ГОСТ-оформление (Times New Roman, поля, отступы).
|
||||||
|
===============================================================================
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from typing import List, Dict, Any
|
||||||
|
from docx import Document
|
||||||
|
from docx.shared import Pt, Inches, RGBColor
|
||||||
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
|
from docx.oxml import OxmlElement
|
||||||
|
from docx.oxml.ns import qn
|
||||||
|
|
||||||
|
|
||||||
|
def set_cell_margins(cell, top=100, bottom=100, left=150, right=150):
|
||||||
|
"""Устанавливает внутренние поля ячейки таблицы."""
|
||||||
|
tcPr = cell._tc.get_or_add_tcPr()
|
||||||
|
tcMar = OxmlElement('w:tcMar')
|
||||||
|
for m, val in [('top', top), ('bottom', bottom), ('left', left), ('right', right)]:
|
||||||
|
node = OxmlElement(f'w:{m}')
|
||||||
|
node.set(qn('w:w'), str(val))
|
||||||
|
node.set(qn('w:type'), 'dxa')
|
||||||
|
tcMar.append(node)
|
||||||
|
tcPr.append(tcMar)
|
||||||
|
|
||||||
|
|
||||||
|
def build_docx_from_ocr(pages_data: List[Dict[str, Any]], output_filepath: str, doc_title: str = "Распознанный документ") -> str:
|
||||||
|
doc = Document()
|
||||||
|
|
||||||
|
# Поля страницы по ГОСТ (2 см по бокам и сверху, 1.5 см справа)
|
||||||
|
for section in doc.sections:
|
||||||
|
section.top_margin = Inches(0.79)
|
||||||
|
section.bottom_margin = Inches(0.79)
|
||||||
|
section.left_margin = Inches(0.79)
|
||||||
|
section.right_margin = Inches(0.59)
|
||||||
|
|
||||||
|
for p_idx, page in enumerate(pages_data):
|
||||||
|
text_content = page.get("text", "")
|
||||||
|
if p_idx > 0:
|
||||||
|
doc.add_page_break()
|
||||||
|
|
||||||
|
lines = text_content.splitlines()
|
||||||
|
table_buffer = []
|
||||||
|
|
||||||
|
def flush_table():
|
||||||
|
nonlocal table_buffer
|
||||||
|
if not table_buffer:
|
||||||
|
return
|
||||||
|
|
||||||
|
parsed_rows = []
|
||||||
|
for t_line in table_buffer:
|
||||||
|
cells = [c.strip() for c in t_line.strip().strip('|').split('|')]
|
||||||
|
# Пропускаем разделительные строки Markdown (|---|---|)
|
||||||
|
if any(cells) and not all(set(c).issubset({'-', ':', ' '}) for c in cells):
|
||||||
|
parsed_rows.append(cells)
|
||||||
|
|
||||||
|
if parsed_rows:
|
||||||
|
num_cols = max(len(r) for r in parsed_rows)
|
||||||
|
tbl = doc.add_table(rows=len(parsed_rows), cols=num_cols)
|
||||||
|
tbl.style = 'Table Grid'
|
||||||
|
|
||||||
|
for r_idx, row_data in enumerate(parsed_rows):
|
||||||
|
for c_idx in range(num_cols):
|
||||||
|
val = row_data[c_idx] if c_idx < len(row_data) else ""
|
||||||
|
cell = tbl.cell(r_idx, c_idx)
|
||||||
|
cell.text = val
|
||||||
|
set_cell_margins(cell)
|
||||||
|
for para in cell.paragraphs:
|
||||||
|
para.paragraph_format.line_spacing = 1.05
|
||||||
|
para.paragraph_format.space_after = Pt(2)
|
||||||
|
for run in para.runs:
|
||||||
|
run.font.name = "Times New Roman"
|
||||||
|
run.font.size = Pt(10)
|
||||||
|
if r_idx == 0:
|
||||||
|
run.font.bold = True
|
||||||
|
|
||||||
|
table_buffer = []
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
line_str = line.strip()
|
||||||
|
if not line_str:
|
||||||
|
flush_table()
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Детекция строки Markdown-таблицы
|
||||||
|
if line_str.startswith('|') and line_str.endswith('|'):
|
||||||
|
table_buffer.append(line_str)
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
flush_table()
|
||||||
|
|
||||||
|
# Обработка блока рукописной резолюции
|
||||||
|
if line_str.startswith('[Резолюция:') or line_str.startswith('Резолюция:'):
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.paragraph_format.space_after = Pt(6)
|
||||||
|
p.paragraph_format.line_spacing = 1.15
|
||||||
|
run = p.add_run(f"✍️ {line_str}")
|
||||||
|
run.font.name = "Times New Roman"
|
||||||
|
run.font.size = Pt(11)
|
||||||
|
run.font.italic = True
|
||||||
|
run.font.color.rgb = RGBColor(15, 76, 129) # Классический синий цвет визы
|
||||||
|
continue
|
||||||
|
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.paragraph_format.space_after = Pt(4)
|
||||||
|
p.paragraph_format.line_spacing = 1.15
|
||||||
|
|
||||||
|
# Выравнивание заголовков
|
||||||
|
if any(h in line_str.upper() for h in ["ПРЕДСЕДАТЕЛЬСТВОВАЛ", "ПРОТОКОЛ", "ПОВЕСТКА", "РЕШИЛИ:", "ОТМЕТИЛИ:", "СПИСОК УЧАСТНИКОВ"]):
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
run = p.add_run(line_str)
|
||||||
|
run.font.name = "Times New Roman"
|
||||||
|
run.font.size = Pt(13)
|
||||||
|
run.font.bold = True
|
||||||
|
else:
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
||||||
|
run = p.add_run(line_str)
|
||||||
|
run.font.name = "Times New Roman"
|
||||||
|
run.font.size = Pt(12)
|
||||||
|
|
||||||
|
flush_table()
|
||||||
|
|
||||||
|
os.makedirs(os.path.dirname(output_filepath), exist_ok=True)
|
||||||
|
doc.save(output_filepath)
|
||||||
|
return output_filepath
|
||||||
|
```
|
||||||
|
|
||||||
## File: `./services/presence_service.py`
|
## File: `./services/presence_service.py`
|
||||||
```py
|
```py
|
||||||
"""
|
"""
|
||||||
@@ -5201,6 +5618,7 @@ def generate_otchet_service(
|
|||||||
"""
|
"""
|
||||||
===============================================================================
|
===============================================================================
|
||||||
FILE: services/scud_etl/pipeline.py
|
FILE: services/scud_etl/pipeline.py
|
||||||
|
ROLE: Загрузка наилучших срезов СКУД и штата/отсутствий 1С с умным fallback-ом.
|
||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -5212,7 +5630,7 @@ import pandas as pd
|
|||||||
from core.connection import get_connection
|
from core.connection import get_connection
|
||||||
from core.database import load_scud_from_db_by_snapshot
|
from core.database import load_scud_from_db_by_snapshot
|
||||||
from config import DATA_DIR
|
from config import DATA_DIR
|
||||||
from services.data_loader import load_staff_data, load_absent_data
|
from services.data_loader import load_1c_data_smart, load_staff_data, load_absent_data
|
||||||
|
|
||||||
logger = logging.getLogger("SCUD_PIPELINE")
|
logger = logging.getLogger("SCUD_PIPELINE")
|
||||||
|
|
||||||
@@ -5257,10 +5675,44 @@ def load_best_snapshot_for_date(date_str: str, prefer_final_y: bool = False) ->
|
|||||||
|
|
||||||
def load_1c_files_for_date(date_str: str) -> Tuple[Optional[pd.DataFrame], Optional[pd.DataFrame]]:
|
def load_1c_files_for_date(date_str: str) -> Tuple[Optional[pd.DataFrame], Optional[pd.DataFrame]]:
|
||||||
"""
|
"""
|
||||||
Загружает реестры штата и отсутствий 1С на указанную дату через data_loader.
|
Загружает штат и отсутствия с каскадным fallback:
|
||||||
|
1. Синхронизирует свежие файлы с сетевой шары.
|
||||||
|
2. Загружает штат и отсутствия через load_1c_data_smart(..., use_db=True).
|
||||||
|
3. Если штат пуст — берет последний доступный срез штата из zup_staff в SQLite.
|
||||||
"""
|
"""
|
||||||
df_staff = load_staff_data(date_str)
|
clean_date = date_str.replace('_', '.')
|
||||||
df_abs = load_absent_data(date_str)
|
|
||||||
|
try:
|
||||||
|
from services.share_copier import copy_1c_files_from_share
|
||||||
|
copy_1c_files_from_share()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[Pipeline] Ошибка копирования с шары: {e}")
|
||||||
|
|
||||||
|
df_staff, df_abs = load_1c_data_smart(clean_date, use_db=True)
|
||||||
|
|
||||||
|
# Fallback за штат: ако данашњи штат још увек није доступан, користи се претходни из базе
|
||||||
|
if df_staff is None or df_staff.empty:
|
||||||
|
with get_connection(row_factory=True) as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT snapshot_date
|
||||||
|
FROM zup_staff
|
||||||
|
ORDER BY
|
||||||
|
SUBSTR(snapshot_date, 7, 4) DESC,
|
||||||
|
SUBSTR(snapshot_date, 4, 2) DESC,
|
||||||
|
SUBSTR(snapshot_date, 1, 2) DESC,
|
||||||
|
id DESC
|
||||||
|
LIMIT 1
|
||||||
|
""")
|
||||||
|
row = cursor.fetchone()
|
||||||
|
if row and row[0]:
|
||||||
|
fallback_date = row[0]
|
||||||
|
df_staff = pd.read_sql_query(
|
||||||
|
"SELECT fio as 'ФИО', fio_clean, department as 'Подразделение', position as 'Должность' FROM zup_staff WHERE snapshot_date = ?",
|
||||||
|
conn, params=(fallback_date,)
|
||||||
|
)
|
||||||
|
logger.info(f"[Pipeline] Для даты {clean_date} применен штат за {fallback_date} ({len(df_staff)} чел.)")
|
||||||
|
|
||||||
return df_staff, df_abs
|
return df_staff, df_abs
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -5470,7 +5922,7 @@ import pandas as pd
|
|||||||
|
|
||||||
from config import DATE_TODAY
|
from config import DATE_TODAY
|
||||||
from core.database import load_scud_from_db_by_snapshot
|
from core.database import load_scud_from_db_by_snapshot
|
||||||
from services.scud_etl.pipeline import load_1c_files_for_date
|
from services.scud_etl.pipeline import load_best_snapshot_for_date, load_1c_files_for_date
|
||||||
from services.scud_etl.merger import merge_scud_and_1c, calculate_summary_metrics
|
from services.scud_etl.merger import merge_scud_and_1c, calculate_summary_metrics
|
||||||
from services.scud_etl.anomaly_detector import detect_registry_anomalies
|
from services.scud_etl.anomaly_detector import detect_registry_anomalies
|
||||||
from services.snapshots.finder import find_or_create_snapshot_for_time
|
from services.snapshots.finder import find_or_create_snapshot_for_time
|
||||||
@@ -5485,37 +5937,46 @@ def generate_svodka_service(
|
|||||||
snapshot_id: Optional[str] = None
|
snapshot_id: Optional[str] = None
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Формирует оперативную сводку на указанную дату / время:
|
Формирует оперативную сводку:
|
||||||
- target_date: дата сводки (по умолчанию сегодня).
|
- По умолчанию берет ПОСЛЕДНИЙ готовый снапшот из базы SQLite (без долгого опроса MS SQL).
|
||||||
- target_time: время среза (например '14:30').
|
|
||||||
- snapshot_id: точный ID среза.
|
|
||||||
"""
|
"""
|
||||||
date_clean = str(target_date or DATE_TODAY).replace('_', '.')
|
date_clean = str(target_date or DATE_TODAY).replace('_', '.')
|
||||||
applied_note = ""
|
applied_note = ""
|
||||||
|
|
||||||
# Если передано время, но не указан конкретный snapshot_id — ищем ближайший или запрашиваем экспорт
|
# 1. Загрузка среза СКУД строго из готовых в базе
|
||||||
if target_time and not snapshot_id:
|
if snapshot_id:
|
||||||
found_id, note = find_or_create_snapshot_for_time(date_clean, target_time, allow_ondemand_export=True)
|
df_scud = load_scud_from_db_by_snapshot(date_clean, snapshot_param=snapshot_id)
|
||||||
snapshot_id = found_id
|
elif target_time:
|
||||||
|
found_id, note = find_or_create_snapshot_for_time(date_clean, target_time, allow_ondemand_export=False)
|
||||||
applied_note = note
|
applied_note = note
|
||||||
if note:
|
df_scud = load_scud_from_db_by_snapshot(date_clean, snapshot_param=found_id)
|
||||||
logger.info(note)
|
else:
|
||||||
|
# По умолчанию: берем самый свежий существующий срез за дату
|
||||||
|
df_scud = load_best_snapshot_for_date(date_clean, prefer_final_y=False)
|
||||||
|
|
||||||
df_scud = load_scud_from_db_by_snapshot(date_clean, snapshot_param=snapshot_id)
|
|
||||||
if df_scud is None or df_scud.empty:
|
if df_scud is None or df_scud.empty:
|
||||||
return {
|
return {
|
||||||
"status": "error",
|
"status": "error",
|
||||||
"message": f"Срез СКУД за {date_clean} ({applied_note or snapshot_id or 'последний доступный'}) не найден в базе."
|
"message": f"Срез СКУД за {date_clean} не найден в базе данных."
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Извлекаем время фактического среза для имени файла
|
||||||
|
actual_snap_time = ""
|
||||||
|
if 'snapshot_time' in df_scud.columns and not df_scud.empty:
|
||||||
|
raw_st = str(df_scud['snapshot_time'].iloc[0]).strip()
|
||||||
|
if " " in raw_st:
|
||||||
|
actual_snap_time = raw_st.split()[1][:5].replace(':', '-')
|
||||||
|
|
||||||
|
# 2. Загружаем актуальные кадровые данные 1С (штат + отсутствия + реестры)
|
||||||
df_staff, df_abs = load_1c_files_for_date(date_clean)
|
df_staff, df_abs = load_1c_files_for_date(date_clean)
|
||||||
|
|
||||||
|
# 3. Слияние и расчет
|
||||||
df_merged = merge_scud_and_1c(df_scud, df_staff, df_abs)
|
df_merged = merge_scud_and_1c(df_scud, df_staff, df_abs)
|
||||||
metrics = calculate_summary_metrics(df_merged)
|
metrics = calculate_summary_metrics(df_merged)
|
||||||
anomalies = detect_registry_anomalies(df_merged, df_raw_scud=df_scud)
|
anomalies = detect_registry_anomalies(df_merged, df_raw_scud=df_scud)
|
||||||
|
|
||||||
# Добавляем суффикс времени в имя файла, если сводка строилась на точный срез
|
# 4. Формирование книги Excel
|
||||||
time_suffix = f" на {target_time.replace(':', '-')}" if target_time else ""
|
time_suffix = f" на {actual_snap_time}" if actual_snap_time else ""
|
||||||
filename = f"{format_date_ru(date_clean)} сводка{time_suffix}.xlsx"
|
filename = f"{format_date_ru(date_clean)} сводка{time_suffix}.xlsx"
|
||||||
generate_summary_excel(df_merged, date_str=date_clean, filename=filename)
|
generate_summary_excel(df_merged, date_str=date_clean, filename=filename)
|
||||||
|
|
||||||
@@ -5526,15 +5987,15 @@ def generate_svodka_service(
|
|||||||
"status": "success",
|
"status": "success",
|
||||||
"report_type": "SVODKA",
|
"report_type": "SVODKA",
|
||||||
"date": date_clean,
|
"date": date_clean,
|
||||||
"target_time": target_time,
|
"target_time": actual_snap_time,
|
||||||
"snapshot_id": snapshot_id or "AUTO_LATEST",
|
"snapshot_id": snapshot_id or "LATEST_READY",
|
||||||
"filename": filename,
|
"filename": filename,
|
||||||
"filepath": full_filepath,
|
"filepath": full_filepath,
|
||||||
"download_url": f"/api/v1/files/download/reports/{os.path.basename(full_filepath)}",
|
"download_url": f"/api/v1/files/download/reports/{os.path.basename(full_filepath)}",
|
||||||
"metrics": metrics,
|
"metrics": metrics,
|
||||||
"anomalies_count": len(anomalies),
|
"anomalies_count": len(anomalies),
|
||||||
"note": applied_note,
|
"note": applied_note,
|
||||||
"message": f"Ежедневная сводка на {date_clean} {target_time or ''} успешно сформирована."
|
"message": f"Ежедневная сводка на {date_clean} успешно сформирована."
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -5875,6 +6336,26 @@ def run_export(input_date: str | None = None, input_time: str | None = None, sav
|
|||||||
log("=== [ЭТАП 0] Выгрузка свежих данных СКУД напрямую из БД Орион ===")
|
log("=== [ЭТАП 0] Выгрузка свежих данных СКУД напрямую из БД Орион ===")
|
||||||
os.makedirs(SCUD_DIR, exist_ok=True)
|
os.makedirs(SCUD_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
# ⭐️ 1. ПОЛУЧАСОВАЯ СИНХРОНИЗАЦИЯ 1С:ЗУП (Файлы с шары + База данных)
|
||||||
|
try:
|
||||||
|
log("[1C] Проверка сетевой шары и синхронизация файлов 1С...")
|
||||||
|
copy_1c_files_from_share()
|
||||||
|
|
||||||
|
target_sync_date = input_date or datetime.now().strftime("%d.%m.%Y")
|
||||||
|
# Прямой опрос свежих отсутствий и сохранение в SQLite
|
||||||
|
df_fresh_abs = load_absent_data(target_sync_date)
|
||||||
|
if df_fresh_abs is not None and not df_fresh_abs.empty:
|
||||||
|
save_absences_to_db(df_fresh_abs, target_sync_date)
|
||||||
|
log(f"[1C] [✓] Актуализировано {len(df_fresh_abs)} отсутствий в SQLite за {target_sync_date}", "SUCCESS")
|
||||||
|
|
||||||
|
# Если на шаре появился свежий штат — также обновляем его в базе
|
||||||
|
df_fresh_staff = load_staff_data(target_sync_date)
|
||||||
|
if df_fresh_staff is not None and not df_fresh_staff.empty:
|
||||||
|
save_staff_to_db(df_fresh_staff, target_sync_date)
|
||||||
|
log(f"[1C] [✓] Актуализирован штат ({len(df_fresh_staff)} чел.) в SQLite за {target_sync_date}", "SUCCESS")
|
||||||
|
except Exception as e:
|
||||||
|
log(f"[1C] ⚠️ Ошибка фоновой синхронизации 1С: {e}", "WARNING")
|
||||||
|
|
||||||
targets = get_targets(input_date, input_time)
|
targets = get_targets(input_date, input_time)
|
||||||
conn_str = (
|
conn_str = (
|
||||||
f"DRIVER={{{ODBC_DRIVER}}};"
|
f"DRIVER={{{ODBC_DRIVER}}};"
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ ROLE: Нативный оркестратор диалога, диспетчер
|
|||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -146,6 +147,7 @@ def process_chat_message(
|
|||||||
f" - База знаний и регламенты -> db_get_rules\n"
|
f" - База знаний и регламенты -> db_get_rules\n"
|
||||||
f" - Аномалии СКУД/1С -> db_get_anomalies\n"
|
f" - Аномалии СКУД/1С -> db_get_anomalies\n"
|
||||||
f" - Справка -> db_get_reference\n"
|
f" - Справка -> db_get_reference\n"
|
||||||
|
f" - Распознавание PDF/сканов и экспорт в Word -> office_pdf_to_word\n"
|
||||||
f"3. ЗАДАЧИ:\n"
|
f"3. ЗАДАЧИ:\n"
|
||||||
f" - При любых запросах на просмотр задач (включая опечатки вроде 'змдачи', 'таски', 'дела', 'покажи задачи') — "
|
f" - При любых запросах на просмотр задач (включая опечатки вроде 'змдачи', 'таски', 'дела', 'покажи задачи') — "
|
||||||
f"ТЫ ОБЯЗАН СРАЗУ ВЫЗВАТЬ db_get_tasks без лишних вопросов!\n"
|
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. Снапшоты СКУД
|
# 5. Снапшоты СКУД
|
||||||
elif fn_name == "db_get_snapshots":
|
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)
|
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:
|
if not session_state:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|||||||
@@ -5,22 +5,23 @@ ROLE: Транспортный клиент HTTP взаимодействия с
|
|||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# ANCHOR[OLLAMA_CLIENT_IMPORTS]
|
|
||||||
import json
|
import json
|
||||||
import urllib.request
|
import urllib.request
|
||||||
import urllib.error
|
import urllib.error
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, Any, Optional
|
from typing import Dict, Any, Optional
|
||||||
|
import config
|
||||||
|
|
||||||
logger = logging.getLogger("OLLAMA_CLIENT")
|
logger = logging.getLogger("OLLAMA_CLIENT")
|
||||||
|
|
||||||
OLLAMA_URL = "http://10.121.17.227:11434/api/chat"
|
# Чистый адрес API chat
|
||||||
TEXT_MODEL = "qwen2.5:14b"
|
OLLAMA_URL = getattr(config, "OLLAMA_CHAT_URL", "http://10.121.17.227:11434/api/chat")
|
||||||
VISION_MODEL = "qwen2.5vl:7b-q8_0"
|
TEXT_MODEL = getattr(config, "OLLAMA_MODEL", "qwen2.5:14b")
|
||||||
|
VISION_MODEL = getattr(config, "VISION_MODEL", "qwen2.5vl:7b-q8_0")
|
||||||
|
|
||||||
LLM_OPTIONS = {
|
LLM_OPTIONS = {
|
||||||
"num_predict": 8192,
|
"num_predict": 8192,
|
||||||
"num_ctx": 8192,
|
"num_ctx": 16384, # Увеличенный контекст под сканы высокого разрешения
|
||||||
"temperature": 0.0,
|
"temperature": 0.0,
|
||||||
"repeat_penalty": 1.0,
|
"repeat_penalty": 1.0,
|
||||||
"presence_penalty": 0.0,
|
"presence_penalty": 0.0,
|
||||||
@@ -28,18 +29,22 @@ LLM_OPTIONS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# ANCHOR[OLLAMA_REQUEST_DISPATCHER]
|
|
||||||
def call_ollama_chat(
|
def call_ollama_chat(
|
||||||
messages: list,
|
messages: list,
|
||||||
tools: Optional[list] = None,
|
tools: Optional[list] = None,
|
||||||
is_vision: bool = False,
|
is_vision: bool = False,
|
||||||
timeout: int = 120
|
timeout: int = 240,
|
||||||
|
model: Optional[str] = None
|
||||||
) -> Dict[str, Any]:
|
) -> 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 = {
|
payload = {
|
||||||
"model": model_name,
|
"model": model_name,
|
||||||
"messages": messages,
|
"messages": messages,
|
||||||
|
|||||||
@@ -33,4 +33,21 @@ def inject_tools_if_needed(user_message: str, raw_reply: str, existing_tool_call
|
|||||||
Модель управляется через TOOLS_SCHEMA и системный контекст.
|
Модель управляется через TOOLS_SCHEMA и системный контекст.
|
||||||
Любые синтетические перехваты текста регулярными выражениями отключены согласно ROADMAP.
|
Любые синтетические перехваты текста регулярными выражениями отключены согласно 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 os
|
||||||
import subprocess
|
import base64
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
from typing import Dict, Any, List
|
||||||
|
|
||||||
logger = logging.getLogger("FILE_PARSER")
|
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:
|
try:
|
||||||
# 1. ИЗОБРАЖЕНИЯ (.png, .jpg, .jpeg, .bmp, .webp) -> Кодируем в Base64 для Vision LLM
|
import pypdf
|
||||||
if ext in ['.png', '.jpg', '.jpeg', '.bmp', '.webp']:
|
reader = pypdf.PdfReader(file_path)
|
||||||
b64_str = base64.b64encode(file_bytes).decode('utf-8')
|
for idx, page in enumerate(reader.pages, start=1):
|
||||||
return {
|
t = page.extract_text() or ""
|
||||||
"text": f"[ПРИКРЕПЛЕНО ИЗОБРАЖЕНИЕ: {filename}]",
|
if t.strip():
|
||||||
"image_b64": b64_str
|
text_pages.append(f"--- Страница {idx} ---\n{t.strip()}")
|
||||||
}
|
|
||||||
|
|
||||||
# 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
|
|
||||||
}
|
|
||||||
|
|
||||||
except Exception as e:
|
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 {
|
return {
|
||||||
"text": f"[ОШИБКА ОБРАБОТКИ ФАЙЛА: {str(e)}]",
|
"has_text": True,
|
||||||
"image_b64": None
|
"text": full_text,
|
||||||
|
"image_b64": None,
|
||||||
|
"pages_count": len(text_pages)
|
||||||
}
|
}
|
||||||
finally:
|
|
||||||
if os.path.exists(temp_filepath):
|
# 3. Если текста мало или это чистый скан — рендерим первую страницу через PyMuPDF для Vision
|
||||||
os.remove(temp_filepath)
|
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");
|
const userInputEl = document.getElementById("user-input");
|
||||||
if (userInputEl) {
|
if (userInputEl) {
|
||||||
userInputEl.addEventListener("input", function() {
|
userInputEl.addEventListener("input", function() {
|
||||||
this.style.height = "24px";
|
this.style.height = "32px";
|
||||||
const newHeight = Math.min(this.scrollHeight, 120);
|
const newHeight = Math.min(this.scrollHeight, 140);
|
||||||
this.style.height = newHeight + "px";
|
this.style.height = newHeight + "px";
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
===============================================================================
|
===============================================================================
|
||||||
FILE: services/office/document_extractor.py
|
FILE: services/office/document_extractor.py
|
||||||
PROJECT: SCUD Orion AI (Office Domain)
|
ROLE: Постраничный OCR на базе Qwen3-VL (qwen3-vl:8b).
|
||||||
ROLE: Постраничное извлечение текста и OCR сканов документов через Vision LLM.
|
|
||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -10,80 +9,72 @@ import os
|
|||||||
import base64
|
import base64
|
||||||
import logging
|
import logging
|
||||||
from typing import List, Dict, Any, Optional
|
from typing import List, Dict, Any, Optional
|
||||||
|
import pymupdf as fitz
|
||||||
import fitz # PyMuPDF
|
|
||||||
from modules.web_api.llm.core.ollama_client import call_ollama_chat
|
from modules.web_api.llm.core.ollama_client import call_ollama_chat
|
||||||
|
|
||||||
logger = logging.getLogger("OFFICE_EXTRACTOR")
|
logger = logging.getLogger("OFFICE_EXTRACTOR")
|
||||||
|
|
||||||
|
TARGET_VISION_MODEL = "qwen2.5vl:7b-q8_0"
|
||||||
|
|
||||||
|
|
||||||
def ocr_image_b64(image_b64: str, page_num: int = 1) -> str:
|
def ocr_image_b64(image_b64: str, page_num: int = 1) -> str:
|
||||||
"""
|
"""
|
||||||
Распознает текст с одного растрового изображения через Qwen 2.5 VL.
|
Распознавание страницы через qwen3-vl:8b с табличным форматированием.
|
||||||
"""
|
"""
|
||||||
system_prompt = (
|
system_prompt = (
|
||||||
"Ты — высокоточный профессиональный модуль OCR для канцелярии и документооборота.\n"
|
"Ты — высокоточный сканер оптического распознавания документов (OCR).\n"
|
||||||
"Твоя задача — точно переписать весь текст с предоставленного изображения документа.\n"
|
"Твоя задача — точно переписать текст со скана слово в слово в формате Markdown.\n\n"
|
||||||
"ПРАВИЛА:\n"
|
"ПРАВИЛА:\n"
|
||||||
"1. Переписывай текст дословно, сохраняя структуру, заголовки, списки, нумерацию и таблицы.\n"
|
"1. Переписывай ТОЛЬКО то, что реально есть на изображении. Не фантазируй и не сокращай.\n"
|
||||||
"2. Запрещено добавлять вводные слова, приветствия, комментарии ('Спасибо за обращение', 'Вот текст' и т.д.).\n"
|
"2. Рукописные визы, пометки и резолюции пиши в начале страницы: [Рукописный текст: ...].\n"
|
||||||
"3. Выводи СТРОГО чистый распознанный текст документа."
|
" Если рукописного текста на странице нет — НЕ ПИШИ блок резолюции.\n"
|
||||||
|
"3. СПИСКИ УЧАСТНИКОВ И ТАБЛИЦЫ: Если на странице идет перечисление участников совещания "
|
||||||
|
"(ФИО, должность, ведомство), ОБЯЗАТЕЛЬНО оформляй их в виде ровной Markdown-таблицы:\n"
|
||||||
|
" | № | Ведомство / Организация | Должность | ФИО | Примечание |\n"
|
||||||
|
"4. Обычный сплошной текст (пункты, решения, преамбулу) оформляй абзацами БЕЗ знаков '|'.\n"
|
||||||
|
"5. Не оборачивай ответ в ```markdown или ```. Выводи сразу готовый текст."
|
||||||
)
|
)
|
||||||
|
|
||||||
user_message = {
|
user_message = {
|
||||||
"role": "user",
|
"role": "user",
|
||||||
"content": f"Распознай весь печатный и рукописный текст страницы №{page_num} без пропусков.",
|
"content": f"Точно распознай текст страницы {page_num} без пропусков. Таблицы и участников оформляй Markdown-таблицей.",
|
||||||
"images": [image_b64]
|
"images": [image_b64]
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
res = call_ollama_chat(
|
res = call_ollama_chat(
|
||||||
messages=[{"role": "system", "content": system_prompt}, user_message],
|
messages=[{"role": "system", "content": system_prompt}, user_message],
|
||||||
is_vision=True,
|
is_vision=True,
|
||||||
timeout=300 # 5 минут на тяжелые страницы
|
timeout=240,
|
||||||
|
model=TARGET_VISION_MODEL
|
||||||
)
|
)
|
||||||
return (res.get("content") or "").strip()
|
return (res.get("content") or "").strip()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"[Office OCR] Ошибка распознавания страницы {page_num}: {e}")
|
logger.error(f"[Office OCR Qwen3] Ошибка на стр. {page_num}: {e}")
|
||||||
return f"[Ошибка распознавания страницы {page_num}: {e}]"
|
return f"[Ошибка распознавания страницы {page_num}: {e}]"
|
||||||
|
|
||||||
|
|
||||||
def process_pdf_full(file_path: str, max_pages: Optional[int] = None) -> List[Dict[str, Any]]:
|
def process_pdf_full(file_path: str, max_pages: Optional[int] = None) -> List[Dict[str, Any]]:
|
||||||
"""
|
|
||||||
Обрабатывает PDF целиком:
|
|
||||||
- Если есть качественный цифровой текст — мгновенно извлекает его со всех страниц.
|
|
||||||
- Если страница является сканом/картинкой — рендерит ее в 200 DPI и прогоняет через Vision OCR.
|
|
||||||
"""
|
|
||||||
results = []
|
results = []
|
||||||
doc = fitz.open(file_path)
|
doc = fitz.open(file_path)
|
||||||
total_pages = len(doc)
|
total_pages = len(doc)
|
||||||
limit = min(total_pages, max_pages) if max_pages else total_pages
|
limit = min(total_pages, max_pages) if max_pages else total_pages
|
||||||
|
|
||||||
logger.info(f"[Office] Начало обработки PDF: {os.path.basename(file_path)} (всего страниц: {total_pages})")
|
logger.info(f"[Office] Старт распознавания {os.path.basename(file_path)}: {limit} из {total_pages} стр. на модели {TARGET_VISION_MODEL}")
|
||||||
|
|
||||||
for idx in range(limit):
|
for idx in range(limit):
|
||||||
page_num = idx + 1
|
page_num = idx + 1
|
||||||
page = doc[idx]
|
page = doc[idx]
|
||||||
extracted_text = (page.get_text("text") or "").strip()
|
|
||||||
|
|
||||||
# Если на странице есть хороший машинный текст (не скан)
|
# 200 DPI обеспечивает достаточную детализацию для Qwen3-VL
|
||||||
if len(extracted_text) > 80:
|
pix = page.get_pixmap(dpi=200)
|
||||||
logger.info(f"[Office] Страница {page_num}/{limit}: извлечен цифровой текст ({len(extracted_text)} симв.)")
|
img_b64 = base64.b64encode(pix.tobytes("png")).decode("utf-8")
|
||||||
results.append({
|
|
||||||
"page": page_num,
|
raw_text = ocr_image_b64(img_b64, page_num=page_num)
|
||||||
"method": "DIGITAL_TEXT",
|
results.append({
|
||||||
"text": extracted_text
|
"page": page_num,
|
||||||
})
|
"text": raw_text
|
||||||
else:
|
})
|
||||||
# Чистый скан — рендерим страницу в PNG и передаем в Vision LLM
|
|
||||||
logger.info(f"[Office] Страница {page_num}/{limit}: распознавание скана через Ollama Vision...")
|
|
||||||
pix = page.get_pixmap(dpi=200)
|
|
||||||
img_b64 = base64.b64encode(pix.tobytes("png")).decode("utf-8")
|
|
||||||
|
|
||||||
ocr_text = ocr_image_b64(img_b64, page_num=page_num)
|
|
||||||
results.append({
|
|
||||||
"page": page_num,
|
|
||||||
"method": "VISION_OCR",
|
|
||||||
"text": ocr_text
|
|
||||||
})
|
|
||||||
|
|
||||||
doc.close()
|
doc.close()
|
||||||
return results
|
return results
|
||||||
+46
-14
@@ -1,12 +1,12 @@
|
|||||||
"""
|
"""
|
||||||
===============================================================================
|
===============================================================================
|
||||||
FILE: services/office/service.py
|
FILE: services/office/service.py
|
||||||
PROJECT: SCUD Orion AI (Office Domain)
|
ROLE: Детерминированная сборка Word без галлюцинаций.
|
||||||
ROLE: Единый фасад офисного модуля для вызова из API и фоновых задач.
|
|
||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import uuid
|
import uuid
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
@@ -21,35 +21,67 @@ OFFICE_OUTPUT_DIR = os.path.join(BASE_DIR, "output", "web", "office")
|
|||||||
os.makedirs(OFFICE_OUTPUT_DIR, exist_ok=True)
|
os.makedirs(OFFICE_OUTPUT_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def clean_page_text(text: str, page_num: int) -> str:
|
||||||
|
"""Детерминированная очистка страницы от шума и галлюцинаций."""
|
||||||
|
lines = text.splitlines()
|
||||||
|
cleaned_lines = []
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
l = line.strip()
|
||||||
|
if not l:
|
||||||
|
cleaned_lines.append("")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 1. Срезаем фантомные резолюции со всех страниц, кроме 1 и 2
|
||||||
|
if page_num > 2 and any(k in l.lower() for k in ["резолюция:", "рукописный текст:"]):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 2. Срезаем приветствия
|
||||||
|
if any(l.lower().startswith(g) for g in ["спасибо за", "здравствуйте", "вот текст"]):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 3. Убираем markdown-обертки ```
|
||||||
|
if l.startswith("```"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
cleaned_lines.append(l)
|
||||||
|
|
||||||
|
return "\n".join(cleaned_lines).strip()
|
||||||
|
|
||||||
|
|
||||||
def convert_pdf_to_word_service(file_path: str, original_filename: str) -> Dict[str, Any]:
|
def convert_pdf_to_word_service(file_path: str, original_filename: str) -> Dict[str, Any]:
|
||||||
"""
|
|
||||||
Полный цикл: Постраничный OCR скана PDF -> Сборка документа DOCX -> Ссылка на скачивание.
|
|
||||||
"""
|
|
||||||
session_id = str(uuid.uuid4())[:8]
|
session_id = str(uuid.uuid4())[:8]
|
||||||
base_name = os.path.splitext(os.path.basename(original_filename))[0]
|
base_name = os.path.splitext(os.path.basename(original_filename))[0]
|
||||||
out_docx_name = f"{base_name}_распознан.docx"
|
out_docx_name = f"{base_name}_распознан.docx"
|
||||||
|
|
||||||
target_dir = os.path.join(OFFICE_OUTPUT_DIR, session_id)
|
target_dir = os.path.join(OFFICE_OUTPUT_DIR, session_id)
|
||||||
os.makedirs(target_dir, exist_ok=True)
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
out_docx_path = os.path.join(target_dir, out_docx_name)
|
out_docx_path = os.path.join(target_dir, out_docx_name)
|
||||||
|
|
||||||
# 1. Постраничный парсинг всех страниц
|
# Постраничный честный OCR без фантазий
|
||||||
pages = process_pdf_full(file_path)
|
raw_pages = process_pdf_full(file_path)
|
||||||
|
|
||||||
# 2. Сборка Word-документа
|
sanitized_pages = []
|
||||||
build_docx_from_ocr(pages, out_docx_path, doc_title=base_name)
|
for p in raw_pages:
|
||||||
|
p_num = p.get("page", 1)
|
||||||
|
cleaned = clean_page_text(p.get("text", ""), page_num=p_num)
|
||||||
|
sanitized_pages.append({
|
||||||
|
"page": p_num,
|
||||||
|
"text": cleaned
|
||||||
|
})
|
||||||
|
|
||||||
# 3. Краткое превью для окна чата
|
# Сборка в Word
|
||||||
preview_sample = pages[0]["text"][:600] if pages else "Документ распознан."
|
build_docx_from_ocr(sanitized_pages, out_docx_path, doc_title=base_name)
|
||||||
|
|
||||||
|
preview_sample = sanitized_pages[0]["text"][:600] if sanitized_pages else "Документ распознан."
|
||||||
download_url = f"/api/v1/files/download/office/{session_id}/{out_docx_name}"
|
download_url = f"/api/v1/files/download/office/{session_id}/{out_docx_name}"
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"total_pages": len(pages),
|
"total_pages": len(sanitized_pages),
|
||||||
"filename": out_docx_name,
|
"filename": out_docx_name,
|
||||||
"filepath": out_docx_path,
|
"filepath": out_docx_path,
|
||||||
"download_url": download_url,
|
"download_url": download_url,
|
||||||
"preview_text": preview_sample,
|
"preview_text": preview_sample,
|
||||||
"message": f"Документ успешно распознан целиком ({len(pages)} стр.) и собран в MS Word."
|
"message": f"Документ точно распознан ({len(sanitized_pages)} стр.) без искажений."
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""
|
||||||
|
===============================================================================
|
||||||
|
FILE: services/office/text_refiner.py
|
||||||
|
PROJECT: SCUD Orion AI (Office Domain)
|
||||||
|
ROLE: Фаза 2: Постобработка и вычитка текста через текстовую LLM (qwen2.5:14b).
|
||||||
|
Устранение артефактов OCR, склейка разорванных предложений,
|
||||||
|
удаление диалогового мусора и форматирование списков в Markdown-таблицы.
|
||||||
|
===============================================================================
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import logging
|
||||||
|
from modules.web_api.llm.core.ollama_client import call_ollama_chat
|
||||||
|
|
||||||
|
logger = logging.getLogger("TEXT_REFINER")
|
||||||
|
|
||||||
|
|
||||||
|
def refine_ocr_page_text(raw_text: str, page_num: int = 1) -> str:
|
||||||
|
"""
|
||||||
|
Нормализует черновой текст OCR:
|
||||||
|
- Очищает от приветствий и служебных фраз.
|
||||||
|
- Склеивает разорванные строки внутри предложений.
|
||||||
|
- Форматирует списки участников совещания в Markdown-таблицы.
|
||||||
|
- Сохраняет блоки [Резолюция: ...].
|
||||||
|
"""
|
||||||
|
if not raw_text or len(raw_text.strip()) < 10:
|
||||||
|
return raw_text
|
||||||
|
|
||||||
|
system_prompt = (
|
||||||
|
"Ты — строгий технический редактор и корректор официальных протоколов и документов.\n"
|
||||||
|
"Тебе передан черновой текст оптического распознавания (OCR) одной страницы документа.\n\n"
|
||||||
|
"ТВОИ ЗАДАЧИ:\n"
|
||||||
|
"1. УДАЛИ любой диалоговый шум: 'Спасибо за обращение', 'Здравствуйте', 'Вот текст' и т.п.\n"
|
||||||
|
"2. БЛОКИ РЕЗОЛЮЦИЙ: Если в тексте есть рукописная резолюция или блок '[Резолюция: ...]', "
|
||||||
|
"сохрани его в самом верху страницы.\n"
|
||||||
|
"3. СКЛЕЙКА АБЗАЦЕВ: Соединяй строки, разорванные при переносе, в связные абзацы. Не оставляй рваных строк.\n"
|
||||||
|
"4. СПИСКИ УЧАСТНИКОВ И ТАБЛИЦЫ: Если на странице идет перечисление участников совещания (ФИО, ведомство, должность), "
|
||||||
|
"ОБЯЗАТЕЛЬНО преобразуй их в ровную Markdown-таблицу:\n"
|
||||||
|
"| № | Ведомство / Организация | Должность | ФИО | Формат |\n"
|
||||||
|
"5. СОХРАНЯЙ все официальные заголовки ('ПРЕДСЕДАТЕЛЬСТВОВАЛ', 'РЕШИЛИ:', 'ОТМЕТИЛИ:').\n"
|
||||||
|
"6. Запрещено сокращать или пересказывать суть. Выводи полный текст документа."
|
||||||
|
)
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt},
|
||||||
|
{"role": "user", "content": f"Вычитай и приведи к стандарту делопроизводства страницу №{page_num}:\n\n{raw_text}"}
|
||||||
|
]
|
||||||
|
|
||||||
|
try:
|
||||||
|
res = call_ollama_chat(messages, is_vision=False, timeout=120)
|
||||||
|
refined = (res.get("content") or "").strip()
|
||||||
|
|
||||||
|
# Снимаем возможное оборачивание в ```markdown
|
||||||
|
refined = re.sub(r'^```[a-zA-Z]*\n', '', refined)
|
||||||
|
refined = re.sub(r'\n```$', '', refined)
|
||||||
|
|
||||||
|
# Страховочное отсечение фраз вежливости
|
||||||
|
for junk in ["Спасибо за обращение", "Здравствуйте", "Вот вычитанный текст"]:
|
||||||
|
if refined.startswith(junk):
|
||||||
|
refined = refined[len(junk):].lstrip(" ,.:!\n")
|
||||||
|
|
||||||
|
return refined
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[TextRefiner] Ошибка рефайнинга страницы {page_num}: {e}")
|
||||||
|
return raw_text
|
||||||
@@ -2,51 +2,117 @@
|
|||||||
===============================================================================
|
===============================================================================
|
||||||
FILE: services/office/word_builder.py
|
FILE: services/office/word_builder.py
|
||||||
PROJECT: SCUD Orion AI (Office Domain)
|
PROJECT: SCUD Orion AI (Office Domain)
|
||||||
ROLE: Сборка форматированного документа MS Word (.docx) из распознанного текста.
|
ROLE: Фаза 3: Сборка форматированного документа MS Word (.docx):
|
||||||
|
- Поддержка нативных таблиц Word (Table Grid) из Markdown.
|
||||||
|
- Специальное выделение блоков рукописных резолюций.
|
||||||
|
- ГОСТ-оформление (Times New Roman, поля, отступы).
|
||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from typing import List, Dict, Any
|
from typing import List, Dict, Any
|
||||||
from docx import Document
|
from docx import Document
|
||||||
from docx.shared import Pt, Inches
|
from docx.shared import Pt, Inches, RGBColor
|
||||||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
|
from docx.oxml import OxmlElement
|
||||||
|
from docx.oxml.ns import qn
|
||||||
|
|
||||||
|
|
||||||
|
def set_cell_margins(cell, top=100, bottom=100, left=150, right=150):
|
||||||
|
"""Устанавливает внутренние поля ячейки таблицы."""
|
||||||
|
tcPr = cell._tc.get_or_add_tcPr()
|
||||||
|
tcMar = OxmlElement('w:tcMar')
|
||||||
|
for m, val in [('top', top), ('bottom', bottom), ('left', left), ('right', right)]:
|
||||||
|
node = OxmlElement(f'w:{m}')
|
||||||
|
node.set(qn('w:w'), str(val))
|
||||||
|
node.set(qn('w:type'), 'dxa')
|
||||||
|
tcMar.append(node)
|
||||||
|
tcPr.append(tcMar)
|
||||||
|
|
||||||
|
|
||||||
def build_docx_from_ocr(pages_data: List[Dict[str, Any]], output_filepath: str, doc_title: str = "Распознанный документ") -> str:
|
def build_docx_from_ocr(pages_data: List[Dict[str, Any]], output_filepath: str, doc_title: str = "Распознанный документ") -> str:
|
||||||
"""
|
|
||||||
Создает файл .docx по ГОСТ-стандартам делопроизводства:
|
|
||||||
- Шрифт Times New Roman 12-14pt.
|
|
||||||
- Межстрочный интервал 1.15.
|
|
||||||
- Разделители страниц и колонтитулы.
|
|
||||||
"""
|
|
||||||
doc = Document()
|
doc = Document()
|
||||||
|
|
||||||
sections = doc.sections
|
# Поля страницы по ГОСТ (2 см по бокам и сверху, 1.5 см справа)
|
||||||
for section in sections:
|
for section in doc.sections:
|
||||||
section.top_margin = Inches(0.79)
|
section.top_margin = Inches(0.79)
|
||||||
section.bottom_margin = Inches(0.79)
|
section.bottom_margin = Inches(0.79)
|
||||||
section.left_margin = Inches(0.79)
|
section.left_margin = Inches(0.79)
|
||||||
section.right_margin = Inches(0.59)
|
section.right_margin = Inches(0.59)
|
||||||
|
|
||||||
for p_idx, page in enumerate(pages_data):
|
for p_idx, page in enumerate(pages_data):
|
||||||
page_num = page.get("page", p_idx + 1)
|
|
||||||
text_content = page.get("text", "")
|
text_content = page.get("text", "")
|
||||||
|
|
||||||
if p_idx > 0:
|
if p_idx > 0:
|
||||||
doc.add_page_break()
|
doc.add_page_break()
|
||||||
|
|
||||||
lines = text_content.splitlines()
|
lines = text_content.splitlines()
|
||||||
|
table_buffer = []
|
||||||
|
|
||||||
|
def flush_table():
|
||||||
|
nonlocal table_buffer
|
||||||
|
if not table_buffer:
|
||||||
|
return
|
||||||
|
|
||||||
|
parsed_rows = []
|
||||||
|
for t_line in table_buffer:
|
||||||
|
cells = [c.strip() for c in t_line.strip().strip('|').split('|')]
|
||||||
|
# Пропускаем разделительные строки Markdown (|---|---|)
|
||||||
|
if any(cells) and not all(set(c).issubset({'-', ':', ' '}) for c in cells):
|
||||||
|
parsed_rows.append(cells)
|
||||||
|
|
||||||
|
if parsed_rows:
|
||||||
|
num_cols = max(len(r) for r in parsed_rows)
|
||||||
|
tbl = doc.add_table(rows=len(parsed_rows), cols=num_cols)
|
||||||
|
tbl.style = 'Table Grid'
|
||||||
|
|
||||||
|
for r_idx, row_data in enumerate(parsed_rows):
|
||||||
|
for c_idx in range(num_cols):
|
||||||
|
val = row_data[c_idx] if c_idx < len(row_data) else ""
|
||||||
|
cell = tbl.cell(r_idx, c_idx)
|
||||||
|
cell.text = val
|
||||||
|
set_cell_margins(cell)
|
||||||
|
for para in cell.paragraphs:
|
||||||
|
para.paragraph_format.line_spacing = 1.05
|
||||||
|
para.paragraph_format.space_after = Pt(2)
|
||||||
|
for run in para.runs:
|
||||||
|
run.font.name = "Times New Roman"
|
||||||
|
run.font.size = Pt(10)
|
||||||
|
if r_idx == 0:
|
||||||
|
run.font.bold = True
|
||||||
|
|
||||||
|
table_buffer = []
|
||||||
|
|
||||||
for line in lines:
|
for line in lines:
|
||||||
line_str = line.strip()
|
line_str = line.strip()
|
||||||
if not line_str:
|
if not line_str:
|
||||||
|
flush_table()
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Детекция строки Markdown-таблицы
|
||||||
|
if line_str.startswith('|') and line_str.endswith('|'):
|
||||||
|
table_buffer.append(line_str)
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
flush_table()
|
||||||
|
|
||||||
|
# Обработка блока рукописной резолюции
|
||||||
|
if line_str.startswith('[Резолюция:') or line_str.startswith('Резолюция:'):
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.paragraph_format.space_after = Pt(6)
|
||||||
|
p.paragraph_format.line_spacing = 1.15
|
||||||
|
run = p.add_run(f"✍️ {line_str}")
|
||||||
|
run.font.name = "Times New Roman"
|
||||||
|
run.font.size = Pt(11)
|
||||||
|
run.font.italic = True
|
||||||
|
run.font.color.rgb = RGBColor(15, 76, 129) # Классический синий цвет визы
|
||||||
continue
|
continue
|
||||||
|
|
||||||
p = doc.add_paragraph()
|
p = doc.add_paragraph()
|
||||||
p.paragraph_format.space_after = Pt(3)
|
p.paragraph_format.space_after = Pt(4)
|
||||||
p.paragraph_format.line_spacing = 1.15
|
p.paragraph_format.line_spacing = 1.15
|
||||||
|
|
||||||
if any(h in line_str.upper() for h in ["ПРЕДСЕДАТЕЛЬСТВОВАЛ", "ПРОТОКОЛ", "ПОВЕСТКА", "РЕШИЛИ:", "ОТМЕТИЛИ:"]):
|
# Выравнивание заголовков
|
||||||
|
if any(h in line_str.upper() for h in ["ПРЕДСЕДАТЕЛЬСТВОВАЛ", "ПРОТОКОЛ", "ПОВЕСТКА", "РЕШИЛИ:", "ОТМЕТИЛИ:", "СПИСОК УЧАСТНИКОВ"]):
|
||||||
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
run = p.add_run(line_str)
|
run = p.add_run(line_str)
|
||||||
run.font.name = "Times New Roman"
|
run.font.name = "Times New Roman"
|
||||||
@@ -58,6 +124,8 @@ def build_docx_from_ocr(pages_data: List[Dict[str, Any]], output_filepath: str,
|
|||||||
run.font.name = "Times New Roman"
|
run.font.name = "Times New Roman"
|
||||||
run.font.size = Pt(12)
|
run.font.size = Pt(12)
|
||||||
|
|
||||||
|
flush_table()
|
||||||
|
|
||||||
os.makedirs(os.path.dirname(output_filepath), exist_ok=True)
|
os.makedirs(os.path.dirname(output_filepath), exist_ok=True)
|
||||||
doc.save(output_filepath)
|
doc.save(output_filepath)
|
||||||
return output_filepath
|
return output_filepath
|
||||||
+11
-187
@@ -2,9 +2,7 @@
|
|||||||
===============================================================================
|
===============================================================================
|
||||||
FILE: services/scud_export.py
|
FILE: services/scud_export.py
|
||||||
ROLE: Прямой экспорт данных СКУД Орион (MS SQL) в SQLite и чистый Excel (XlsxWriter).
|
ROLE: Прямой экспорт данных СКУД Орион (MS SQL) в SQLite и чистый Excel (XlsxWriter).
|
||||||
Корректная фильтрация транзитных проходов турникетов парковки и двора.
|
Фильтрация транзитных проходов турникетов парковки, правого PERCo и Флигеля.
|
||||||
Учет только левого PERCo (DoorIndex = 1), правого PERCo (DoorIndex = 2)
|
|
||||||
и входа через Флигель (DoorIndex = 23).
|
|
||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -24,11 +22,17 @@ import pandas as pd
|
|||||||
import pyodbc
|
import pyodbc
|
||||||
import xlsxwriter
|
import xlsxwriter
|
||||||
|
|
||||||
|
# Запросы импортируются из единого источника
|
||||||
from services.scud_etl.sql_queries import SQL_QUERY_TEMPLATE, SQL_RAW_EVENTS_QUERY
|
from services.scud_etl.sql_queries import SQL_QUERY_TEMPLATE, SQL_RAW_EVENTS_QUERY
|
||||||
from config import SCUD_DIR, clean_scud_fio_light, load_exceptions
|
from config import SCUD_DIR, clean_scud_fio_light, load_exceptions
|
||||||
from core.database import save_scud_to_db, has_scud_logs_for_date, has_yesterday_final_snapshot
|
from core.database import save_scud_to_db, has_scud_logs_for_date, has_yesterday_final_snapshot
|
||||||
from core.repositories.scud_repo import save_raw_events_to_db
|
from core.repositories.scud_repo import save_raw_events_to_db
|
||||||
|
|
||||||
|
# Фоновая синхронизация кадровых реестров 1С
|
||||||
|
from services.share_copier import copy_1c_files_from_share
|
||||||
|
from services.data_loader import load_absent_data, load_staff_data
|
||||||
|
from core.repositories.zup_repo import save_absences_to_db, save_staff_to_db
|
||||||
|
|
||||||
warnings.filterwarnings("ignore", message="pandas only supports SQLAlchemy connectable")
|
warnings.filterwarnings("ignore", message="pandas only supports SQLAlchemy connectable")
|
||||||
|
|
||||||
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
@@ -76,184 +80,6 @@ SQL_USER = "sa"
|
|||||||
SQL_PASSWORD = "123456"
|
SQL_PASSWORD = "123456"
|
||||||
ODBC_DRIVER = "ODBC Driver 18 for SQL Server"
|
ODBC_DRIVER = "ODBC Driver 18 for SQL Server"
|
||||||
|
|
||||||
SQL_QUERY_TEMPLATE = r"""
|
|
||||||
DECLARE @InputDate DATE = '{target_date}';
|
|
||||||
DECLARE @TargetDate DATE = @InputDate;
|
|
||||||
|
|
||||||
DECLARE @StartDate DATETIME = CAST(@TargetDate AS DATETIME);
|
|
||||||
DECLARE @EndDate DATETIME = {end_datetime_sql};
|
|
||||||
|
|
||||||
WITH PercoPassages AS (
|
|
||||||
-- Физические факты прохода (Event = 32)
|
|
||||||
SELECT
|
|
||||||
log.HozOrgan AS EmployeeID,
|
|
||||||
log.TimeVal,
|
|
||||||
CASE
|
|
||||||
WHEN log.Mode = 1 THEN 'IN'
|
|
||||||
WHEN log.Mode = 2 THEN 'OUT'
|
|
||||||
ELSE 'OTHER'
|
|
||||||
END AS Direction
|
|
||||||
FROM pLogData log WITH (NOLOCK)
|
|
||||||
INNER JOIN pList p WITH (NOLOCK) ON log.HozOrgan = p.ID
|
|
||||||
LEFT JOIN PDivision div WITH (NOLOCK) ON p.Section = div.ID
|
|
||||||
WHERE log.TimeVal BETWEEN @StartDate AND @EndDate
|
|
||||||
AND log.HozOrgan IS NOT NULL
|
|
||||||
AND log.HozOrgan > 0
|
|
||||||
AND log.Event = 32
|
|
||||||
AND log.Mode IN (1, 2)
|
|
||||||
AND (
|
|
||||||
-- Контур 1: Левый турникет открыт для всех
|
|
||||||
log.DoorIndex = 1
|
|
||||||
OR
|
|
||||||
-- Контур 2: Правый турникет разрешен только для реестра двора
|
|
||||||
(
|
|
||||||
log.DoorIndex = 2
|
|
||||||
AND ({turnstile_filter_sql})
|
|
||||||
)
|
|
||||||
OR
|
|
||||||
-- Контур 3: Флигель 1 эт. разрешен только для реестра флигеля
|
|
||||||
(
|
|
||||||
log.DoorIndex = 23
|
|
||||||
AND ({fligel_filter_sql})
|
|
||||||
)
|
|
||||||
)
|
|
||||||
),
|
|
||||||
Passages AS (
|
|
||||||
SELECT
|
|
||||||
EmployeeID,
|
|
||||||
MIN(TimeVal) AS FirstRawEvent,
|
|
||||||
MAX(TimeVal) AS LastRawEvent,
|
|
||||||
MIN(CASE WHEN Direction = 'IN' THEN TimeVal END) AS FirstIn,
|
|
||||||
MAX(CASE WHEN Direction = 'OUT' THEN TimeVal END) AS FinalOut
|
|
||||||
FROM PercoPassages
|
|
||||||
GROUP BY EmployeeID
|
|
||||||
),
|
|
||||||
EvaluatedPassages AS (
|
|
||||||
SELECT
|
|
||||||
p.*,
|
|
||||||
CASE
|
|
||||||
WHEN p.FinalOut IS NOT NULL
|
|
||||||
AND p.FirstIn IS NOT NULL
|
|
||||||
AND p.FinalOut > DATEADD(MINUTE, 5, p.FirstIn)
|
|
||||||
THEN p.FinalOut
|
|
||||||
ELSE NULL
|
|
||||||
END AS FilteredLastOut
|
|
||||||
FROM Passages p
|
|
||||||
)
|
|
||||||
SELECT
|
|
||||||
N'ЛЕНМОРНИИПРОЕКТ' AS [Фирма],
|
|
||||||
ISNULL(CAST(div.Name AS NVARCHAR(255)), N'Без подразделения') AS [Подразделение],
|
|
||||||
LTRIM(RTRIM(
|
|
||||||
ISNULL(CAST(p.Name AS NVARCHAR(255)), N'') +
|
|
||||||
CASE WHEN p.FirstName IS NOT NULL AND CAST(p.FirstName AS NVARCHAR(255)) <> ''
|
|
||||||
THEN N' ' + CAST(p.FirstName AS NVARCHAR(255)) ELSE N'' END +
|
|
||||||
CASE WHEN p.MidName IS NOT NULL AND CAST(p.MidName AS NVARCHAR(255)) <> ''
|
|
||||||
THEN N' ' + CAST(p.MidName AS NVARCHAR(255)) ELSE N'' END
|
|
||||||
)) AS [Сотрудник],
|
|
||||||
ISNULL(CAST(post.Name AS NVARCHAR(255)), N'—') AS [Должность],
|
|
||||||
ISNULL(CAST(p.TabNumber AS NVARCHAR(50)), N'—') AS [Таб_№],
|
|
||||||
CONVERT(VARCHAR(10), @TargetDate, 104) AS [Дата],
|
|
||||||
ISNULL(CAST(CONVERT(VARCHAR(8), pass.FirstIn, 108) AS NVARCHAR(20)), N'Нет входа') AS [Начало_дня],
|
|
||||||
CASE
|
|
||||||
WHEN pass.FirstIn IS NULL AND pass.FirstRawEvent IS NOT NULL
|
|
||||||
THEN CAST(CONVERT(VARCHAR(8), pass.FirstRawEvent, 108) AS NVARCHAR(20))
|
|
||||||
ELSE N'—'
|
|
||||||
END AS [Первая_активность],
|
|
||||||
CASE
|
|
||||||
WHEN pass.FilteredLastOut IS NOT NULL
|
|
||||||
THEN CAST(CONVERT(VARCHAR(8), pass.FilteredLastOut, 108) AS NVARCHAR(20))
|
|
||||||
ELSE N'Нет выхода'
|
|
||||||
END AS [Конец_дня],
|
|
||||||
CASE
|
|
||||||
WHEN pass.EmployeeID IS NOT NULL AND (pass.FirstIn IS NOT NULL OR pass.FirstRawEvent IS NOT NULL) THEN
|
|
||||||
RIGHT('0' + CAST(DATEDIFF(MINUTE,
|
|
||||||
ISNULL(pass.FirstIn, pass.FirstRawEvent),
|
|
||||||
CASE
|
|
||||||
WHEN pass.FilteredLastOut IS NOT NULL THEN pass.FilteredLastOut
|
|
||||||
ELSE @EndDate
|
|
||||||
END) / 60 AS VARCHAR), 2) + ':' +
|
|
||||||
RIGHT('0' + CAST(DATEDIFF(MINUTE,
|
|
||||||
ISNULL(pass.FirstIn, pass.FirstRawEvent),
|
|
||||||
CASE
|
|
||||||
WHEN pass.FilteredLastOut IS NOT NULL THEN pass.FilteredLastOut
|
|
||||||
ELSE @EndDate
|
|
||||||
END) % 60 AS VARCHAR), 2)
|
|
||||||
ELSE N'00:00'
|
|
||||||
END AS [Находился_в_здании],
|
|
||||||
CASE
|
|
||||||
WHEN pass.EmployeeID IS NOT NULL THEN N'Присутствовал'
|
|
||||||
ELSE N'Отсутствовал (Нет событий)'
|
|
||||||
END AS [Статус]
|
|
||||||
FROM pList p WITH (NOLOCK)
|
|
||||||
LEFT JOIN PDivision div WITH (NOLOCK) ON p.Section = div.ID
|
|
||||||
LEFT JOIN PPost post WITH (NOLOCK) ON p.Post = post.ID
|
|
||||||
LEFT JOIN EvaluatedPassages pass ON p.ID = pass.EmployeeID
|
|
||||||
WHERE
|
|
||||||
ISNULL(p.StatusRecord, 0) = 0
|
|
||||||
AND p.DateTimeInArchive IS NULL
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'Аренд%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT IN (N'Без подразделения', N'')
|
|
||||||
AND p.Name NOT LIKE N'бр.%'
|
|
||||||
AND p.Name NOT LIKE N'Гость%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT IN (N'БГИ', N'КНР')
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'Рабоч%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'Врем%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'Практика%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'тест%'
|
|
||||||
AND ISNULL(CAST(post.Name AS NVARCHAR(255)), N'') NOT LIKE N'Практикант%'
|
|
||||||
ORDER BY p.Name ASC;
|
|
||||||
"""
|
|
||||||
|
|
||||||
SQL_RAW_EVENTS_QUERY = r"""
|
|
||||||
DECLARE @InputDate DATE = '{target_date}';
|
|
||||||
DECLARE @StartDate DATETIME = CAST(@InputDate AS DATETIME);
|
|
||||||
DECLARE @EndDate DATETIME = {end_datetime_sql};
|
|
||||||
|
|
||||||
SELECT
|
|
||||||
log.TimeVal,
|
|
||||||
log.HozOrgan,
|
|
||||||
LTRIM(RTRIM(
|
|
||||||
ISNULL(CAST(p.Name AS NVARCHAR(255)), N'') +
|
|
||||||
CASE WHEN p.FirstName IS NOT NULL AND CAST(p.FirstName AS NVARCHAR(255)) <> ''
|
|
||||||
THEN N' ' + CAST(p.FirstName AS NVARCHAR(255)) ELSE N'' END +
|
|
||||||
CASE WHEN p.MidName IS NOT NULL AND CAST(p.MidName AS NVARCHAR(255)) <> ''
|
|
||||||
THEN N' ' + CAST(p.MidName AS NVARCHAR(255)) ELSE N'' END
|
|
||||||
)) AS [Сотрудник],
|
|
||||||
ISNULL(CAST(div.Name AS NVARCHAR(255)), N'Без подразделения') AS [Подразделение],
|
|
||||||
log.Event,
|
|
||||||
log.Mode,
|
|
||||||
log.DoorIndex,
|
|
||||||
CASE
|
|
||||||
WHEN log.Mode = 2 THEN 'OUT'
|
|
||||||
WHEN log.Mode = 1 THEN 'IN'
|
|
||||||
WHEN log.Event IN (2, 27, 29, 33, 55, 65) THEN 'OUT'
|
|
||||||
WHEN log.Event IN (1, 21, 26, 54, 64) THEN 'IN'
|
|
||||||
ELSE 'OTHER'
|
|
||||||
END AS Direction
|
|
||||||
FROM pLogData log WITH (NOLOCK)
|
|
||||||
INNER JOIN pList p WITH (NOLOCK) ON log.HozOrgan = p.ID
|
|
||||||
LEFT JOIN PDivision div WITH (NOLOCK) ON p.Section = div.ID
|
|
||||||
LEFT JOIN PPost post WITH (NOLOCK) ON p.Post = post.ID
|
|
||||||
WHERE log.TimeVal BETWEEN @StartDate AND @EndDate
|
|
||||||
AND log.HozOrgan IS NOT NULL
|
|
||||||
AND log.HozOrgan > 0
|
|
||||||
AND log.Event IN (28, 32)
|
|
||||||
-- ⭐️ Фильтрация сотрудников Ленморниипроект (исключение арендаторов и гостей)
|
|
||||||
AND ISNULL(p.StatusRecord, 0) = 0
|
|
||||||
AND p.DateTimeInArchive IS NULL
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'Аренд%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT IN (N'Без подразделения', N'')
|
|
||||||
AND p.Name NOT LIKE N'бр.%'
|
|
||||||
AND p.Name NOT LIKE N'Гость%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT IN (N'БГИ', N'КНР')
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'Рабоч%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'Врем%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'Практика%'
|
|
||||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'тест%'
|
|
||||||
AND ISNULL(CAST(post.Name AS NVARCHAR(255)), N'') NOT LIKE N'Практикант%'
|
|
||||||
ORDER BY log.TimeVal ASC;
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def save_df_to_clean_excel(df: pd.DataFrame, file_path: str, sheet_name: str = "Отчет"):
|
def save_df_to_clean_excel(df: pd.DataFrame, file_path: str, sheet_name: str = "Отчет"):
|
||||||
workbook = xlsxwriter.Workbook(file_path, {'constant_memory': False})
|
workbook = xlsxwriter.Workbook(file_path, {'constant_memory': False})
|
||||||
@@ -333,19 +159,17 @@ def run_export(input_date: str | None = None, input_time: str | None = None, sav
|
|||||||
log("=== [ЭТАП 0] Выгрузка свежих данных СКУД напрямую из БД Орион ===")
|
log("=== [ЭТАП 0] Выгрузка свежих данных СКУД напрямую из БД Орион ===")
|
||||||
os.makedirs(SCUD_DIR, exist_ok=True)
|
os.makedirs(SCUD_DIR, exist_ok=True)
|
||||||
|
|
||||||
# ⭐️ 1. ПОЛУЧАСОВАЯ СИНХРОНИЗАЦИЯ 1С:ЗУП (Файлы с шары + База данных)
|
# Получасовая синхронизация файлов 1С:ЗУП
|
||||||
try:
|
try:
|
||||||
log("[1C] Проверка сетевой шары и синхронизация файлов 1С...")
|
log("[1C] Проверка сетевой шары и синхронизация файлов 1С...")
|
||||||
copy_1c_files_from_share()
|
copy_1c_files_from_share()
|
||||||
|
|
||||||
target_sync_date = input_date or datetime.now().strftime("%d.%m.%Y")
|
target_sync_date = input_date or datetime.now().strftime("%d.%m.%Y")
|
||||||
# Прямой опрос свежих отсутствий и сохранение в SQLite
|
|
||||||
df_fresh_abs = load_absent_data(target_sync_date)
|
df_fresh_abs = load_absent_data(target_sync_date)
|
||||||
if df_fresh_abs is not None and not df_fresh_abs.empty:
|
if df_fresh_abs is not None and not df_fresh_abs.empty:
|
||||||
save_absences_to_db(df_fresh_abs, target_sync_date)
|
save_absences_to_db(df_fresh_abs, target_sync_date)
|
||||||
log(f"[1C] [✓] Актуализировано {len(df_fresh_abs)} отсутствий в SQLite за {target_sync_date}", "SUCCESS")
|
log(f"[1C] [✓] Актуализировано {len(df_fresh_abs)} отсутствий в SQLite за {target_sync_date}", "SUCCESS")
|
||||||
|
|
||||||
# Если на шаре появился свежий штат — также обновляем его в базе
|
|
||||||
df_fresh_staff = load_staff_data(target_sync_date)
|
df_fresh_staff = load_staff_data(target_sync_date)
|
||||||
if df_fresh_staff is not None and not df_fresh_staff.empty:
|
if df_fresh_staff is not None and not df_fresh_staff.empty:
|
||||||
save_staff_to_db(df_fresh_staff, target_sync_date)
|
save_staff_to_db(df_fresh_staff, target_sync_date)
|
||||||
@@ -380,7 +204,7 @@ def run_export(input_date: str | None = None, input_time: str | None = None, sav
|
|||||||
|
|
||||||
exc_data = load_exceptions()
|
exc_data = load_exceptions()
|
||||||
|
|
||||||
# 1. Формируем фильтр правого турникета (DoorIndex = 2)
|
# Фильтр правого турникета (DoorIndex = 2)
|
||||||
t_fios = [f.replace("'", "''") for f in exc_data.get('turnstile_fio', []) if f]
|
t_fios = [f.replace("'", "''") for f in exc_data.get('turnstile_fio', []) if f]
|
||||||
t_depts = [d.replace("'", "''") for d in exc_data.get('turnstile_departments', []) if d]
|
t_depts = [d.replace("'", "''") for d in exc_data.get('turnstile_departments', []) if d]
|
||||||
|
|
||||||
@@ -403,7 +227,7 @@ def run_export(input_date: str | None = None, input_time: str | None = None, sav
|
|||||||
|
|
||||||
turnstile_filter_sql = " OR ".join(conditions) if conditions else "1 = 0"
|
turnstile_filter_sql = " OR ".join(conditions) if conditions else "1 = 0"
|
||||||
|
|
||||||
# 1.1 Формируем фильтр Флигеля (DoorIndex = 23)
|
# Фильтр Флигеля (DoorIndex = 23)
|
||||||
fl_fios = [f.replace("'", "''") for f in exc_data.get('fligel_fio', []) if f]
|
fl_fios = [f.replace("'", "''") for f in exc_data.get('fligel_fio', []) if f]
|
||||||
fl_depts = [d.replace("'", "''") for d in exc_data.get('fligel_departments', []) if d]
|
fl_depts = [d.replace("'", "''") for d in exc_data.get('fligel_departments', []) if d]
|
||||||
|
|
||||||
@@ -418,7 +242,7 @@ def run_export(input_date: str | None = None, input_time: str | None = None, sav
|
|||||||
|
|
||||||
fligel_filter_sql = " OR ".join(fl_conditions) if fl_conditions else "1 = 0"
|
fligel_filter_sql = " OR ".join(fl_conditions) if fl_conditions else "1 = 0"
|
||||||
|
|
||||||
# 2. Безопасное математическое определение @EndDate через DATEADD
|
# Определение временных границ
|
||||||
if target_time:
|
if target_time:
|
||||||
t_clean = target_time.strip()
|
t_clean = target_time.strip()
|
||||||
t_parts = t_clean.split(":")
|
t_parts = t_clean.split(":")
|
||||||
|
|||||||
+412
-210
@@ -12,6 +12,7 @@ ROLE: Нативный оркестратор диалога, диспетчер
|
|||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -150,6 +151,7 @@ def process_chat_message(
|
|||||||
f" - База знаний и регламенты -> db_get_rules\n"
|
f" - База знаний и регламенты -> db_get_rules\n"
|
||||||
f" - Аномалии СКУД/1С -> db_get_anomalies\n"
|
f" - Аномалии СКУД/1С -> db_get_anomalies\n"
|
||||||
f" - Справка -> db_get_reference\n"
|
f" - Справка -> db_get_reference\n"
|
||||||
|
f" - Распознавание PDF/сканов и экспорт в Word -> office_pdf_to_word\n"
|
||||||
f"3. ЗАДАЧИ:\n"
|
f"3. ЗАДАЧИ:\n"
|
||||||
f" - При любых запросах на просмотр задач (включая опечатки вроде 'змдачи', 'таски', 'дела', 'покажи задачи') — "
|
f" - При любых запросах на просмотр задач (включая опечатки вроде 'змдачи', 'таски', 'дела', 'покажи задачи') — "
|
||||||
f"ТЫ ОБЯЗАН СРАЗУ ВЫЗВАТЬ db_get_tasks без лишних вопросов!\n"
|
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. Снапшоты СКУД
|
# 5. Снапшоты СКУД
|
||||||
elif fn_name == "db_get_snapshots":
|
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)
|
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:
|
if not session_state:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -943,6 +1013,23 @@ def inject_tools_if_needed(user_message: str, raw_reply: str, existing_tool_call
|
|||||||
Любые синтетические перехваты текста регулярными выражениями отключены согласно ROADMAP.
|
Любые синтетические перехваты текста регулярными выражениями отключены согласно 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
|
||||||
```
|
```
|
||||||
|
|
||||||
## File: `./modules/web_api/llm/db/connection.py`
|
## 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`
|
## File: `./modules/web_api/llm/file_parser.py`
|
||||||
```py
|
```py
|
||||||
import base64
|
"""
|
||||||
|
===============================================================================
|
||||||
|
FILE: modules/web_api/llm/file_parser.py
|
||||||
|
ROLE: Изолированный сервис извлечения содержимого из PDF, таблиц и сканов.
|
||||||
|
===============================================================================
|
||||||
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import base64
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
from typing import Dict, Any, List
|
||||||
|
|
||||||
logger = logging.getLogger("FILE_PARSER")
|
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:
|
try:
|
||||||
# 1. ИЗОБРАЖЕНИЯ (.png, .jpg, .jpeg, .bmp, .webp) -> Кодируем в Base64 для Vision LLM
|
import pypdf
|
||||||
if ext in ['.png', '.jpg', '.jpeg', '.bmp', '.webp']:
|
reader = pypdf.PdfReader(file_path)
|
||||||
b64_str = base64.b64encode(file_bytes).decode('utf-8')
|
for idx, page in enumerate(reader.pages, start=1):
|
||||||
return {
|
t = page.extract_text() or ""
|
||||||
"text": f"[ПРИКРЕПЛЕНО ИЗОБРАЖЕНИЕ: {filename}]",
|
if t.strip():
|
||||||
"image_b64": b64_str
|
text_pages.append(f"--- Страница {idx} ---\n{t.strip()}")
|
||||||
}
|
|
||||||
|
|
||||||
# 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
|
|
||||||
}
|
|
||||||
|
|
||||||
except Exception as e:
|
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 {
|
return {
|
||||||
"text": f"[ОШИБКА ОБРАБОТКИ ФАЙЛА: {str(e)}]",
|
"has_text": True,
|
||||||
"image_b64": None
|
"text": full_text,
|
||||||
|
"image_b64": None,
|
||||||
|
"pages_count": len(text_pages)
|
||||||
}
|
}
|
||||||
finally:
|
|
||||||
if os.path.exists(temp_filepath):
|
# 3. Если текста мало или это чистый скан — рендерим первую страницу через PyMuPDF для Vision
|
||||||
os.remove(temp_filepath)
|
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`
|
## 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
|
FILE: modules/web_api/routers/chat.py
|
||||||
ROLE: Полнофункциональный роутер чата с извлечением текста из PDF и сканов,
|
ROLE: Роутер чата с чистым разделением:
|
||||||
поддержкой Function Calling, Fast-Path и оптического распознавания OCR.
|
- Диалог и команды СКУД/1С (через agent.py).
|
||||||
|
- Парсинг и извлечение документов без обрезания (через file_parser.py).
|
||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import base64
|
|
||||||
import logging
|
import logging
|
||||||
from typing import Optional, List, Dict, Any
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Header, HTTPException, UploadFile, File, Form
|
from fastapi import APIRouter, Header, HTTPException, UploadFile, File, Form
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from llm.agent import process_chat_message
|
from llm.agent import process_chat_message
|
||||||
|
from llm.file_parser import parse_uploaded_file
|
||||||
from config import BASE_DIR
|
from config import BASE_DIR
|
||||||
|
|
||||||
logger = logging.getLogger("CHAT_API")
|
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()
|
token = authorization.replace("Bearer ", "").strip()
|
||||||
if token.isdigit():
|
if token.isdigit():
|
||||||
return int(token)
|
return int(token)
|
||||||
elif token.startswith("dev_token_"):
|
|
||||||
try:
|
|
||||||
return int(token.replace("dev_token_", ""))
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
|
||||||
@@ -2185,8 +2329,6 @@ async def chat_endpoint(payload: ChatMessageRequest, authorization: Optional[str
|
|||||||
if not user_msg:
|
if not user_msg:
|
||||||
raise HTTPException(status_code=400, detail="Пустое сообщение")
|
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(
|
reply_text, history, action_payload = process_chat_message(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
user_message=user_msg,
|
user_message=user_msg,
|
||||||
@@ -2215,60 +2357,60 @@ async def chat_upload_endpoint(
|
|||||||
with open(file_path, "wb") as buffer:
|
with open(file_path, "wb") as buffer:
|
||||||
shutil.copyfileobj(file.file, buffer)
|
shutil.copyfileobj(file.file, buffer)
|
||||||
|
|
||||||
file_context = ""
|
user_msg = (message or "").strip()
|
||||||
image_b64 = None
|
msg_lower = user_msg.lower()
|
||||||
fn_lower = file.filename.lower()
|
fn_lower = file.filename.lower()
|
||||||
|
|
||||||
# 1. Текстовые форматы
|
# ⭐️ 1. ПРЯМАЯ ИЗОЛИРОВАННАЯ ОБРАБОТКА PDF/СКАНОВ В WORD ЧЕРЕЗ OFFICE МОДУЛЬ
|
||||||
if fn_lower.endswith((".txt", ".csv", ".log", ".md")):
|
ocr_keywords = [
|
||||||
try:
|
"распознай", "распознать", "в word", "в ворд", "для ворда", "для word",
|
||||||
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}")
|
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")):
|
prompt_text = user_msg or f"Распознать документ {file.filename} для MS Word"
|
||||||
try:
|
db_save_chat_message(session_id, "user", prompt_text, is_ephemeral=0)
|
||||||
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}")
|
|
||||||
|
|
||||||
# 3. PDF документы (текстовый слой + рендеринг скана при необходимости)
|
# Вызываем офисный сервис постраничного OCR и сборки DOCX
|
||||||
elif fn_lower.endswith(".pdf"):
|
office_res = convert_pdf_to_word_service(file_path, file.filename)
|
||||||
# Попытка извлечь встроенный текстовый слой
|
|
||||||
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
|
|
||||||
|
|
||||||
# Если текстового слоя мало (скан или фото документа), рендерим страницу в картинку для Vision OCR
|
reply_text = (
|
||||||
if len(file_context) < 40:
|
f"📄 **{office_res['message']}**\n\n"
|
||||||
try:
|
f"**Фрагмент первой страницы документа:**\n"
|
||||||
import fitz # PyMuPDF
|
f"```text\n{office_res['preview_text']}...\n```\n\n"
|
||||||
doc = fitz.open(file_path)
|
f"Файл готов к скачиванию и редактированию в MS Word."
|
||||||
if len(doc) > 0:
|
)
|
||||||
page = doc[0]
|
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=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}")
|
|
||||||
|
|
||||||
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(
|
reply_text, history, action_payload = process_chat_message(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
user_message=user_msg,
|
user_message=prompt_for_agent,
|
||||||
file_context=file_context,
|
file_context=file_context,
|
||||||
image_b64=image_b64,
|
image_b64=image_b64,
|
||||||
session_id=session_id
|
session_id=session_id
|
||||||
@@ -2380,8 +2522,7 @@ def api_delete_exception(category: str, value: str):
|
|||||||
"""
|
"""
|
||||||
===============================================================================
|
===============================================================================
|
||||||
FILE: modules/web_api/routers/files.py
|
FILE: modules/web_api/routers/files.py
|
||||||
ROLE: Раздача сформированных отчетов и выгрузок с сохранением оригинальных имен
|
ROLE: Раздача сформированных отчетов и выгрузок с сохранением оригинальных имен.
|
||||||
через изолированные UUID-директории инструментов.
|
|
||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -2389,6 +2530,7 @@ import os
|
|||||||
import time
|
import time
|
||||||
import shutil
|
import shutil
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
|
from typing import Optional
|
||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, HTTPException
|
||||||
from fastapi.responses import FileResponse
|
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__), "../../../"))
|
BASE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
|
||||||
WEB_OUTPUT_DIR = os.path.join(BASE_ROOT, "output", "web")
|
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):
|
def purge_old_tool_sessions(tool_dir_path: str):
|
||||||
"""Удаляет временные UUID-папки старше SESSION_TTL_HOURS внутри инструмента."""
|
|
||||||
if not os.path.exists(tool_dir_path):
|
if not os.path.exists(tool_dir_path):
|
||||||
return
|
return
|
||||||
now = time.time()
|
now = time.time()
|
||||||
@@ -2419,9 +2565,6 @@ def purge_old_tool_sessions(tool_dir_path: str):
|
|||||||
|
|
||||||
@router.get("/download/{tool_name}/{session_uuid}/{filename}")
|
@router.get("/download/{tool_name}/{session_uuid}/{filename}")
|
||||||
async def download_file(tool_name: str, session_uuid: str, filename: str):
|
async def download_file(tool_name: str, session_uuid: str, filename: str):
|
||||||
"""
|
|
||||||
Безопасная отдача файла с каноническим именем из изолированной директории.
|
|
||||||
"""
|
|
||||||
safe_tool = os.path.basename(tool_name)
|
safe_tool = os.path.basename(tool_name)
|
||||||
safe_uuid = os.path.basename(session_uuid)
|
safe_uuid = os.path.basename(session_uuid)
|
||||||
safe_filename = os.path.basename(filename)
|
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):
|
if not os.path.exists(file_path) or not os.path.isfile(file_path):
|
||||||
raise HTTPException(status_code=404, detail="Файл не найден или срок его действия истек")
|
raise HTTPException(status_code=404, detail="Файл не найден или срок его действия истек")
|
||||||
|
|
||||||
# Определение MIME-типа
|
|
||||||
media_type = "application/octet-stream"
|
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"
|
media_type = "text/markdown; charset=utf-8"
|
||||||
elif safe_filename.endswith(".xlsx"):
|
elif safe_filename.endswith(".xlsx"):
|
||||||
media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
elif safe_filename.endswith(".pdf"):
|
elif safe_filename.endswith(".pdf"):
|
||||||
media_type = "application/pdf"
|
media_type = "application/pdf"
|
||||||
|
|
||||||
# Корректная кодировка для кириллических имен файлов
|
|
||||||
encoded_filename = urllib.parse.quote(safe_filename)
|
encoded_filename = urllib.parse.quote(safe_filename)
|
||||||
|
|
||||||
return FileResponse(
|
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="Отчет не найден")
|
raise HTTPException(status_code=404, detail="Отчет не найден")
|
||||||
|
|
||||||
encoded_filename = urllib.parse.quote(safe_filename)
|
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
|
FILE: modules/web_api/routers/reports.py
|
||||||
ROLE: REST API On-Demand генерации отчетов (Сводка, Детальный, Упрощенный)
|
ROLE: REST API On-Demand генерации отчетов:
|
||||||
с атомарной сборкой в /tmp и безопасной публикацией на сетевую шару.
|
- Сводка: за СЕГОДНЯ (оперативный контроль, текущий срез).
|
||||||
|
- Детальный и Упрощенный отчет: строго за ВЧЕРА по финальному срезу Y.
|
||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from fastapi import APIRouter, HTTPException, Query
|
from fastapi import APIRouter, HTTPException
|
||||||
|
|
||||||
from config import DATE_TODAY, DATE_YESTERDAY
|
from config import DATE_TODAY, DATE_YESTERDAY
|
||||||
from services.scud_etl.svodka_generator import generate_svodka_service
|
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")
|
logger = logging.getLogger("REPORTS_API")
|
||||||
router = APIRouter(prefix="/api/v1/reports", tags=["Reports"])
|
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):
|
class GenerateReportRequest(BaseModel):
|
||||||
date: Optional[str] = None # ДД.ММ.ГГГГ
|
date: Optional[str] = None # ДД.ММ.ГГГГ
|
||||||
time: Optional[str] = None # ЧЧ:ММ (для сводки)
|
time: Optional[str] = None # ЧЧ:ММ
|
||||||
report_type: str # 'SVODKA', 'DETAILED', 'SIMPLIFIED', 'ALL'
|
report_type: str # 'SVODKA', 'DETAILED', 'SIMPLIFIED', 'ALL'
|
||||||
|
|
||||||
|
|
||||||
@router.post("/generate")
|
@router.post("/generate")
|
||||||
def api_generate_report(req: GenerateReportRequest):
|
def api_generate_report(req: GenerateReportRequest):
|
||||||
"""
|
"""
|
||||||
Генерирует выбранный отчет на указанную дату/время и возвращает ссылки на скачивание.
|
Генерирует выбранный отчет:
|
||||||
|
- SVODKA: на текущую дату (date).
|
||||||
|
- DETAILED / SIMPLIFIED: строго за вчерашний рабочий день по финальному срезу Y.
|
||||||
"""
|
"""
|
||||||
target_date = (req.date or DATE_TODAY).replace('_', '.')
|
target_date = (req.date or DATE_TODAY).replace('_', '.')
|
||||||
|
yesterday_date = get_previous_workday(target_date)
|
||||||
r_type = req.report_type.upper()
|
r_type = req.report_type.upper()
|
||||||
results = []
|
results = []
|
||||||
|
|
||||||
# 1. Ежедневная сводка
|
# 1. Ежедневная сводка (за СЕГОДНЯ)
|
||||||
if r_type in ["SVODKA", "ALL"]:
|
if r_type in ["SVODKA", "ALL"]:
|
||||||
res_svodka = generate_svodka_service(
|
res_svodka = generate_svodka_service(
|
||||||
target_date=target_date,
|
target_date=target_date,
|
||||||
@@ -2824,9 +2997,9 @@ def api_generate_report(req: GenerateReportRequest):
|
|||||||
"status": "error"
|
"status": "error"
|
||||||
})
|
})
|
||||||
|
|
||||||
# 2. Детальный отчет
|
# 2. Детальный отчет (строго за ВЧЕРА по финальному срезу Y)
|
||||||
if r_type in ["DETAILED", "ALL"]:
|
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":
|
if res_det.get("status") == "success":
|
||||||
results.append({
|
results.append({
|
||||||
"type": "Детальный отчет",
|
"type": "Детальный отчет",
|
||||||
@@ -2841,14 +3014,14 @@ def api_generate_report(req: GenerateReportRequest):
|
|||||||
"status": "error"
|
"status": "error"
|
||||||
})
|
})
|
||||||
|
|
||||||
# 3. Упрощенный отчет
|
# 3. Упрощенный отчет (строго за ВЧЕРА по финальному срезу Y)
|
||||||
if r_type in ["SIMPLIFIED", "ALL"]:
|
if r_type in ["SIMPLIFIED", "ALL"]:
|
||||||
try:
|
try:
|
||||||
df_scud = load_best_snapshot_for_date(target_date, prefer_final_y=True)
|
df_scud_y = load_best_snapshot_for_date(yesterday_date, prefer_final_y=True)
|
||||||
if df_scud is not None and not df_scud.empty:
|
if df_scud_y is not None and not df_scud_y.empty:
|
||||||
df_staff, df_abs = load_1c_files_for_date(target_date)
|
df_staff_y, df_abs_y = load_1c_files_for_date(yesterday_date)
|
||||||
df_merged = merge_scud_and_1c(df_scud, df_staff, df_abs)
|
df_merged_y = merge_scud_and_1c(df_scud_y, df_staff_y, df_abs_y)
|
||||||
out_path = generate_simplified_excel(df_merged, date_str=target_date)
|
out_path = generate_simplified_excel(df_merged_y, date_str=yesterday_date)
|
||||||
filename = os.path.basename(out_path)
|
filename = os.path.basename(out_path)
|
||||||
results.append({
|
results.append({
|
||||||
"type": "Упрощенный отчет",
|
"type": "Упрощенный отчет",
|
||||||
@@ -2859,10 +3032,11 @@ def api_generate_report(req: GenerateReportRequest):
|
|||||||
else:
|
else:
|
||||||
results.append({
|
results.append({
|
||||||
"type": "Упрощенный отчет",
|
"type": "Упрощенный отчет",
|
||||||
"error": f"Срез СКУД за {target_date} не найден.",
|
"error": f"Финальный срез СКУД (Y) за {yesterday_date} не найден.",
|
||||||
"status": "error"
|
"status": "error"
|
||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
logger.exception(f"Ошибка формирования упрощенного отчета: {e}")
|
||||||
results.append({
|
results.append({
|
||||||
"type": "Упрощенный отчет",
|
"type": "Упрощенный отчет",
|
||||||
"error": str(e),
|
"error": str(e),
|
||||||
@@ -2871,6 +3045,7 @@ def api_generate_report(req: GenerateReportRequest):
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"date": target_date,
|
"date": target_date,
|
||||||
|
"yesterday_date": yesterday_date,
|
||||||
"requested_type": r_type,
|
"requested_type": r_type,
|
||||||
"reports": results
|
"reports": results
|
||||||
}
|
}
|
||||||
@@ -3469,16 +3644,32 @@ body {
|
|||||||
* { overflow-anchor: none !important; }
|
* { overflow-anchor: none !important; }
|
||||||
#chat-messages-container, main { overflow-anchor: none !important; }
|
#chat-messages-container, main { overflow-anchor: none !important; }
|
||||||
#chat-messages-container { padding-bottom: clamp(400px, 85vh, 900px) !important; }
|
#chat-messages-container { padding-bottom: clamp(400px, 85vh, 900px) !important; }
|
||||||
|
|
||||||
|
/* ⭐️ Комфортный размер шрифта в стиле Gemini */
|
||||||
#chat-messages-container .message-content,
|
#chat-messages-container .message-content,
|
||||||
|
#chat-messages-container .text-sm,
|
||||||
#chat-messages-container .text-xs,
|
#chat-messages-container .text-xs,
|
||||||
#chat-messages-container .text-sm {
|
#chat-messages-container p,
|
||||||
font-size: 14.5px !important;
|
#chat-messages-container li {
|
||||||
line-height: 1.6 !important;
|
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 pre,
|
||||||
#chat-messages-container code {
|
#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; }
|
.user-chat-bubble { scroll-margin-top: 24px !important; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</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 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="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">
|
<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-xs"></i>
|
<i class="fa-solid fa-robot text-sm"></i>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
|
<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-[11px] 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-sm text-slate-700 leading-relaxed">
|
||||||
Привет! Вы можете задавать вопросы ассистенту, управлять системным промптом, сверять кадровые нестыковки СКУД и 1С или формировать срезы и отчеты.
|
Привет! Вы можете задавать вопросы ассистенту, управлять системным промптом, сверять кадровые нестыковки СКУД и 1С или формировать срезы и отчеты.
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -3716,24 +3907,35 @@ body {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- СТРОКА ВВОДА -->
|
<!-- СТРОКА ВВОДА -->
|
||||||
<div class="px-4 py-2 bg-white border-t border-slate-200">
|
<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-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">
|
<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 transition shrink-0" title="Прикрепить файл">
|
<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-xs"></i>
|
<i class="fa-solid fa-paperclip text-base"></i>
|
||||||
</button>
|
</button>
|
||||||
<input type="file" id="file-upload-input" class="hidden" />
|
<input type="file" id="file-upload-input" class="hidden" />
|
||||||
|
|
||||||
<textarea id="user-input" rows="1" placeholder="Команда, вопрос (Enter - отправить, Shift+Enter - перенос строки)..."
|
<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>
|
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">
|
<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-[10px]"></i>
|
<i class="fa-solid fa-paper-plane text-xs"></i>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</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>
|
<div id="modals-container"></div>
|
||||||
|
|
||||||
@@ -4153,8 +4355,8 @@ document.addEventListener("DOMContentLoaded", async () => {
|
|||||||
const userInputEl = document.getElementById("user-input");
|
const userInputEl = document.getElementById("user-input");
|
||||||
if (userInputEl) {
|
if (userInputEl) {
|
||||||
userInputEl.addEventListener("input", function() {
|
userInputEl.addEventListener("input", function() {
|
||||||
this.style.height = "24px";
|
this.style.height = "32px";
|
||||||
const newHeight = Math.min(this.scrollHeight, 120);
|
const newHeight = Math.min(this.scrollHeight, 140);
|
||||||
this.style.height = newHeight + "px";
|
this.style.height = newHeight + "px";
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -4309,7 +4511,7 @@ function updateInputHeightAndFade(textarea) {
|
|||||||
if (!textarea) return;
|
if (!textarea) return;
|
||||||
|
|
||||||
if (!textarea.value || textarea.value.trim() === '') {
|
if (!textarea.value || textarea.value.trim() === '') {
|
||||||
textarea.style.height = '24px';
|
textarea.style.height = '32px';
|
||||||
textarea.style.overflowY = 'hidden';
|
textarea.style.overflowY = 'hidden';
|
||||||
textarea.style.maskImage = 'none';
|
textarea.style.maskImage = 'none';
|
||||||
textarea.style.webkitMaskImage = 'none';
|
textarea.style.webkitMaskImage = 'none';
|
||||||
@@ -4317,8 +4519,8 @@ function updateInputHeightAndFade(textarea) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
textarea.style.height = 'auto';
|
textarea.style.height = 'auto';
|
||||||
const minHeight = 24;
|
const minHeight = 32;
|
||||||
const maxHeight = 120;
|
const maxHeight = 140;
|
||||||
const currentScrollHeight = textarea.scrollHeight;
|
const currentScrollHeight = textarea.scrollHeight;
|
||||||
|
|
||||||
if (currentScrollHeight <= minHeight + 2) {
|
if (currentScrollHeight <= minHeight + 2) {
|
||||||
@@ -4404,23 +4606,23 @@ function appendAssistantMessage(text, buttons = [], actionPayload = null) {
|
|||||||
payloadHtml = renderInteractiveTaskCard(actionPayload.tasks);
|
payloadHtml = renderInteractiveTaskCard(actionPayload.tasks);
|
||||||
} else if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
|
} else if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
|
||||||
const dlUrl = actionPayload.download_url || '#';
|
const dlUrl = actionPayload.download_url || '#';
|
||||||
const fName = actionPayload.filename || 'ROADMAP.md';
|
const fName = actionPayload.filename || 'document.docx';
|
||||||
const count = actionPayload.tasks_count || '';
|
const count = actionPayload.tasks_count || '';
|
||||||
payloadHtml = `
|
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="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">
|
<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-lines text-base"></i>
|
<i class="fa-solid fa-file-word text-lg"></i>
|
||||||
</div>
|
</div>
|
||||||
<div class="min-w-0">
|
<div class="min-w-0">
|
||||||
<div class="text-sm font-bold text-slate-800 truncate">${escapeHtml(fName)}</div>
|
<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>
|
||||||
</div>
|
</div>
|
||||||
<a href="${dlUrl}" download="${escapeHtml(fName)}" target="_blank"
|
<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">
|
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-download text-xs"></i>
|
<i class="fa-solid fa-arrow-down-to-line text-sm text-white"></i>
|
||||||
<span>Скачать файл</span>
|
<span class="text-white tracking-wide">Скачать файл</span>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
@@ -4624,7 +4826,7 @@ window.sendMessage = async function() {
|
|||||||
saveCommandToHistory(messageText);
|
saveCommandToHistory(messageText);
|
||||||
|
|
||||||
input.value = "";
|
input.value = "";
|
||||||
input.style.height = '24px';
|
input.style.height = '32px';
|
||||||
input.style.overflowY = 'hidden';
|
input.style.overflowY = 'hidden';
|
||||||
input.style.maskImage = 'none';
|
input.style.maskImage = 'none';
|
||||||
input.style.webkitMaskImage = 'none';
|
input.style.webkitMaskImage = 'none';
|
||||||
@@ -4739,7 +4941,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
|||||||
|
|
||||||
if (input) {
|
if (input) {
|
||||||
input.style.lineHeight = '24px';
|
input.style.lineHeight = '24px';
|
||||||
input.style.height = '24px';
|
input.style.height = '32px';
|
||||||
|
|
||||||
input.addEventListener("keydown", (e) => {
|
input.addEventListener("keydown", (e) => {
|
||||||
if (e.key === "Enter") {
|
if (e.key === "Enter") {
|
||||||
@@ -6546,8 +6748,8 @@ async function deleteSnapshotItem(snapshotId) {
|
|||||||
|
|
||||||
// 7. Генерация отчетов On-Demand
|
// 7. Генерация отчетов On-Demand
|
||||||
window.generateReportDirect = async function(reportType) {
|
window.generateReportDirect = async function(reportType) {
|
||||||
const dateInput = document.getElementById('manual-snapshot-date')?.value || '';
|
const fromInput = document.getElementById('snapshots-date-from');
|
||||||
const timeInput = document.getElementById('manual-snapshot-time')?.value || '';
|
const dateInput = fromInput ? isoToBackendFormat(fromInput.value) : '';
|
||||||
|
|
||||||
const labelMap = {
|
const labelMap = {
|
||||||
'SVODKA': 'Сводки',
|
'SVODKA': 'Сводки',
|
||||||
@@ -6564,7 +6766,7 @@ window.generateReportDirect = async function(reportType) {
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
report_type: reportType,
|
report_type: reportType,
|
||||||
date: dateInput || null,
|
date: dateInput || null,
|
||||||
time: timeInput || null
|
time: null // ⭐️ Всегда берем последний готовый срез
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user