Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,63 +11,101 @@ from reportlab.pdfbase import pdfmetrics
|
|
| 11 |
from reportlab.pdfbase.ttfonts import TTFont
|
| 12 |
from reportlab.lib import colors
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
class KDChecker:
|
| 15 |
def __init__(self):
|
| 16 |
self.excel_db = pd.DataFrame()
|
| 17 |
self.cabinet_list = []
|
| 18 |
self.known_docs = ["Э3", "В4", "ПЭ3", "ВО", "ТЭ5", "СБ", "С5", "ОЛ", "Э1", "Э4", "Э7", "Д3", "Э6"]
|
|
|
|
| 19 |
|
| 20 |
-
def load_excel_db(self,
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
log.append(f"Путь к файлу: {excel_path}")
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
try:
|
| 29 |
size = os.path.getsize(excel_path)
|
| 30 |
log.append(f"Размер файла: {size} байт")
|
| 31 |
except Exception as e:
|
| 32 |
-
log.append(f"
|
| 33 |
return "\n".join(log), gr.update(choices=[], value=None)
|
| 34 |
|
|
|
|
| 35 |
try:
|
| 36 |
import openpyxl
|
| 37 |
-
log.append("
|
| 38 |
-
except ImportError:
|
| 39 |
-
|
|
|
|
| 40 |
|
| 41 |
all_data = []
|
| 42 |
sheets_log = []
|
| 43 |
|
| 44 |
try:
|
| 45 |
-
log.append("
|
| 46 |
xls = pd.read_excel(excel_path, sheet_name=None, header=None, engine='openpyxl')
|
| 47 |
-
log.append(f"
|
|
|
|
| 48 |
|
| 49 |
for sheet_name, df_raw in xls.items():
|
|
|
|
|
|
|
| 50 |
header_row_index = -1
|
| 51 |
cab_col_idx = -1
|
| 52 |
rem_col_idx = -1
|
| 53 |
|
|
|
|
| 54 |
for i in range(min(20, len(df_raw))):
|
| 55 |
row_values = [str(x).lower().strip() for x in df_raw.iloc[i].values]
|
| 56 |
c_idx = -1
|
| 57 |
r_idx = -1
|
| 58 |
for idx, val in enumerate(row_values):
|
| 59 |
-
if "шкаф" in val or "cabinet" in val:
|
| 60 |
c_idx = idx
|
| 61 |
-
if "примечание" in val or "remark" in val:
|
| 62 |
r_idx = idx
|
| 63 |
if c_idx != -1 and r_idx != -1:
|
| 64 |
header_row_index = i
|
| 65 |
cab_col_idx = c_idx
|
| 66 |
rem_col_idx = r_idx
|
|
|
|
| 67 |
break
|
| 68 |
|
| 69 |
if header_row_index != -1:
|
| 70 |
df = pd.read_excel(excel_path, sheet_name=sheet_name, header=header_row_index, engine='openpyxl')
|
|
|
|
|
|
|
| 71 |
if cab_col_idx < len(df.columns) and rem_col_idx < len(df.columns):
|
| 72 |
df_subset = df.iloc[:, [cab_col_idx, rem_col_idx]]
|
| 73 |
df_subset.columns = ["Cabinet", "Remark"]
|
|
@@ -77,23 +115,31 @@ class KDChecker:
|
|
| 77 |
lambda x: x.strip().replace(" ", "").replace("\n", "").replace("\r", "")
|
| 78 |
)
|
| 79 |
all_data.append(df_subset)
|
| 80 |
-
sheets_log.append(f"
|
|
|
|
| 81 |
else:
|
| 82 |
-
sheets_log.append(f"
|
|
|
|
| 83 |
else:
|
| 84 |
-
sheets_log.append(f"
|
|
|
|
| 85 |
|
| 86 |
if not all_data:
|
| 87 |
-
log.append("Не найдены данные ни на одном
|
| 88 |
return "\n".join(log), gr.update(choices=[], value=None)
|
| 89 |
|
| 90 |
self.excel_db = pd.concat(all_data, ignore_index=True)
|
| 91 |
self.cabinet_list = sorted(self.excel_db["Cabinet"].unique().tolist())
|
| 92 |
|
| 93 |
-
log.append("
|
| 94 |
-
|
| 95 |
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
except Exception as e:
|
| 99 |
log.append(f"КРИТИЧЕСКАЯ ОШИБКА: {str(e)}")
|
|
@@ -102,16 +148,19 @@ class KDChecker:
|
|
| 102 |
return "\n".join(log), gr.update(choices=[], value=None)
|
| 103 |
|
| 104 |
def extract_text(self, pdf_path):
|
|
|
|
| 105 |
try:
|
| 106 |
full_text = ""
|
| 107 |
with pdfplumber.open(pdf_path) as pdf:
|
| 108 |
for page in pdf.pages:
|
| 109 |
full_text += (page.extract_text() or "") + "\n"
|
| 110 |
return full_text
|
| 111 |
-
except:
|
|
|
|
| 112 |
return ""
|
| 113 |
|
| 114 |
def find_all_decimal_numbers(self, text):
|
|
|
|
| 115 |
pattern = r"(РЛТ|ЛДАР|ВНАР|ШТМ)[\s\.]*\d{1}[\s\.]*\d{3}[\s\.]*[А-ЯA-Z]{1,4}[\s\.]*\d{3}(-[\d]+)?"
|
| 116 |
matches = []
|
| 117 |
for match in re.finditer(pattern, text):
|
|
@@ -121,6 +170,7 @@ class KDChecker:
|
|
| 121 |
return matches
|
| 122 |
|
| 123 |
def determine_doc_type(self, filename):
|
|
|
|
| 124 |
fname = filename.upper()
|
| 125 |
if "С2" in fname: return "С2"
|
| 126 |
if "ПЭ3" in fname or "ПЕРЕЧЕНЬ" in fname: return "ПЭ3"
|
|
@@ -138,8 +188,10 @@ class KDChecker:
|
|
| 138 |
return "UNKNOWN"
|
| 139 |
|
| 140 |
def get_remarks(self, cabinet_key, is_clean_key=True):
|
|
|
|
| 141 |
if self.excel_db.empty:
|
| 142 |
return {}
|
|
|
|
| 143 |
if is_clean_key:
|
| 144 |
target = cabinet_key.replace(" ", "")
|
| 145 |
mask = self.excel_db['Cabinet_Clean'].str.contains(re.escape(target), case=False, na=False)
|
|
@@ -155,6 +207,7 @@ class KDChecker:
|
|
| 155 |
cell_text = str(remark_cell)
|
| 156 |
cell_text = re.sub(r'(\d+)\.([А-ЯA-Z])', r'\1. \2', cell_text)
|
| 157 |
items = re.split(r'(?:^|\n)\s*(?=\d+[\.\)])', cell_text)
|
|
|
|
| 158 |
for item in items:
|
| 159 |
if len(item) < 3:
|
| 160 |
continue
|
|
@@ -162,8 +215,10 @@ class KDChecker:
|
|
| 162 |
clean_item_no_num = re.sub(r'^\d+[\.\)]\s*', '', clean_item)
|
| 163 |
doc_pattern = r'^(?:Документ\s+|В\s+)?([А-ЯA-Z0-9\s,\(\)\-]+?)(?:[\.\:\-]|\s+)(.*)'
|
| 164 |
match = re.match(doc_pattern, clean_item_no_num, re.IGNORECASE | re.DOTALL)
|
|
|
|
| 165 |
detected_docs = []
|
| 166 |
final_text = clean_item
|
|
|
|
| 167 |
if match:
|
| 168 |
potential_docs_str = match.group(1).upper()
|
| 169 |
cleaned_codes = potential_docs_str.replace("(", " ").replace(")", " ").replace(",", " ")
|
|
@@ -172,32 +227,46 @@ class KDChecker:
|
|
| 172 |
if valid_parts:
|
| 173 |
detected_docs = valid_parts
|
| 174 |
final_text = match.group(2).strip()
|
|
|
|
| 175 |
if not detected_docs:
|
| 176 |
detected_docs = ["ALL"]
|
|
|
|
| 177 |
for doc in detected_docs:
|
| 178 |
if doc not in parsed:
|
| 179 |
parsed[doc] = []
|
| 180 |
parsed[doc].append(final_text)
|
|
|
|
| 181 |
return parsed
|
| 182 |
|
| 183 |
def check_files(self, files, manual_cabinet):
|
|
|
|
| 184 |
if not files:
|
| 185 |
-
return "Файлы не загружены", None
|
| 186 |
if self.excel_db.empty:
|
| 187 |
-
return "Сначала загрузите Excel базу!", None
|
| 188 |
|
| 189 |
checklist = {}
|
| 190 |
detected_cabinet = "Не определен"
|
| 191 |
found_by_method = ""
|
| 192 |
is_manual = False
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
if manual_cabinet and manual_cabinet.strip():
|
| 195 |
detected_cabinet = manual_cabinet
|
| 196 |
found_by_method = "manual"
|
| 197 |
is_manual = True
|
| 198 |
else:
|
| 199 |
all_pdf_text = ""
|
| 200 |
-
for file_path in
|
| 201 |
all_pdf_text += self.extract_text(file_path) + "\n"
|
| 202 |
|
| 203 |
pdf_numbers = self.find_all_decimal_numbers(all_pdf_text)
|
|
@@ -224,16 +293,16 @@ class KDChecker:
|
|
| 224 |
break
|
| 225 |
|
| 226 |
if detected_cabinet == "Не определен":
|
| 227 |
-
return "⚠️ Шкаф не опознан автоматически.\n
|
| 228 |
|
| 229 |
is_clean_search = (found_by_method == "number")
|
| 230 |
remarks = self.get_remarks(detected_cabinet, is_clean_key=is_clean_search)
|
| 231 |
|
| 232 |
if not remarks:
|
| 233 |
-
return f"⚠️ Шкаф '{detected_cabinet}'
|
| 234 |
|
| 235 |
processed_count = 0
|
| 236 |
-
for file_path in
|
| 237 |
fname = os.path.basename(file_path)
|
| 238 |
dtype = self.determine_doc_type(fname)
|
| 239 |
|
|
@@ -249,10 +318,10 @@ class KDChecker:
|
|
| 249 |
|
| 250 |
pdf_title = detected_cabinet
|
| 251 |
if is_manual:
|
| 252 |
-
pdf_title += " (
|
| 253 |
|
| 254 |
try:
|
| 255 |
-
|
| 256 |
except Exception as e:
|
| 257 |
return f"❌ Ошибка создания PDF: {e}", None
|
| 258 |
|
|
@@ -260,18 +329,24 @@ class KDChecker:
|
|
| 260 |
method_str = "Ручной выбор" if is_manual else (
|
| 261 |
"По децимальному номеру" if is_clean_search else "По наименованию")
|
| 262 |
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
def create_pdf(self, cabinet, data):
|
|
|
|
| 266 |
fname = "CheckList_Result.pdf"
|
| 267 |
path = os.path.join(tempfile.gettempdir(), fname)
|
| 268 |
c = canvas.Canvas(path, pagesize=A4)
|
| 269 |
-
form = c.acroForm
|
| 270 |
width, height = A4
|
| 271 |
|
|
|
|
| 272 |
font_name = 'Helvetica'
|
| 273 |
font_path = "arial.ttf"
|
| 274 |
-
|
| 275 |
if os.path.exists(font_path):
|
| 276 |
try:
|
| 277 |
pdfmetrics.registerFont(TTFont('Arial', font_path))
|
|
@@ -286,8 +361,7 @@ class KDChecker:
|
|
| 286 |
c.drawString(50, y, "ЧЕК-ЛИСТ ПРОВЕРКИ КД")
|
| 287 |
except:
|
| 288 |
c.setFont("Helvetica", 16)
|
| 289 |
-
c.drawString(50, y, "CHECK-LIST")
|
| 290 |
-
c.setFont(font_name, 16)
|
| 291 |
|
| 292 |
y -= 25
|
| 293 |
c.setFont(font_name, 12)
|
|
@@ -297,8 +371,7 @@ class KDChecker:
|
|
| 297 |
c.drawString(50, y, f"Шкаф: {disp_cab}")
|
| 298 |
except:
|
| 299 |
c.setFont("Helvetica", 12)
|
| 300 |
-
c.drawString(50, y, "Cabinet
|
| 301 |
-
c.setFont(font_name, 12)
|
| 302 |
|
| 303 |
c.drawString(400, y, f"Дата: {datetime.now().strftime('%d.%m.%Y')}")
|
| 304 |
y -= 20
|
|
@@ -310,7 +383,6 @@ class KDChecker:
|
|
| 310 |
c.save()
|
| 311 |
return path
|
| 312 |
|
| 313 |
-
cb_id = 0
|
| 314 |
for filename, tasks in data.items():
|
| 315 |
if y < 100:
|
| 316 |
c.showPage()
|
|
@@ -324,57 +396,52 @@ class KDChecker:
|
|
| 324 |
except:
|
| 325 |
c.setFont("Helvetica", 11)
|
| 326 |
c.drawString(50, y, f"File: {filename}")
|
| 327 |
-
c.setFont(font_name, 11)
|
| 328 |
|
| 329 |
c.setFillColor(colors.black)
|
| 330 |
y -= 15
|
| 331 |
c.setFont(font_name, 10)
|
| 332 |
|
| 333 |
for task in tasks:
|
| 334 |
-
paragraphs = task.split('\n')
|
| 335 |
-
|
| 336 |
if y < 80:
|
| 337 |
c.showPage()
|
| 338 |
y = height - 50
|
| 339 |
c.setFont(font_name, 10)
|
| 340 |
|
| 341 |
-
c.rect(50, y -
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
y = text_start_y - 8
|
| 372 |
|
| 373 |
y -= 10
|
| 374 |
c.setStrokeColor(colors.lightgrey)
|
| 375 |
c.line(50, y, width - 50, y)
|
| 376 |
c.setStrokeColor(colors.black)
|
| 377 |
-
y -=
|
| 378 |
|
| 379 |
c.save()
|
| 380 |
return path
|
|
@@ -383,49 +450,71 @@ class KDChecker:
|
|
| 383 |
def create_app():
|
| 384 |
checker = KDChecker()
|
| 385 |
|
| 386 |
-
with gr.Blocks(title="Генератор чек-листов КД") as app:
|
| 387 |
gr.Markdown("# ✅ Генератор чек-листов КД")
|
| 388 |
gr.Markdown("Автоматическая проверка конструкторской документации по базе знаний Excel.")
|
| 389 |
|
| 390 |
with gr.Row():
|
| 391 |
-
with gr.Column():
|
| 392 |
-
gr.Markdown("### 1. База знаний")
|
| 393 |
-
db_in = gr.File(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
manual_cab = gr.Dropdown(
|
| 395 |
-
label="Или выберите
|
| 396 |
choices=[],
|
| 397 |
-
interactive=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
)
|
| 399 |
-
db_out = gr.Textbox(label="Статус загрузки", lines=6)
|
| 400 |
-
db_in.upload(checker.load_excel_db, inputs=[db_in], outputs=[db_out, manual_cab])
|
| 401 |
|
| 402 |
-
with gr.Column():
|
| 403 |
-
gr.Markdown("### 2. Документация (PDF)")
|
| 404 |
-
files_in = gr.File(
|
| 405 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
with gr.Row():
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
|
| 413 |
return app
|
| 414 |
|
| 415 |
|
| 416 |
-
#
|
| 417 |
app = create_app()
|
| 418 |
|
| 419 |
-
# Запуск для Hugging Face Spaces
|
| 420 |
if __name__ == "__main__":
|
| 421 |
-
|
| 422 |
-
username = os.environ.get("GRADIO_USERNAME")
|
| 423 |
-
password = os.environ.get("GRADIO_PASSWORD")
|
| 424 |
-
|
| 425 |
-
auth = (username, password) if username and password else None
|
| 426 |
|
| 427 |
app.launch(
|
| 428 |
server_name="0.0.0.0",
|
| 429 |
server_port=7860,
|
| 430 |
-
auth=
|
|
|
|
| 431 |
)
|
|
|
|
| 11 |
from reportlab.pdfbase.ttfonts import TTFont
|
| 12 |
from reportlab.lib import colors
|
| 13 |
|
| 14 |
+
# ========== НАСТРОЙКИ АВТОРИЗАЦИИ ==========
|
| 15 |
+
AUTH_USERNAME = "admin"
|
| 16 |
+
AUTH_PASSWORD = "12345"
|
| 17 |
+
# ===========================================
|
| 18 |
+
|
| 19 |
+
print("===== Application Startup =====")
|
| 20 |
+
print(f"Time: {datetime.now()}")
|
| 21 |
+
print(f"Auth enabled: Username={AUTH_USERNAME}")
|
| 22 |
+
print("================================")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
class KDChecker:
|
| 26 |
def __init__(self):
|
| 27 |
self.excel_db = pd.DataFrame()
|
| 28 |
self.cabinet_list = []
|
| 29 |
self.known_docs = ["Э3", "В4", "ПЭ3", "ВО", "ТЭ5", "СБ", "С5", "ОЛ", "Э1", "Э4", "Э7", "Д3", "Э6"]
|
| 30 |
+
print("[KDChecker] Инициализация завершена")
|
| 31 |
|
| 32 |
+
def load_excel_db(self, excel_file):
|
| 33 |
+
"""Загрузка Excel базы знаний"""
|
| 34 |
+
log = [f"[{datetime.now().strftime('%H:%M:%S')}] Старт загрузки Excel"]
|
| 35 |
|
| 36 |
+
# Проверка входных данных
|
| 37 |
+
if excel_file is None:
|
| 38 |
+
log.append("ERROR: excel_file is None")
|
| 39 |
+
return "\n".join(log), gr.update(choices=[], value=None)
|
| 40 |
+
|
| 41 |
+
# Определяем путь к файлу (gradio может передать разные типы)
|
| 42 |
+
if isinstance(excel_file, str):
|
| 43 |
+
excel_path = excel_file
|
| 44 |
+
elif hasattr(excel_file, 'name'):
|
| 45 |
+
excel_path = excel_file.name
|
| 46 |
+
else:
|
| 47 |
+
excel_path = str(excel_file)
|
| 48 |
+
|
| 49 |
+
log.append(f"Тип входных данных: {type(excel_file)}")
|
| 50 |
log.append(f"Путь к файлу: {excel_path}")
|
| 51 |
|
| 52 |
+
# Проверка существования файла
|
| 53 |
+
if not os.path.exists(excel_path):
|
| 54 |
+
log.append(f"ERROR: Файл не найден по пути: {excel_path}")
|
| 55 |
+
return "\n".join(log), gr.update(choices=[], value=None)
|
| 56 |
+
|
| 57 |
try:
|
| 58 |
size = os.path.getsize(excel_path)
|
| 59 |
log.append(f"Размер файла: {size} байт")
|
| 60 |
except Exception as e:
|
| 61 |
+
log.append(f"ERROR при получении размера: {e}")
|
| 62 |
return "\n".join(log), gr.update(choices=[], value=None)
|
| 63 |
|
| 64 |
+
# Проверка openpyxl
|
| 65 |
try:
|
| 66 |
import openpyxl
|
| 67 |
+
log.append(f"openpyxl version: {openpyxl.__version__}")
|
| 68 |
+
except ImportError as e:
|
| 69 |
+
log.append(f"ERROR: openpyxl не установлен: {e}")
|
| 70 |
+
return "\n".join(log), gr.update(choices=[], value=None)
|
| 71 |
|
| 72 |
all_data = []
|
| 73 |
sheets_log = []
|
| 74 |
|
| 75 |
try:
|
| 76 |
+
log.append("Чтение Excel файла...")
|
| 77 |
xls = pd.read_excel(excel_path, sheet_name=None, header=None, engine='openpyxl')
|
| 78 |
+
log.append(f"Найдено листов: {len(xls)}")
|
| 79 |
+
log.append(f"Имена листов: {list(xls.keys())}")
|
| 80 |
|
| 81 |
for sheet_name, df_raw in xls.items():
|
| 82 |
+
log.append(f"--- Обработка листа: '{sheet_name}' ({len(df_raw)} строк) ---")
|
| 83 |
+
|
| 84 |
header_row_index = -1
|
| 85 |
cab_col_idx = -1
|
| 86 |
rem_col_idx = -1
|
| 87 |
|
| 88 |
+
# Поиск заголовков в первых 20 строках
|
| 89 |
for i in range(min(20, len(df_raw))):
|
| 90 |
row_values = [str(x).lower().strip() for x in df_raw.iloc[i].values]
|
| 91 |
c_idx = -1
|
| 92 |
r_idx = -1
|
| 93 |
for idx, val in enumerate(row_values):
|
| 94 |
+
if "шкаф" in val or "cabinet" in val:
|
| 95 |
c_idx = idx
|
| 96 |
+
if "примечание" in val or "remark" in val:
|
| 97 |
r_idx = idx
|
| 98 |
if c_idx != -1 and r_idx != -1:
|
| 99 |
header_row_index = i
|
| 100 |
cab_col_idx = c_idx
|
| 101 |
rem_col_idx = r_idx
|
| 102 |
+
log.append(f" Заголовки найдены в строке {i}: шкаф={c_idx}, примечание={r_idx}")
|
| 103 |
break
|
| 104 |
|
| 105 |
if header_row_index != -1:
|
| 106 |
df = pd.read_excel(excel_path, sheet_name=sheet_name, header=header_row_index, engine='openpyxl')
|
| 107 |
+
log.append(f" Колонок в листе: {len(df.columns)}")
|
| 108 |
+
|
| 109 |
if cab_col_idx < len(df.columns) and rem_col_idx < len(df.columns):
|
| 110 |
df_subset = df.iloc[:, [cab_col_idx, rem_col_idx]]
|
| 111 |
df_subset.columns = ["Cabinet", "Remark"]
|
|
|
|
| 115 |
lambda x: x.strip().replace(" ", "").replace("\n", "").replace("\r", "")
|
| 116 |
)
|
| 117 |
all_data.append(df_subset)
|
| 118 |
+
sheets_log.append(f"'{sheet_name}': {len(df_subset)} записей")
|
| 119 |
+
log.append(f" ✓ Добавлено {len(df_subset)} записей")
|
| 120 |
else:
|
| 121 |
+
sheets_log.append(f"'{sheet_name}': ошибка индексов")
|
| 122 |
+
log.append(f" ✗ Ошибка индексов колонок")
|
| 123 |
else:
|
| 124 |
+
sheets_log.append(f"'{sheet_name}': заголовки не найдены")
|
| 125 |
+
log.append(f" ✗ Заголовки 'шкаф'/'примечание' не найдены")
|
| 126 |
|
| 127 |
if not all_data:
|
| 128 |
+
log.append("ИТОГ: Не найдены данные ни на одном листе!")
|
| 129 |
return "\n".join(log), gr.update(choices=[], value=None)
|
| 130 |
|
| 131 |
self.excel_db = pd.concat(all_data, ignore_index=True)
|
| 132 |
self.cabinet_list = sorted(self.excel_db["Cabinet"].unique().tolist())
|
| 133 |
|
| 134 |
+
log.append(f"ИТОГ: Загружено {len(self.excel_db)} записей")
|
| 135 |
+
log.append(f"Уникальных шкафов: {len(self.cabinet_list)}")
|
| 136 |
|
| 137 |
+
result_msg = f"✅ База загружена успешно!\n\n"
|
| 138 |
+
result_msg += f"📊 Всего записей: {len(self.excel_db)}\n"
|
| 139 |
+
result_msg += f"🗄️ Шкафов: {len(self.cabinet_list)}\n"
|
| 140 |
+
result_msg += f"📋 Листы: {', '.join(sheets_log)}"
|
| 141 |
+
|
| 142 |
+
return result_msg, gr.update(choices=self.cabinet_list, value=None)
|
| 143 |
|
| 144 |
except Exception as e:
|
| 145 |
log.append(f"КРИТИЧЕСКАЯ ОШИБКА: {str(e)}")
|
|
|
|
| 148 |
return "\n".join(log), gr.update(choices=[], value=None)
|
| 149 |
|
| 150 |
def extract_text(self, pdf_path):
|
| 151 |
+
"""Извлечение текста из PDF"""
|
| 152 |
try:
|
| 153 |
full_text = ""
|
| 154 |
with pdfplumber.open(pdf_path) as pdf:
|
| 155 |
for page in pdf.pages:
|
| 156 |
full_text += (page.extract_text() or "") + "\n"
|
| 157 |
return full_text
|
| 158 |
+
except Exception as e:
|
| 159 |
+
print(f"[extract_text] Error: {e}")
|
| 160 |
return ""
|
| 161 |
|
| 162 |
def find_all_decimal_numbers(self, text):
|
| 163 |
+
"""Поиск децимальных номеров в тексте"""
|
| 164 |
pattern = r"(РЛТ|ЛДАР|ВНАР|ШТМ)[\s\.]*\d{1}[\s\.]*\d{3}[\s\.]*[А-ЯA-Z]{1,4}[\s\.]*\d{3}(-[\d]+)?"
|
| 165 |
matches = []
|
| 166 |
for match in re.finditer(pattern, text):
|
|
|
|
| 170 |
return matches
|
| 171 |
|
| 172 |
def determine_doc_type(self, filename):
|
| 173 |
+
"""Определение типа документа по имени файла"""
|
| 174 |
fname = filename.upper()
|
| 175 |
if "С2" in fname: return "С2"
|
| 176 |
if "ПЭ3" in fname or "ПЕРЕЧЕНЬ" in fname: return "ПЭ3"
|
|
|
|
| 188 |
return "UNKNOWN"
|
| 189 |
|
| 190 |
def get_remarks(self, cabinet_key, is_clean_key=True):
|
| 191 |
+
"""Получение замечаний для шкафа"""
|
| 192 |
if self.excel_db.empty:
|
| 193 |
return {}
|
| 194 |
+
|
| 195 |
if is_clean_key:
|
| 196 |
target = cabinet_key.replace(" ", "")
|
| 197 |
mask = self.excel_db['Cabinet_Clean'].str.contains(re.escape(target), case=False, na=False)
|
|
|
|
| 207 |
cell_text = str(remark_cell)
|
| 208 |
cell_text = re.sub(r'(\d+)\.([А-ЯA-Z])', r'\1. \2', cell_text)
|
| 209 |
items = re.split(r'(?:^|\n)\s*(?=\d+[\.\)])', cell_text)
|
| 210 |
+
|
| 211 |
for item in items:
|
| 212 |
if len(item) < 3:
|
| 213 |
continue
|
|
|
|
| 215 |
clean_item_no_num = re.sub(r'^\d+[\.\)]\s*', '', clean_item)
|
| 216 |
doc_pattern = r'^(?:Документ\s+|В\s+)?([А-ЯA-Z0-9\s,\(\)\-]+?)(?:[\.\:\-]|\s+)(.*)'
|
| 217 |
match = re.match(doc_pattern, clean_item_no_num, re.IGNORECASE | re.DOTALL)
|
| 218 |
+
|
| 219 |
detected_docs = []
|
| 220 |
final_text = clean_item
|
| 221 |
+
|
| 222 |
if match:
|
| 223 |
potential_docs_str = match.group(1).upper()
|
| 224 |
cleaned_codes = potential_docs_str.replace("(", " ").replace(")", " ").replace(",", " ")
|
|
|
|
| 227 |
if valid_parts:
|
| 228 |
detected_docs = valid_parts
|
| 229 |
final_text = match.group(2).strip()
|
| 230 |
+
|
| 231 |
if not detected_docs:
|
| 232 |
detected_docs = ["ALL"]
|
| 233 |
+
|
| 234 |
for doc in detected_docs:
|
| 235 |
if doc not in parsed:
|
| 236 |
parsed[doc] = []
|
| 237 |
parsed[doc].append(final_text)
|
| 238 |
+
|
| 239 |
return parsed
|
| 240 |
|
| 241 |
def check_files(self, files, manual_cabinet):
|
| 242 |
+
"""Проверка PDF файлов"""
|
| 243 |
if not files:
|
| 244 |
+
return "❌ Файлы не загружены", None
|
| 245 |
if self.excel_db.empty:
|
| 246 |
+
return "❌ Сначала загрузите Excel базу!", None
|
| 247 |
|
| 248 |
checklist = {}
|
| 249 |
detected_cabinet = "Не определен"
|
| 250 |
found_by_method = ""
|
| 251 |
is_manual = False
|
| 252 |
|
| 253 |
+
# Обработка входных файлов
|
| 254 |
+
file_paths = []
|
| 255 |
+
for f in files:
|
| 256 |
+
if isinstance(f, str):
|
| 257 |
+
file_paths.append(f)
|
| 258 |
+
elif hasattr(f, 'name'):
|
| 259 |
+
file_paths.append(f.name)
|
| 260 |
+
else:
|
| 261 |
+
file_paths.append(str(f))
|
| 262 |
+
|
| 263 |
if manual_cabinet and manual_cabinet.strip():
|
| 264 |
detected_cabinet = manual_cabinet
|
| 265 |
found_by_method = "manual"
|
| 266 |
is_manual = True
|
| 267 |
else:
|
| 268 |
all_pdf_text = ""
|
| 269 |
+
for file_path in file_paths:
|
| 270 |
all_pdf_text += self.extract_text(file_path) + "\n"
|
| 271 |
|
| 272 |
pdf_numbers = self.find_all_decimal_numbers(all_pdf_text)
|
|
|
|
| 293 |
break
|
| 294 |
|
| 295 |
if detected_cabinet == "Не определен":
|
| 296 |
+
return "⚠️ Шкаф не опознан автоматически.\nВыберите шкаф из списка вручную.", None
|
| 297 |
|
| 298 |
is_clean_search = (found_by_method == "number")
|
| 299 |
remarks = self.get_remarks(detected_cabinet, is_clean_key=is_clean_search)
|
| 300 |
|
| 301 |
if not remarks:
|
| 302 |
+
return f"⚠️ Шкаф '{detected_cabinet}' найден, но замечаний в базе нет.", None
|
| 303 |
|
| 304 |
processed_count = 0
|
| 305 |
+
for file_path in file_paths:
|
| 306 |
fname = os.path.basename(file_path)
|
| 307 |
dtype = self.determine_doc_type(fname)
|
| 308 |
|
|
|
|
| 318 |
|
| 319 |
pdf_title = detected_cabinet
|
| 320 |
if is_manual:
|
| 321 |
+
pdf_title += " (Ручной выбор)"
|
| 322 |
|
| 323 |
try:
|
| 324 |
+
pdf_path = self.create_pdf(pdf_title, checklist)
|
| 325 |
except Exception as e:
|
| 326 |
return f"❌ Ошибка создания PDF: {e}", None
|
| 327 |
|
|
|
|
| 329 |
method_str = "Ручной выбор" if is_manual else (
|
| 330 |
"По децимальному номеру" if is_clean_search else "По наименованию")
|
| 331 |
|
| 332 |
+
result = f"✅ Чек-лист сформирован!\n\n"
|
| 333 |
+
result += f"📂 Шкаф: {detected_cabinet}\n"
|
| 334 |
+
result += f"🔍 Метод определения: {method_str}\n"
|
| 335 |
+
result += f"📄 Обработано файлов: {processed_count}\n"
|
| 336 |
+
result += f"🚩 Всего замечаний: {total}"
|
| 337 |
+
|
| 338 |
+
return result, pdf_path
|
| 339 |
|
| 340 |
def create_pdf(self, cabinet, data):
|
| 341 |
+
"""Создание PDF чек-листа"""
|
| 342 |
fname = "CheckList_Result.pdf"
|
| 343 |
path = os.path.join(tempfile.gettempdir(), fname)
|
| 344 |
c = canvas.Canvas(path, pagesize=A4)
|
|
|
|
| 345 |
width, height = A4
|
| 346 |
|
| 347 |
+
# Шрифт
|
| 348 |
font_name = 'Helvetica'
|
| 349 |
font_path = "arial.ttf"
|
|
|
|
| 350 |
if os.path.exists(font_path):
|
| 351 |
try:
|
| 352 |
pdfmetrics.registerFont(TTFont('Arial', font_path))
|
|
|
|
| 361 |
c.drawString(50, y, "ЧЕК-ЛИСТ ПРОВЕРКИ КД")
|
| 362 |
except:
|
| 363 |
c.setFont("Helvetica", 16)
|
| 364 |
+
c.drawString(50, y, "CHECK-LIST KD")
|
|
|
|
| 365 |
|
| 366 |
y -= 25
|
| 367 |
c.setFont(font_name, 12)
|
|
|
|
| 371 |
c.drawString(50, y, f"Шкаф: {disp_cab}")
|
| 372 |
except:
|
| 373 |
c.setFont("Helvetica", 12)
|
| 374 |
+
c.drawString(50, y, f"Cabinet: {disp_cab}")
|
|
|
|
| 375 |
|
| 376 |
c.drawString(400, y, f"Дата: {datetime.now().strftime('%d.%m.%Y')}")
|
| 377 |
y -= 20
|
|
|
|
| 383 |
c.save()
|
| 384 |
return path
|
| 385 |
|
|
|
|
| 386 |
for filename, tasks in data.items():
|
| 387 |
if y < 100:
|
| 388 |
c.showPage()
|
|
|
|
| 396 |
except:
|
| 397 |
c.setFont("Helvetica", 11)
|
| 398 |
c.drawString(50, y, f"File: {filename}")
|
|
|
|
| 399 |
|
| 400 |
c.setFillColor(colors.black)
|
| 401 |
y -= 15
|
| 402 |
c.setFont(font_name, 10)
|
| 403 |
|
| 404 |
for task in tasks:
|
|
|
|
|
|
|
| 405 |
if y < 80:
|
| 406 |
c.showPage()
|
| 407 |
y = height - 50
|
| 408 |
c.setFont(font_name, 10)
|
| 409 |
|
| 410 |
+
c.rect(50, y - 2, 8, 8, stroke=1, fill=0)
|
| 411 |
+
|
| 412 |
+
# Разбивка текста на строки
|
| 413 |
+
max_len = 90
|
| 414 |
+
words = task.replace('\n', ' ').split(' ')
|
| 415 |
+
lines = []
|
| 416 |
+
cur_line = ""
|
| 417 |
+
for w in words:
|
| 418 |
+
if len(cur_line) + len(w) + 1 <= max_len:
|
| 419 |
+
cur_line += w + " "
|
| 420 |
+
else:
|
| 421 |
+
lines.append(cur_line.strip())
|
| 422 |
+
cur_line = w + " "
|
| 423 |
+
if cur_line:
|
| 424 |
+
lines.append(cur_line.strip())
|
| 425 |
+
|
| 426 |
+
for i, line in enumerate(lines):
|
| 427 |
+
if y < 40:
|
| 428 |
+
c.showPage()
|
| 429 |
+
y = height - 50
|
| 430 |
+
c.setFont(font_name, 10)
|
| 431 |
+
x_offset = 65 if i == 0 else 65
|
| 432 |
+
try:
|
| 433 |
+
c.drawString(x_offset, y, line)
|
| 434 |
+
except:
|
| 435 |
+
pass
|
| 436 |
+
y -= 12
|
| 437 |
+
|
| 438 |
+
y -= 5
|
|
|
|
|
|
|
| 439 |
|
| 440 |
y -= 10
|
| 441 |
c.setStrokeColor(colors.lightgrey)
|
| 442 |
c.line(50, y, width - 50, y)
|
| 443 |
c.setStrokeColor(colors.black)
|
| 444 |
+
y -= 15
|
| 445 |
|
| 446 |
c.save()
|
| 447 |
return path
|
|
|
|
| 450 |
def create_app():
|
| 451 |
checker = KDChecker()
|
| 452 |
|
| 453 |
+
with gr.Blocks(title="Генератор чек-листов КД", theme=gr.themes.Soft()) as app:
|
| 454 |
gr.Markdown("# ✅ Генератор чек-листов КД")
|
| 455 |
gr.Markdown("Автоматическая проверка конструкторской документации по базе знаний Excel.")
|
| 456 |
|
| 457 |
with gr.Row():
|
| 458 |
+
with gr.Column(scale=1):
|
| 459 |
+
gr.Markdown("### 📁 1. База знаний")
|
| 460 |
+
db_in = gr.File(
|
| 461 |
+
label="Загрузить Excel (.xlsx)",
|
| 462 |
+
file_types=[".xlsx", ".xls"],
|
| 463 |
+
type="filepath"
|
| 464 |
+
)
|
| 465 |
manual_cab = gr.Dropdown(
|
| 466 |
+
label="Или выберите шкаф вручную",
|
| 467 |
choices=[],
|
| 468 |
+
interactive=True,
|
| 469 |
+
allow_custom_value=False
|
| 470 |
+
)
|
| 471 |
+
db_out = gr.Textbox(
|
| 472 |
+
label="Статус загрузки",
|
| 473 |
+
lines=8,
|
| 474 |
+
max_lines=15
|
| 475 |
)
|
|
|
|
|
|
|
| 476 |
|
| 477 |
+
with gr.Column(scale=1):
|
| 478 |
+
gr.Markdown("### 📄 2. Документация (PDF)")
|
| 479 |
+
files_in = gr.File(
|
| 480 |
+
label="Загрузить чертежи (PDF)",
|
| 481 |
+
file_count="multiple",
|
| 482 |
+
file_types=[".pdf"],
|
| 483 |
+
type="filepath"
|
| 484 |
+
)
|
| 485 |
+
btn = gr.Button("🔍 Сформировать чек-лист", variant="primary", size="lg")
|
| 486 |
|
| 487 |
with gr.Row():
|
| 488 |
+
with gr.Column(scale=1):
|
| 489 |
+
res_txt = gr.Textbox(label="Результат проверки", lines=8)
|
| 490 |
+
with gr.Column(scale=1):
|
| 491 |
+
res_pdf = gr.File(label="📥 Скачать PDF чек-лист")
|
| 492 |
+
|
| 493 |
+
# Привязка событий
|
| 494 |
+
db_in.change(
|
| 495 |
+
fn=checker.load_excel_db,
|
| 496 |
+
inputs=[db_in],
|
| 497 |
+
outputs=[db_out, manual_cab]
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
btn.click(
|
| 501 |
+
fn=checker.check_files,
|
| 502 |
+
inputs=[files_in, manual_cab],
|
| 503 |
+
outputs=[res_txt, res_pdf]
|
| 504 |
+
)
|
| 505 |
|
| 506 |
return app
|
| 507 |
|
| 508 |
|
| 509 |
+
# ========== ЗАПУСК ПРИЛОЖЕНИЯ ==========
|
| 510 |
app = create_app()
|
| 511 |
|
|
|
|
| 512 |
if __name__ == "__main__":
|
| 513 |
+
print(f"Starting with auth: {AUTH_USERNAME} / {'*' * len(AUTH_PASSWORD)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 514 |
|
| 515 |
app.launch(
|
| 516 |
server_name="0.0.0.0",
|
| 517 |
server_port=7860,
|
| 518 |
+
auth=(AUTH_USERNAME, AUTH_PASSWORD),
|
| 519 |
+
auth_message="Введите логин и пароль для доступа"
|
| 520 |
)
|