Add parse_pol177.py - PDF parser with Unstructured API + pypdf
This commit is contained in:
@@ -0,0 +1,82 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Комбинированный парсинг ПОЛ-177:
|
||||||
|
- Текст: Unstructured API (192.168.1.103:8005)
|
||||||
|
- Таблицы: pypdf (локально)
|
||||||
|
|
||||||
|
Сохраняет результат в /opt/okf-regulations/concepts/pol177_parsed.json
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# === НАСТРОЙКИ ===
|
||||||
|
UNSTRUCTURED_API = "http://192.168.1.103:8005/general/v0/general"
|
||||||
|
PDF_PATH = "/opt/documents_xk/АОХКСибцем/07 Служба Вице-президента по экономике и финансам/ДИТ/02 Регламенты деятельности/10 Положение Хранение электронных документов от 03.04.2024 № ПОЛ-177.pdf"
|
||||||
|
OUTPUT_PATH = "/opt/okf-regulations/concepts/pol177_parsed.json"
|
||||||
|
|
||||||
|
def fetch_unstructured(pdf_path: str) -> list[dict]:
|
||||||
|
"""Получаем элементы текста из Unstructured API (103)."""
|
||||||
|
cmd = [
|
||||||
|
"curl", "-X", "POST", UNSTRUCTURED_API,
|
||||||
|
"-F", f"files=@{pdf_path}",
|
||||||
|
"-F", "strategy=fast",
|
||||||
|
"-F", "output_format=json",
|
||||||
|
]
|
||||||
|
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||||
|
if result.returncode != 0:
|
||||||
|
print(f"❌ Unstructured API error: {result.stderr}")
|
||||||
|
return []
|
||||||
|
return json.loads(result.stdout)
|
||||||
|
|
||||||
|
def extract_tables_pypdf(pdf_path: str) -> list[dict]:
|
||||||
|
"""Извлекаем таблицы через pypdf (локально на 106)."""
|
||||||
|
try:
|
||||||
|
from pypdf import PdfReader
|
||||||
|
except ImportError:
|
||||||
|
import subprocess
|
||||||
|
subprocess.run(["pip3", "install", "pypdf", "--user"], check=True)
|
||||||
|
from pypdf import PdfReader
|
||||||
|
|
||||||
|
reader = PdfReader(pdf_path)
|
||||||
|
tables = []
|
||||||
|
for i, page in enumerate(reader.pages):
|
||||||
|
text = page.extract_text()
|
||||||
|
if text and ("таблица" in text.lower() or "стр" in text.lower()):
|
||||||
|
tables.append({"page": i + 1, "text": text})
|
||||||
|
return tables
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("=" * 60)
|
||||||
|
print("📄 Парсинг ПОЛ-177")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# 1. Текст через Unstructured API
|
||||||
|
print("\n[1/2] Запрос текста через Unstructured API (103)...")
|
||||||
|
elements = fetch_unstructured(PDF_PATH)
|
||||||
|
print(f" ✅ Получено {len(elements)} элементов")
|
||||||
|
|
||||||
|
# 2. Таблицы через pypdf
|
||||||
|
print("\n[2/2] Извлечение таблиц через pypdf (106)...")
|
||||||
|
tables = extract_tables_pypdf(PDF_PATH)
|
||||||
|
print(f" ✅ Найдено {len(tables)} страниц с текстом")
|
||||||
|
|
||||||
|
# 3. Сохраняем комбинированный результат
|
||||||
|
result = {
|
||||||
|
"document": "ПОЛ-177",
|
||||||
|
"title": "Положение Хранение электронных документов от 03.04.2024 № ПОЛ-177",
|
||||||
|
"unstructured": elements,
|
||||||
|
"tables": tables,
|
||||||
|
"metadata": {
|
||||||
|
"unstructured_api": UNSTRUCTURED_API,
|
||||||
|
"strategy": "fast",
|
||||||
|
"timestamp": "2026-07-06",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
Path(OUTPUT_PATH).write_text(json.dumps(result, ensure_ascii=False, indent=2))
|
||||||
|
print(f"\n✅ Сохранено в {OUTPUT_PATH}")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user