Ed5 commited on
Commit
3107b38
·
verified ·
1 Parent(s): 8ba65ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -31
app.py CHANGED
@@ -94,26 +94,16 @@ class KDChecker:
94
 
95
  def find_all_decimal_numbers(self, text):
96
  matches = []
97
-
98
- # Шаблон 1: Специфичный (РЛТ.1.006.ША.030)
99
- # Ищет: Префикс + цифра + 3 цифры + буквы + 3 цифры
100
  pattern_custom = r"(РЛТ|ЛДАР|ВНАР|ШТМ)[\s\.]*\d{1}[\s\.]*\d{3}[\s\.]*[А-ЯA-Z]{1,4}[\s\.]*\d{3}(-[\d]+)?"
101
-
102
- # Шаблон 2: Стандартный ГОСТ (ЛДАР.421246.337)
103
- # Ищет: Префикс + точка + 6 цифр + точка + 3 цифры (допускаются пробелы вместо точек)
104
  pattern_gost = r"(РЛТ|ЛДАР|ВНАР|ШТМ)[\s\.]*\d{6}[\s\.]*\d{3}"
105
 
106
- # Ищем по первому шаблону
107
  for match in re.finditer(pattern_custom, text):
108
  clean_num = match.group(0).replace(" ", "").replace("\n", "")
109
- if clean_num not in matches:
110
- matches.append(clean_num)
111
 
112
- # Ищем по второму шаблону
113
  for match in re.finditer(pattern_gost, text):
114
  clean_num = match.group(0).replace(" ", "").replace("\n", "")
115
- if clean_num not in matches:
116
- matches.append(clean_num)
117
 
118
  return matches
119
 
@@ -191,7 +181,7 @@ class KDChecker:
191
  for file_path in progress.tqdm(files, desc="Поиск номера шкафа"):
192
  raw_text = self.extract_text(file_path)
193
 
194
- # --- ПОИСК ПО НОМЕРУ (2 ШАБЛОНА) ---
195
  pdf_numbers = self.find_all_decimal_numbers(raw_text)
196
  for cand in pdf_numbers:
197
  if cand in db_clean_keys:
@@ -203,16 +193,11 @@ class KDChecker:
203
  print(f"✅ Шкаф найден по номеру: {detected_cabinet}")
204
  break
205
 
206
- # --- ПОИСК ПО ИМЕНИ (УЛУЧШЕННЫЙ) ---
207
- # Убираем переносы строк, чтобы "Шкаф\nСАУ" стало "Шкаф САУ"
208
  flat_text = raw_text.replace("\n", " ").replace(" ", " ").lower()
209
-
210
  unique_cabinets = self.excel_db["Cabinet"].unique()
211
  for cab_name in unique_cabinets:
212
- # Ищем только если это похоже на название, а не на код
213
  if "ЛДАР" in cab_name or "РЛТ" in cab_name: continue
214
-
215
- # Проверяем точное вхождение названия
216
  clean_name = cab_name.lower().strip()
217
  if len(clean_name) > 5 and clean_name in flat_text:
218
  detected_cabinet = cab_name
@@ -220,8 +205,7 @@ class KDChecker:
220
  print(f"✅ Шкаф найден по имени: {cab_name}")
221
  break
222
 
223
- if found_by_method == "name":
224
- break
225
 
226
  print(f"Определен шкаф: {detected_cabinet}")
227
 
@@ -261,7 +245,10 @@ class KDChecker:
261
  return f"✅ Готово!\n📂 Шкаф: {detected_cabinet}\n🔍 Метод: {method_str}\n📄 Файлов: {processed_count}\n🚩 Замечаний: {total}", pdf
262
 
263
  def create_pdf(self, cabinet, data):
264
- fname = f"CheckList_Result.pdf"
 
 
 
265
  path = os.path.join(tempfile.gettempdir(), fname)
266
  c = canvas.Canvas(path, pagesize=A4)
267
  form = c.acroForm
@@ -346,18 +333,38 @@ class KDChecker:
346
 
347
  # --- ИНТЕРФЕЙС ---
348
 
 
349
  css = """
350
  .gradio-container { max-width: 95% !important; }
351
- .compact_file { height: 150px !important; min-height: 150px !important; max-height: 150px !important; overflow: hidden !important; }
352
- .orange_btn { background: #FF7F27 !important; border: none !important; color: white !important; font-weight: bold; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
  .orange_btn:hover { background: #E06010 !important; }
 
354
  footer { display: none !important; }
355
  """
356
 
357
  def create_app():
358
  checker = KDChecker()
359
 
360
- with gr.Blocks(title="Генератор чек-листов КД") as app:
 
361
  gr.Markdown("## ✅ Генератор чек-листов КД")
362
 
363
  with gr.Row():
@@ -392,10 +399,9 @@ def create_app():
392
 
393
  if __name__ == "__main__":
394
  app = create_app()
 
395
  app.launch(
396
- server_name="0.0.0.0",
397
- server_port=7860,
398
- css=css,
399
- theme=gr.themes.Soft(),
400
- auth=("admin", "12345") # <--- ДОБАВЬТЕ ЭТО (Логин, Пароль)
401
- )
 
94
 
95
  def find_all_decimal_numbers(self, text):
96
  matches = []
 
 
 
97
  pattern_custom = r"(РЛТ|ЛДАР|ВНАР|ШТМ)[\s\.]*\d{1}[\s\.]*\d{3}[\s\.]*[А-ЯA-Z]{1,4}[\s\.]*\d{3}(-[\d]+)?"
 
 
 
98
  pattern_gost = r"(РЛТ|ЛДАР|ВНАР|ШТМ)[\s\.]*\d{6}[\s\.]*\d{3}"
99
 
 
100
  for match in re.finditer(pattern_custom, text):
101
  clean_num = match.group(0).replace(" ", "").replace("\n", "")
102
+ if clean_num not in matches: matches.append(clean_num)
 
103
 
 
104
  for match in re.finditer(pattern_gost, text):
105
  clean_num = match.group(0).replace(" ", "").replace("\n", "")
106
+ if clean_num not in matches: matches.append(clean_num)
 
107
 
108
  return matches
109
 
 
181
  for file_path in progress.tqdm(files, desc="Поиск номера шкафа"):
182
  raw_text = self.extract_text(file_path)
183
 
184
+ # Поиск по номеру
185
  pdf_numbers = self.find_all_decimal_numbers(raw_text)
186
  for cand in pdf_numbers:
187
  if cand in db_clean_keys:
 
193
  print(f"✅ Шкаф найден по номеру: {detected_cabinet}")
194
  break
195
 
196
+ # Поиск по имени
 
197
  flat_text = raw_text.replace("\n", " ").replace(" ", " ").lower()
 
198
  unique_cabinets = self.excel_db["Cabinet"].unique()
199
  for cab_name in unique_cabinets:
 
200
  if "ЛДАР" in cab_name or "РЛТ" in cab_name: continue
 
 
201
  clean_name = cab_name.lower().strip()
202
  if len(clean_name) > 5 and clean_name in flat_text:
203
  detected_cabinet = cab_name
 
205
  print(f"✅ Шкаф найден по имени: {cab_name}")
206
  break
207
 
208
+ if found_by_method == "name": break
 
209
 
210
  print(f"Определен шкаф: {detected_cabinet}")
211
 
 
245
  return f"✅ Готово!\n📂 Шкаф: {detected_cabinet}\n🔍 Метод: {method_str}\n📄 Файлов: {processed_count}\n🚩 Замечаний: {total}", pdf
246
 
247
  def create_pdf(self, cabinet, data):
248
+ # ФОРМИРОВАНИЕ ПРАВИЛЬНОГО ИМЕНИ ФАЙЛА
249
+ safe_name = cabinet.replace(" ", "_").replace("/", "-").replace("\\", "-").replace(":", "")[:50]
250
+ fname = f"Checklist_{safe_name}.pdf"
251
+
252
  path = os.path.join(tempfile.gettempdir(), fname)
253
  c = canvas.Canvas(path, pagesize=A4)
254
  form = c.acroForm
 
333
 
334
  # --- ИНТЕРФЕЙС ---
335
 
336
+ # Усиленные CSS стили для работы с авторизацией
337
  css = """
338
  .gradio-container { max-width: 95% !important; }
339
+
340
+ /* Принудительно задаем стиль для блока файла */
341
+ .compact_file .file-preview {
342
+ height: 150px !important;
343
+ min-height: 150px !important;
344
+ max-height: 150px !important;
345
+ overflow: hidden !important;
346
+ }
347
+ .compact_file {
348
+ height: auto !important;
349
+ }
350
+
351
+ .orange_btn {
352
+ background: #FF7F27 !important;
353
+ border: none !important;
354
+ color: white !important;
355
+ font-weight: bold;
356
+ font-size: 16px !important;
357
+ }
358
  .orange_btn:hover { background: #E06010 !important; }
359
+
360
  footer { display: none !important; }
361
  """
362
 
363
  def create_app():
364
  checker = KDChecker()
365
 
366
+ # ВОЗВРАЩАЕМ THEME и CSS СЮДА (Это решает проблему с интерфейсом при авторизации)
367
+ with gr.Blocks(title="Генератор чек-листов КД", theme=gr.themes.Soft(), css=css) as app:
368
  gr.Markdown("## ✅ Генератор чек-листов КД")
369
 
370
  with gr.Row():
 
399
 
400
  if __name__ == "__main__":
401
  app = create_app()
402
+ # Оставляем здесь только настройки сервера и авторизацию
403
  app.launch(
404
+ server_name="0.0.0.0",
405
+ server_port=7860,
406
+ auth=("admin", "12345")
407
+ )