jin2li commited on
Commit
cd0baad
Β·
verified Β·
1 Parent(s): 6c87d2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1123 -1
app.py CHANGED
@@ -1353,4 +1353,1126 @@ def evaluate_local_rules(country, material, component, ingredient_totals, ingred
1353
  "λΉ„κ³ ": "-",
1354
  }
1355
 
1356
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1353
  "λΉ„κ³ ": "-",
1354
  }
1355
 
1356
+ return None
1357
+
1358
+ # ============================================================
1359
+ # 8. GPT 보쑰 νŒμ •
1360
+ # ============================================================
1361
+
1362
+ def parse_country_response(text):
1363
+ result = {
1364
+ "λŒ€ν‘œ INCI": "-",
1365
+ "κ²°κ³Ό": NO_EVIDENCE_TEXT,
1366
+ "ν‘œμ‹œλ¬Έκ΅¬": "Pass",
1367
+ "λΉ„κ³ ": "-",
1368
+ }
1369
+
1370
+ for line in safe_str(text).splitlines():
1371
+ line = line.strip()
1372
+
1373
+ if line.startswith("λŒ€ν‘œ INCI:"):
1374
+ result["λŒ€ν‘œ INCI"] = line.split(":", 1)[1].strip() or "-"
1375
+ elif line.startswith("κ²°κ³Ό:"):
1376
+ result["κ²°κ³Ό"] = line.split(":", 1)[1].strip() or NO_EVIDENCE_TEXT
1377
+ elif line.startswith("ν‘œμ‹œλ¬Έκ΅¬:"):
1378
+ result["ν‘œμ‹œλ¬Έκ΅¬"] = line.split(":", 1)[1].strip() or "Pass"
1379
+ elif line.startswith("λΉ„κ³ :"):
1380
+ result["λΉ„κ³ "] = line.split(":", 1)[1].strip() or "-"
1381
+
1382
+ return result
1383
+
1384
+
1385
+ def clean_json_text(text):
1386
+ text = safe_str(text)
1387
+ text = re.sub(r"^```json\s*", "", text.strip(), flags=re.IGNORECASE)
1388
+ text = re.sub(r"^```\s*", "", text.strip())
1389
+ text = re.sub(r"\s*```$", "", text.strip())
1390
+
1391
+ match = re.search(r"\[.*\]", text, flags=re.DOTALL)
1392
+ if match:
1393
+ return match.group(0)
1394
+
1395
+ match = re.search(r"\{.*\}", text, flags=re.DOTALL)
1396
+ if match:
1397
+ return match.group(0)
1398
+
1399
+ return text
1400
+
1401
+
1402
+ def sanitize_country_result(parsed, country_col="", component=None):
1403
+ if not isinstance(parsed, dict):
1404
+ parsed = {}
1405
+
1406
+ component = component or {}
1407
+
1408
+ representative = safe_str(parsed.get("λŒ€ν‘œ INCI", "")) or safe_str(component.get("INCI Name", "")) or "-"
1409
+ result_text = safe_str(parsed.get("κ²°κ³Ό", "")) or NO_EVIDENCE_TEXT
1410
+ note = safe_str(parsed.get("λΉ„κ³ ", "")) or "-"
1411
+
1412
+ display_text = safe_str(parsed.get("ν‘œμ‹œλ¬Έκ΅¬", ""))
1413
+ if not display_text:
1414
+ display_text = normalize_formula_country_text(
1415
+ result_text,
1416
+ country_col=country_col,
1417
+ inci_name=safe_str(component.get("INCI Name", "")),
1418
+ amount_text=safe_str(component.get("In formula(w/w %)", "")),
1419
+ )
1420
+
1421
+ bad_tokens = [
1422
+ "규제λͺ…",
1423
+ "μ΄λŸ‰ 계산",
1424
+ "규제 / μ΄λŸ‰",
1425
+ "{규제ꡰλͺ…}",
1426
+ "{μ„±λΆ„λͺ…",
1427
+ "{ν•¨λŸ‰}",
1428
+ "{κΈ°μ€€μΉ˜}",
1429
+ "placeholder",
1430
+ "N/A",
1431
+ "n/a",
1432
+ ]
1433
+
1434
+ if any(token in result_text for token in bad_tokens):
1435
+ result_text = "확인 ν•„μš” / 규제 μ„ΈλΆ€ 계산 μž¬ν™•μΈ ν•„μš”"
1436
+ display_text = "확인 ν•„μš”"
1437
+ if note == "-":
1438
+ note = "ꡬ체 ν•œλ„ λ˜λŠ” μ΄λŸ‰ 계산값 확인 ν•„μš”"
1439
+
1440
+ return {
1441
+ "λŒ€ν‘œ INCI": representative,
1442
+ "κ²°κ³Ό": result_text,
1443
+ "ν‘œμ‹œλ¬Έκ΅¬": display_text,
1444
+ "λΉ„κ³ ": note,
1445
+ }
1446
+
1447
+
1448
+ def make_eval_cache_key(country, component):
1449
+ amount = component.get("amount_float")
1450
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1451
+ db_signature = get_current_db_signature(country)
1452
+
1453
+ return (
1454
+ str(country),
1455
+ str(db_signature),
1456
+ safe_str(component.get("INCI Name", "")).lower(),
1457
+ safe_str(component.get("ν•œκΈ€ μ„±λΆ„λͺ…", "")).lower(),
1458
+ amount_text,
1459
+ )
1460
+
1461
+
1462
+ def has_meaningful_search_hit(db, search_text, ingredient_names, k=MEANINGFUL_HIT_K):
1463
+ if not db:
1464
+ return False, ""
1465
+
1466
+ try:
1467
+ docs = db.similarity_search(search_text, k=k)
1468
+ context = "\n".join([d.page_content for d in docs])
1469
+ except Exception:
1470
+ return False, ""
1471
+
1472
+ context_norm = normalize_compact(context)
1473
+
1474
+ for name in ingredient_names:
1475
+ name_norm = normalize_compact(name)
1476
+ if name_norm and len(name_norm) >= 3 and name_norm in context_norm:
1477
+ return True, context
1478
+
1479
+ return False, context
1480
+
1481
+
1482
+ def evaluate_component_with_llm(country, material, component, llm, target_id=""):
1483
+ db = build_database(country)
1484
+ country_col = display_country(country)
1485
+
1486
+ inci_name = safe_str(component.get("INCI Name", ""))
1487
+ korean_name = safe_str(component.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""))
1488
+ amount = component.get("amount_float")
1489
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1490
+
1491
+ if not inci_name and not korean_name:
1492
+ return {
1493
+ "λŒ€ν‘œ INCI": "-",
1494
+ "κ²°κ³Ό": "",
1495
+ "ν‘œμ‹œλ¬Έκ΅¬": "",
1496
+ "λΉ„κ³ ": "-",
1497
+ }
1498
+
1499
+ if not db:
1500
+ result = {
1501
+ "λŒ€ν‘œ INCI": inci_name or "-",
1502
+ "κ²°κ³Ό": NO_EVIDENCE_TEXT,
1503
+ "ν‘œμ‹œλ¬Έκ΅¬": "Pass",
1504
+ "λΉ„κ³ ": "-",
1505
+ }
1506
+ log_search_context(target_id, country, component, result["κ²°κ³Ό"], "NO_DB", "ν•΄λ‹Ή κ΅­κ°€/채널 규제 DB μ—†μŒ")
1507
+ return result
1508
+
1509
+ cache_key = make_eval_cache_key(country, component)
1510
+ if cache_key in EVAL_CACHE:
1511
+ return EVAL_CACHE[cache_key]
1512
+
1513
+ trade_ko = material.get("Trade name(κ΅­λ¬Έ)", "")
1514
+ trade_en = material.get("Trade name(영문)", "")
1515
+
1516
+ search_text = f"""
1517
+ κ΅­κ°€/채널: {country}
1518
+ μ›λ£Œλͺ… κ΅­λ¬Έ: {trade_ko}
1519
+ μ›λ£Œλͺ… 영문: {trade_en}
1520
+ κ²€ν†  μ„±λΆ„ κ΅­λ¬Έ: {korean_name}
1521
+ κ²€ν†  μ„±λΆ„ INCI/CAS: {inci_name}
1522
+ μ΅œμ’… μ œν’ˆ λ‚΄ ν•¨λŸ‰: {amount_text}%
1523
+ μ œν’ˆμœ ν˜•: Leave-on 및 Wash-off κΈ°μ€€ λͺ¨λ‘ 확인
1524
+ """
1525
+
1526
+ has_hit, pre_context = has_meaningful_search_hit(
1527
+ db=db,
1528
+ search_text=search_text,
1529
+ ingredient_names=[inci_name, korean_name],
1530
+ k=MEANINGFUL_HIT_K,
1531
+ )
1532
+
1533
+ if not has_hit:
1534
+ result = {
1535
+ "λŒ€ν‘œ INCI": inci_name or "-",
1536
+ "κ²°κ³Ό": NO_EVIDENCE_TEXT,
1537
+ "ν‘œμ‹œλ¬Έκ΅¬": "Pass",
1538
+ "λΉ„κ³ ": "-",
1539
+ }
1540
+ EVAL_CACHE[cache_key] = result
1541
+ log_search_context(target_id, country, component, result["κ²°κ³Ό"], "NO_MEANINGFUL_HIT", pre_context)
1542
+ return result
1543
+
1544
+ docs = db.similarity_search(search_text, k=RAG_TOP_K_SINGLE)
1545
+ context = "\n".join([d.page_content for d in docs])
1546
+
1547
+ prompt = f"""
1548
+ λ„ˆλŠ” ν™”μž₯ν’ˆ μ „μ„±λΆ„ 규제 μŠ€ν¬λ¦¬λ‹ μ „λ¬Έκ°€μ•Ό.
1549
+ μ•„λž˜ 단일 ꡬ성성뢄을 λ°˜λ“œμ‹œ "{country}" κΈ°μ€€μœΌλ‘œλ§Œ κ²€ν† ν•΄.
1550
+
1551
+ [μ ˆλŒ€ κ·œμΉ™]
1552
+ - ν˜„μž¬ κ²€ν†  κ΅­κ°€λŠ” "{country}"이닀.
1553
+ - μ•„λž˜ 검색 원문은 "{country}" ν΄λ”μ—μ„œλ§Œ κ²€μƒ‰λœ κ·Όκ±°λ‹€.
1554
+ - μ™ΈλΆ€ 지식, ν•™μŠ΅ 지식, 일반 규제 지식을 μ‚¬μš©ν•˜μ§€ 마.
1555
+ - λ‹€λ₯Έ κ΅­κ°€ κ·œμ •μ„ ν˜„μž¬ ꡭ가에 μž„μ˜ μ μš©ν•˜μ§€ 마.
1556
+ - 검색 원문에 λͺ…μ‹œλ˜μ§€ μ•Šμ€ μ œν•œ, λ°°ν•©κΈˆμ§€, λ°°ν•©ν•œλ„λŠ” λ§Œλ“€μ§€ 마.
1557
+ - 검색 원문에 λͺ…μ‹œλœ μ œν•œ/κΈˆμ§€/ν•œλ„ κ·Όκ±°κ°€ μ—†μœΌλ©΄ κ²°κ³ΌλŠ” μ •ν™•νžˆ "{NO_EVIDENCE_TEXT}"으둜 μž‘μ„±ν•΄.
1558
+
1559
+ [κ²€ν†  μ„±λΆ„]
1560
+ κ΅­λ¬Έλͺ…: {korean_name}
1561
+ INCI/CAS: {inci_name}
1562
+ μ΅œμ’… μ œν’ˆ λ‚΄ ν•¨λŸ‰: {amount_text}%
1563
+
1564
+ [κ²€μƒ‰λœ {country} 규제 원문]
1565
+ {context}
1566
+
1567
+ λ°˜λ“œμ‹œ μ•„λž˜ ν˜•μ‹μœΌλ‘œλ§Œ λ‹΅λ³€ν•΄.
1568
+ λŒ€ν‘œ INCI:
1569
+ κ²°κ³Ό:
1570
+ ν‘œμ‹œλ¬Έκ΅¬:
1571
+ λΉ„κ³ :
1572
+
1573
+ ν‘œμ‹œλ¬Έκ΅¬ μž‘μ„± κ·œμΉ™:
1574
+ - 문제 μ—†μœΌλ©΄ "Pass"
1575
+ - λ°°ν•©ν•œλ„κ°€ 있으면 "λ°°ν•©ν•œλ„: 10%"처럼 짧게 μž‘μ„±
1576
+ - μŠ€ν”„λ ˆμ΄/κΈ°νƒ€μ œν’ˆμ²˜λŸΌ 쑰건이 있으면 μ€„λ°”κΏˆμœΌλ‘œ μž‘μ„±
1577
+ - 라벨 ν‘œμ‹œκ°€ ν•„μš”ν•˜λ©΄ "라벨링 ν•„μˆ˜"
1578
+ - μ •ν™•ν•œ νŒλ‹¨μ΄ μ–΄λ €μš°λ©΄ "확인 ν•„μš”"
1579
+ """
1580
+
1581
+ try:
1582
+ response = llm.invoke(prompt).content
1583
+ parsed = parse_country_response(response)
1584
+ parsed = sanitize_country_result(parsed, country_col=country_col, component=component)
1585
+ EVAL_CACHE[cache_key] = parsed
1586
+ log_search_context(target_id, country, component, parsed["κ²°κ³Ό"], "GPT_SINGLE", context)
1587
+ return parsed
1588
+
1589
+ except Exception as e:
1590
+ result = {
1591
+ "λŒ€ν‘œ INCI": inci_name or "-",
1592
+ "κ²°κ³Ό": "확인 ν•„μš”",
1593
+ "ν‘œμ‹œλ¬Έκ΅¬": "확인 ν•„μš”",
1594
+ "λΉ„κ³ ": str(e),
1595
+ }
1596
+ log_search_context(target_id, country, component, result["κ²°κ³Ό"], "GPT_SINGLE_ERROR", str(e))
1597
+ return result
1598
+
1599
+
1600
+ def evaluate_components_with_llm_batch(country, targets, llm):
1601
+ results = {}
1602
+
1603
+ if not targets:
1604
+ return results
1605
+
1606
+ db = build_database(country)
1607
+ country_col = display_country(country)
1608
+
1609
+ if not db:
1610
+ for item in targets:
1611
+ comp = item["component"]
1612
+ inci_name = safe_str(comp.get("INCI Name", ""))
1613
+
1614
+ results[item["target_id"]] = {
1615
+ "λŒ€ν‘œ INCI": inci_name or "-",
1616
+ "κ²°κ³Ό": NO_EVIDENCE_TEXT,
1617
+ "ν‘œμ‹œλ¬Έκ΅¬": "Pass",
1618
+ "λΉ„κ³ ": "-",
1619
+ }
1620
+
1621
+ log_search_context(
1622
+ item["target_id"],
1623
+ country,
1624
+ comp,
1625
+ NO_EVIDENCE_TEXT,
1626
+ "NO_DB",
1627
+ "ν•΄λ‹Ή κ΅­κ°€/채널 규제 DB μ—†μŒ",
1628
+ )
1629
+
1630
+ return results
1631
+
1632
+ uncached_targets = []
1633
+
1634
+ for item in targets:
1635
+ comp = item["component"]
1636
+ cache_key = make_eval_cache_key(country, comp)
1637
+
1638
+ if cache_key in EVAL_CACHE:
1639
+ results[item["target_id"]] = EVAL_CACHE[cache_key]
1640
+ else:
1641
+ uncached_targets.append(item)
1642
+
1643
+ filtered_targets = []
1644
+
1645
+ for item in uncached_targets:
1646
+ material = item["material"]
1647
+ comp = item["component"]
1648
+
1649
+ inci_name = safe_str(comp.get("INCI Name", ""))
1650
+ korean_name = safe_str(comp.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""))
1651
+ amount = comp.get("amount_float")
1652
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1653
+
1654
+ search_text = f"""
1655
+ κ΅­κ°€/채널: {country}
1656
+ μ›λ£Œλͺ… κ΅­λ¬Έ: {material.get("Trade name(κ΅­λ¬Έ)", "")}
1657
+ μ›λ£Œλͺ… 영문: {material.get("Trade name(영문)", "")}
1658
+ κ²€ν†  μ„±λΆ„ κ΅­λ¬Έ: {korean_name}
1659
+ κ²€ν†  μ„±λΆ„ INCI/CAS: {inci_name}
1660
+ μ΅œμ’… μ œν’ˆ λ‚΄ ν•¨λŸ‰: {amount_text}%
1661
+ """
1662
+
1663
+ has_hit, context = has_meaningful_search_hit(
1664
+ db=db,
1665
+ search_text=search_text,
1666
+ ingredient_names=[inci_name, korean_name],
1667
+ k=MEANINGFUL_HIT_K,
1668
+ )
1669
+
1670
+ if has_hit:
1671
+ filtered_targets.append(item)
1672
+ else:
1673
+ result = {
1674
+ "λŒ€ν‘œ INCI": inci_name or "-",
1675
+ "κ²°κ³Ό": NO_EVIDENCE_TEXT,
1676
+ "ν‘œμ‹œλ¬Έκ΅¬": "Pass",
1677
+ "λΉ„κ³ ": "-",
1678
+ }
1679
+ results[item["target_id"]] = result
1680
+ EVAL_CACHE[make_eval_cache_key(country, comp)] = result
1681
+ log_search_context(
1682
+ item["target_id"],
1683
+ country,
1684
+ comp,
1685
+ result["κ²°κ³Ό"],
1686
+ "NO_MEANINGFUL_HIT",
1687
+ context,
1688
+ )
1689
+
1690
+ uncached_targets = filtered_targets
1691
+
1692
+ if not uncached_targets:
1693
+ return results
1694
+
1695
+ for batch in chunk_list(uncached_targets, BATCH_SIZE):
1696
+ target_payload = []
1697
+ search_blocks = []
1698
+
1699
+ for item in batch:
1700
+ material = item["material"]
1701
+ comp = item["component"]
1702
+
1703
+ inci_name = safe_str(comp.get("INCI Name", ""))
1704
+ korean_name = safe_str(comp.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""))
1705
+ amount = comp.get("amount_float")
1706
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1707
+
1708
+ target_payload.append({
1709
+ "target_id": item["target_id"],
1710
+ "μ„±λΆ„ κ΅­λ¬Έλͺ…": korean_name,
1711
+ "INCI/CAS": inci_name,
1712
+ "μ΅œμ’… μ œν’ˆ λ‚΄ ν•¨λŸ‰(%)": amount_text,
1713
+ })
1714
+
1715
+ search_blocks.append(f"{inci_name} {korean_name} {amount_text}%")
1716
+
1717
+ search_text = f"""
1718
+ κ΅­κ°€/채널: {country}
1719
+ κ²€ν†  λŒ€μƒ μ„±λΆ„:
1720
+ {chr(10).join(search_blocks)}
1721
+ """
1722
+
1723
+ try:
1724
+ docs = db.similarity_search(search_text, k=RAG_TOP_K_BATCH)
1725
+ context = "\n".join([d.page_content for d in docs])
1726
+
1727
+ prompt = f"""
1728
+ λ„ˆλŠ” ν™”μž₯ν’ˆ μ „μ„±λΆ„ 규제 μŠ€ν¬λ¦¬λ‹ μ „λ¬Έκ°€μ•Ό.
1729
+ μ•„λž˜ μ—¬λŸ¬ ꡬ성성뢄을 λ°˜λ“œμ‹œ "{country}" κΈ°μ€€μœΌλ‘œλ§Œ κ²€ν† ν•΄.
1730
+
1731
+ [μ ˆλŒ€ κ·œμΉ™]
1732
+ - ν˜„μž¬ κ²€ν†  κ΅­κ°€λŠ” "{country}"이닀.
1733
+ - μ•„λž˜ 검색 원문은 "{country}" ν΄λ”μ—μ„œλ§Œ κ²€μƒ‰λœ κ·Όκ±°λ‹€.
1734
+ - μ™ΈλΆ€ 지식, ν•™μŠ΅ 지식, 일반 규제 지식을 μ‚¬μš©ν•˜μ§€ 마.
1735
+ - 검색 원문에 κ·Όκ±°κ°€ μ—†μœΌλ©΄ κ²°κ³ΌλŠ” μ •ν™•νžˆ "{NO_EVIDENCE_TEXT}"으둜 μž‘μ„±ν•΄.
1736
+
1737
+ [κ²€ν†  λŒ€μƒ JSON]
1738
+ {json.dumps(target_payload, ensure_ascii=False, indent=2)}
1739
+
1740
+ [κ²€μƒ‰λœ {country} 규제 원문]
1741
+ {context}
1742
+
1743
+ λ°˜λ“œμ‹œ JSON λ°°μ—΄λ§Œ 좜λ ₯ν•΄.
1744
+ λ§ˆν¬λ‹€μš΄, μ„€λͺ…λ¬Έ, μ½”λ“œλΈ”λ‘ 없이 순수 JSON만 좜λ ₯ν•΄.
1745
+
1746
+ 좜λ ₯ ν˜•μ‹:
1747
+ [
1748
+ {{
1749
+ "target_id": "μž…λ ₯ target_id κ·ΈλŒ€λ‘œ",
1750
+ "λŒ€ν‘œ INCI": "λŒ€ν‘œ INCI λ˜λŠ” -",
1751
+ "κ²°κ³Ό": "{NO_EVIDENCE_TEXT} λ˜λŠ” 규제 λ‚΄μš©",
1752
+ "ν‘œμ‹œλ¬Έκ΅¬": "Pass λ˜λŠ” λ°°ν•©ν•œλ„/라벨링/확인 ν•„μš” λ“± 짧은 문ꡬ",
1753
+ "λΉ„κ³ ": "-"
1754
+ }}
1755
+ ]
1756
+ """
1757
+
1758
+ response = llm.invoke(prompt).content
1759
+ parsed = json.loads(clean_json_text(response))
1760
+
1761
+ if isinstance(parsed, dict):
1762
+ parsed = [parsed]
1763
+
1764
+ parsed_by_id = {}
1765
+
1766
+ for obj in parsed:
1767
+ if not isinstance(obj, dict):
1768
+ continue
1769
+
1770
+ target_id = safe_str(obj.get("target_id", ""))
1771
+ if not target_id:
1772
+ continue
1773
+
1774
+ item_comp = None
1775
+ for item in batch:
1776
+ if item["target_id"] == target_id:
1777
+ item_comp = item["component"]
1778
+ break
1779
+
1780
+ parsed_by_id[target_id] = sanitize_country_result(
1781
+ obj,
1782
+ country_col=country_col,
1783
+ component=item_comp or {},
1784
+ )
1785
+
1786
+ for item in batch:
1787
+ target_id = item["target_id"]
1788
+ comp = item["component"]
1789
+
1790
+ if target_id in parsed_by_id:
1791
+ result = parsed_by_id[target_id]
1792
+ results[target_id] = result
1793
+ EVAL_CACHE[make_eval_cache_key(country, comp)] = result
1794
+ log_search_context(target_id, country, comp, result["κ²°κ³Ό"], "GPT_BATCH", context)
1795
+
1796
+ for item in batch:
1797
+ target_id = item["target_id"]
1798
+
1799
+ if target_id in results:
1800
+ continue
1801
+
1802
+ results[target_id] = evaluate_component_with_llm(
1803
+ country=country,
1804
+ material=item["material"],
1805
+ component=item["component"],
1806
+ llm=llm,
1807
+ target_id=target_id,
1808
+ )
1809
+
1810
+ except Exception as e:
1811
+ print(f"batch GPT νŒμ • μ‹€νŒ¨: {country} / {e}")
1812
+
1813
+ for item in batch:
1814
+ target_id = item["target_id"]
1815
+
1816
+ if target_id in results:
1817
+ continue
1818
+
1819
+ results[target_id] = evaluate_component_with_llm(
1820
+ country=country,
1821
+ material=item["material"],
1822
+ component=item["component"],
1823
+ llm=llm,
1824
+ target_id=target_id,
1825
+ )
1826
+
1827
+ return results
1828
+
1829
+
1830
+ # ============================================================
1831
+ # 9. 좜λ ₯ 데이터 ꡬ성
1832
+ # ============================================================
1833
+
1834
+ def make_formula_statement_rows(row_items, country_cols):
1835
+ rows = []
1836
+
1837
+ for item in row_items:
1838
+ material = item["material"]
1839
+ comp = item["component"]
1840
+ row_data = item["row_data"]
1841
+
1842
+ row = {
1843
+ "NO.": material.get("NO", ""),
1844
+ "ν•œκΈ€ ν‘œμ€€ν™” λͺ…μΉ­": comp.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""),
1845
+ "INGREDIENT NAME (INCI)": comp.get("INCI Name", ""),
1846
+ "FUNCTION": comp.get("FUNCTION", ""),
1847
+ "CAS.No": comp.get("CAS.No", ""),
1848
+ "SOURCE": comp.get("SOURCE", "ICID") or "ICID",
1849
+ "%(w/w)": comp.get("In formula(w/w %)", ""),
1850
+ }
1851
+
1852
+ for country_col in country_cols:
1853
+ raw_text = safe_str(row_data.get(country_col, ""))
1854
+ display_text = safe_str(row_data.get(country_col + "_display", ""))
1855
+
1856
+ if display_text:
1857
+ row[country_col] = display_text
1858
+ else:
1859
+ row[country_col] = normalize_formula_country_text(
1860
+ raw_text,
1861
+ country_col=country_col,
1862
+ inci_name=comp.get("INCI Name", ""),
1863
+ amount_text=comp.get("In formula(w/w %)", ""),
1864
+ )
1865
+
1866
+ rows.append(row)
1867
+
1868
+ total = 0.0
1869
+
1870
+ for row in rows:
1871
+ value = to_number(row.get("%(w/w)", ""))
1872
+ if value is not None:
1873
+ total += value
1874
+
1875
+ total_row = {
1876
+ "NO.": "",
1877
+ "ν•œκΈ€ ν‘œμ€€ν™” λͺ…μΉ­": "",
1878
+ "INGREDIENT NAME (INCI)": "TOTAL",
1879
+ "FUNCTION": "",
1880
+ "CAS.No": "",
1881
+ "SOURCE": "",
1882
+ "%(w/w)": format_amount(total),
1883
+ }
1884
+
1885
+ for country_col in country_cols:
1886
+ total_row[country_col] = ""
1887
+
1888
+ rows.append(total_row)
1889
+
1890
+ return pd.DataFrame(rows)
1891
+
1892
+
1893
+ def make_regulatory_summary_rows(row_items, country_cols):
1894
+ rows = []
1895
+
1896
+ for item in row_items:
1897
+ row_data = item["row_data"]
1898
+
1899
+ if not is_country_result_issue(row_data.get("Result", "")):
1900
+ continue
1901
+
1902
+ row = {
1903
+ "ν•œκΈ€ μ„±λΆ„λͺ…": row_data.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""),
1904
+ "INCI Name": row_data.get("INCI Name", ""),
1905
+ "In formula(w/w %)": row_data.get("In formula\n(w/w %)", ""),
1906
+ "Result": row_data.get("Result", ""),
1907
+ }
1908
+
1909
+ for country_col in country_cols:
1910
+ value = safe_str(row_data.get(country_col, ""))
1911
+ row[country_col] = value if is_country_result_issue(value) else "-"
1912
+
1913
+ row["λΉ„κ³ "] = row_data.get("λΉ„κ³ ", "-")
1914
+ rows.append(row)
1915
+
1916
+ columns = ["ν•œκΈ€ μ„±λΆ„λͺ…", "INCI Name", "In formula(w/w %)", "Result"] + country_cols + ["λΉ„κ³ "]
1917
+
1918
+ if not rows:
1919
+ return pd.DataFrame(columns=columns)
1920
+
1921
+ return pd.DataFrame(rows)[columns]
1922
+
1923
+
1924
+ def sum_formula_percent(formula_df):
1925
+ total = 0.0
1926
+
1927
+ if formula_df is None or formula_df.empty:
1928
+ return total
1929
+
1930
+ for value in formula_df.get("%(w/w)", []):
1931
+ num = to_number(value)
1932
+ if num is not None:
1933
+ total += num
1934
+
1935
+ return total
1936
+
1937
+
1938
+ # ============================================================
1939
+ # 10. μ—‘μ…€ μ €μž₯ / μŠ€νƒ€μΌ
1940
+ # ============================================================
1941
+
1942
+ def write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw_df):
1943
+ with pd.ExcelWriter(out_path, engine="openpyxl") as writer:
1944
+ formula_df.to_excel(writer, index=False, sheet_name="Formula Ingredients Statement", startrow=5)
1945
+ regulatory_df.to_excel(writer, index=False, sheet_name="Regulatory Screening Summary")
1946
+ raw_df.to_excel(writer, index=False, sheet_name="Evidence Log")
1947
+
1948
+ wb = load_workbook(out_path)
1949
+ ws = wb["Formula Ingredients Statement"]
1950
+ max_col = max(1, ws.max_column)
1951
+
1952
+ ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=max_col)
1953
+ ws["A1"] = "Formular Ingredients Statement"
1954
+ ws["A1"].font = Font(bold=True, size=24, underline="single")
1955
+ ws["A1"].alignment = Alignment(horizontal="center", vertical="center")
1956
+
1957
+ ws.merge_cells(start_row=4, start_column=1, end_row=4, end_column=max_col)
1958
+ ws["A4"] = f"PRODUCT NAME : {safe_str(product_name)}"
1959
+ ws["A4"].font = Font(bold=True, size=13)
1960
+ ws["A4"].alignment = Alignment(horizontal="left", vertical="center")
1961
+
1962
+ wb.save(out_path)
1963
+ style_output_workbook(out_path)
1964
+
1965
+
1966
+ def style_output_workbook(path):
1967
+ wb = load_workbook(path)
1968
+
1969
+ thin_border = Border(
1970
+ left=Side(style="thin", color="808080"),
1971
+ right=Side(style="thin", color="808080"),
1972
+ top=Side(style="thin", color="808080"),
1973
+ bottom=Side(style="thin", color="808080"),
1974
+ )
1975
+
1976
+ header_font = Font(color="000000", bold=True, size=10)
1977
+ body_font = Font(color="000000", size=10)
1978
+ title_font = Font(color="000000", bold=True, size=24, underline="single")
1979
+ product_font = Font(color="000000", bold=True, size=13)
1980
+
1981
+ warning_fill = PatternFill(start_color="FCE4D6", end_color="FCE4D6", fill_type="solid")
1982
+ pass_fill = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid")
1983
+
1984
+ for ws in wb.worksheets:
1985
+ if ws.title == "Formula Ingredients Statement":
1986
+ header_row = 6
1987
+ ws.sheet_view.showGridLines = False
1988
+
1989
+ ws.row_dimensions[1].height = 36
1990
+ ws.row_dimensions[2].height = 20
1991
+ ws.row_dimensions[3].height = 20
1992
+ ws.row_dimensions[4].height = 26
1993
+ ws.row_dimensions[5].height = 18
1994
+ ws.row_dimensions[6].height = 28
1995
+
1996
+ ws["A1"].font = title_font
1997
+ ws["A1"].alignment = Alignment(horizontal="center", vertical="center")
1998
+
1999
+ ws["A4"].font = product_font
2000
+ ws["A4"].alignment = Alignment(horizontal="left", vertical="center")
2001
+
2002
+ for row in range(header_row, ws.max_row + 1):
2003
+ for col in range(1, ws.max_column + 1):
2004
+ cell = ws.cell(row=row, column=col)
2005
+ cell.border = thin_border
2006
+ cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
2007
+ cell.font = body_font
2008
+
2009
+ if row == header_row:
2010
+ cell.font = header_font
2011
+
2012
+ if row > header_row:
2013
+ value = safe_str(cell.value)
2014
+
2015
+ if value and value != "Pass" and col >= 8:
2016
+ cell.fill = warning_fill
2017
+ elif value == "Pass":
2018
+ cell.fill = pass_fill
2019
+
2020
+ total_row = None
2021
+
2022
+ for row in range(header_row + 1, ws.max_row + 1):
2023
+ if safe_str(ws.cell(row=row, column=3).value).upper() == "TOTAL":
2024
+ total_row = row
2025
+ break
2026
+
2027
+ if total_row:
2028
+ for col in range(1, ws.max_column + 1):
2029
+ cell = ws.cell(row=total_row, column=col)
2030
+ cell.font = Font(bold=True)
2031
+ cell.border = thin_border
2032
+ cell.alignment = Alignment(horizontal="center", vertical="center")
2033
+
2034
+ try:
2035
+ ws.merge_cells(start_row=total_row, start_column=2, end_row=total_row, end_column=6)
2036
+ ws.cell(row=total_row, column=2).value = "TOTAL"
2037
+ ws.cell(row=total_row, column=2).font = Font(bold=True)
2038
+ ws.cell(row=total_row, column=2).alignment = Alignment(horizontal="center", vertical="center")
2039
+ ws.cell(row=total_row, column=3).value = None
2040
+ except Exception:
2041
+ pass
2042
+
2043
+ widths = {
2044
+ 1: 6,
2045
+ 2: 34,
2046
+ 3: 34,
2047
+ 4: 26,
2048
+ 5: 16,
2049
+ 6: 10,
2050
+ 7: 12,
2051
+ }
2052
+
2053
+ for col_idx in range(1, ws.max_column + 1):
2054
+ col_letter = get_column_letter(col_idx)
2055
+ ws.column_dimensions[col_letter].width = widths.get(col_idx, 15)
2056
+
2057
+ for row in range(header_row + 1, ws.max_row + 1):
2058
+ cell = ws.cell(row=row, column=7)
2059
+ if to_number(cell.value) is not None:
2060
+ cell.number_format = "0.000######"
2061
+
2062
+ ws.freeze_panes = "A7"
2063
+
2064
+ else:
2065
+ header_row = 1
2066
+ ws.sheet_view.showGridLines = False
2067
+
2068
+ for row in range(1, ws.max_row + 1):
2069
+ for col in range(1, ws.max_column + 1):
2070
+ cell = ws.cell(row=row, column=col)
2071
+ cell.border = thin_border
2072
+ cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
2073
+
2074
+ if row == header_row:
2075
+ cell.font = header_font
2076
+
2077
+ for col_idx in range(1, ws.max_column + 1):
2078
+ col_letter = get_column_letter(col_idx)
2079
+ header = safe_str(ws.cell(row=header_row, column=col_idx).value)
2080
+
2081
+ if header in ["검색 원문", "Evidence", "Evidence Text"]:
2082
+ ws.column_dimensions[col_letter].width = 70
2083
+ elif header in ["Result", "λΉ„κ³ "]:
2084
+ ws.column_dimensions[col_letter].width = 45
2085
+ elif header in ["INCI Name"]:
2086
+ ws.column_dimensions[col_letter].width = 32
2087
+ else:
2088
+ ws.column_dimensions[col_letter].width = 18
2089
+
2090
+ ws.freeze_panes = "A2"
2091
+
2092
+ wb.save(path)
2093
+
2094
+
2095
+ # ============================================================
2096
+ # 11. 메인 처리
2097
+ # ============================================================
2098
+
2099
+ def build_integrated_result(row_data, country_cols):
2100
+ issue_items = []
2101
+
2102
+ for country_col in country_cols:
2103
+ value = safe_str(row_data.get(country_col, ""))
2104
+ if is_country_result_issue(value):
2105
+ issue_items.append(country_col)
2106
+
2107
+ if not issue_items:
2108
+ return "PASS"
2109
+
2110
+ return "μž¬κ²€ν†  ν•„μš”: " + ", ".join(issue_items)
2111
+
2112
+
2113
+ def process(countries, file, product_name="", use_mfds_live=False, mfds_max_terms=30, mfds_headless=True):
2114
+ global RAW_SEARCH_LOGS
2115
+ RAW_SEARCH_LOGS = []
2116
+
2117
+ try:
2118
+ if not file:
2119
+ return None, None, "❌ μ—‘μ…€ νŒŒμΌμ„ μ—…λ‘œλ“œν•΄μ£Όμ„Έμš”."
2120
+
2121
+ if not countries:
2122
+ return None, None, "❌ μŠ€ν¬λ¦¬λ‹ κ΅­κ°€λ₯Ό μ„ νƒν•΄μ£Όμ„Έμš”."
2123
+
2124
+ df = pd.read_excel(file.name)
2125
+ grouped_materials, meta = make_grouped_materials(df)
2126
+
2127
+ if not grouped_materials:
2128
+ return None, None, "❌ μ—‘μ…€μ—μ„œ μ „μ„±λΆ„ 정보λ₯Ό 읽지 λͺ»ν–ˆμŠ΅λ‹ˆλ‹€. 컬럼λͺ…을 ν™•μΈν•΄μ£Όμ„Έμš”."
2129
+
2130
+ ingredient_totals = meta["ingredient_totals"]
2131
+ ingredient_amount_parts = meta["ingredient_amount_parts"]
2132
+
2133
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
2134
+
2135
+ row_items = []
2136
+
2137
+ for material in grouped_materials:
2138
+ comp = material["Components"][0]
2139
+ target_id = f"row_{len(row_items)}"
2140
+
2141
+ row_data = {
2142
+ "NO": material.get("NO", ""),
2143
+ "Trade name(κ΅­λ¬Έ)": material.get("Trade name(κ΅­λ¬Έ)", ""),
2144
+ "Trade name(영문)": material.get("Trade name(영문)", ""),
2145
+ "ν•œκΈ€ μ„±λΆ„λͺ…": comp.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""),
2146
+ "INCI Name": comp.get("INCI Name", ""),
2147
+ "In formula\n(w/w %)": comp.get("In formula(w/w %)", ""),
2148
+ "Result": "",
2149
+ }
2150
+
2151
+ row_items.append({
2152
+ "target_id": target_id,
2153
+ "material": material,
2154
+ "component": comp,
2155
+ "row_data": row_data,
2156
+ "notes": [],
2157
+ })
2158
+
2159
+ mfds_df = pd.DataFrame()
2160
+ mfds_live_msg = "μ‚¬μš© μ•ˆ 함"
2161
+
2162
+ if use_mfds_live:
2163
+ try:
2164
+ terms = extract_terms_for_mfds_live(row_items)
2165
+ mfds_df, mfds_live_msg = mfds_live_lookup_terms(
2166
+ terms=terms,
2167
+ max_terms=mfds_max_terms,
2168
+ headless=mfds_headless,
2169
+ )
2170
+ except Exception as e:
2171
+ mfds_df = pd.DataFrame()
2172
+ mfds_live_msg = f"MFDS μ‹€μ‹œκ°„ 쑰회 μ‹€νŒ¨: {e}"
2173
+
2174
+ for country in countries:
2175
+ col_name = display_country(country)
2176
+ gpt_targets = []
2177
+
2178
+ for item in row_items:
2179
+ local_result = evaluate_local_rules(
2180
+ country=country,
2181
+ material=item["material"],
2182
+ component=item["component"],
2183
+ ingredient_totals=ingredient_totals,
2184
+ ingredient_amount_parts=ingredient_amount_parts,
2185
+ )
2186
+
2187
+ if local_result is not None:
2188
+ item["row_data"][col_name] = local_result.get("κ²°κ³Ό", "")
2189
+ item["row_data"][col_name + "_display"] = local_result.get("ν‘œμ‹œλ¬Έκ΅¬", "Pass")
2190
+
2191
+ note = safe_str(local_result.get("λΉ„κ³ ", "-"))
2192
+ if note and note != "-":
2193
+ item["notes"].append(f"{col_name}: {note}")
2194
+
2195
+ log_search_context(
2196
+ item["target_id"],
2197
+ country,
2198
+ item["component"],
2199
+ local_result.get("κ²°κ³Ό", ""),
2200
+ "LOCAL_RULE",
2201
+ note if note and note != "-" else "둜컬 κ³ μ • κ·œμΉ™ μš°μ„  νŒμ •",
2202
+ )
2203
+ continue
2204
+
2205
+ mfds_result = None
2206
+
2207
+ if use_mfds_live and mfds_df is not None and not mfds_df.empty:
2208
+ mfds_result = evaluate_mfds_detail_rule(
2209
+ country=country,
2210
+ material=item["material"],
2211
+ component=item["component"],
2212
+ mfds_df=mfds_df,
2213
+ )
2214
+
2215
+ if mfds_result is not None:
2216
+ item["row_data"][col_name] = mfds_result.get("κ²°κ³Ό", "")
2217
+ item["row_data"][col_name + "_display"] = mfds_result.get("ν‘œμ‹œλ¬Έκ΅¬", "확인 ν•„μš”")
2218
+
2219
+ note = safe_str(mfds_result.get("λΉ„κ³ ", "-"))
2220
+ if note and note != "-":
2221
+ item["notes"].append(f"{col_name}: {note}")
2222
+
2223
+ log_search_context(
2224
+ item["target_id"],
2225
+ country,
2226
+ item["component"],
2227
+ mfds_result.get("κ²°κ³Ό", ""),
2228
+ "MFDS_LIVE",
2229
+ note,
2230
+ )
2231
+ continue
2232
+
2233
+ gpt_targets.append({
2234
+ "target_id": item["target_id"],
2235
+ "material": item["material"],
2236
+ "component": item["component"],
2237
+ })
2238
+
2239
+ batch_results = evaluate_components_with_llm_batch(
2240
+ country=country,
2241
+ targets=gpt_targets,
2242
+ llm=llm,
2243
+ )
2244
+
2245
+ for item in row_items:
2246
+ if col_name in item["row_data"]:
2247
+ continue
2248
+
2249
+ result = batch_results.get(item["target_id"])
2250
+
2251
+ if result is None:
2252
+ result = {
2253
+ "λŒ€ν‘œ INCI": safe_str(item["component"].get("INCI Name", "")) or "-",
2254
+ "κ²°κ³Ό": "확인 ν•„μš”",
2255
+ "ν‘œμ‹œλ¬Έκ΅¬": "확인 ν•„μš”",
2256
+ "λΉ„κ³ ": "batch κ²°κ³Ό λˆ„λ½",
2257
+ }
2258
+
2259
+ item["row_data"][col_name] = result.get("κ²°κ³Ό", "")
2260
+ item["row_data"][col_name + "_display"] = result.get("ν‘œμ‹œλ¬Έκ΅¬", "Pass")
2261
+
2262
+ note = safe_str(result.get("λΉ„κ³ ", "-"))
2263
+ if note and note != "-":
2264
+ item["notes"].append(f"{col_name}: {note}")
2265
+
2266
+ country_cols = [display_country(c) for c in countries]
2267
+
2268
+ for item in row_items:
2269
+ item["row_data"]["Result"] = build_integrated_result(item["row_data"], country_cols)
2270
+ item["row_data"]["λΉ„κ³ "] = " / ".join(item["notes"]) if item["notes"] else "-"
2271
+
2272
+ formula_df = make_formula_statement_rows(row_items, country_cols)
2273
+ regulatory_df = make_regulatory_summary_rows(row_items, country_cols)
2274
+
2275
+ raw_columns = ["target_id", "κ΅­κ°€/채널", "μ„±λΆ„λͺ…", "INCI Name", "νŒμ •", "좜처", "검색 원문"]
2276
+ raw_df = pd.DataFrame(RAW_SEARCH_LOGS)
2277
+
2278
+ if raw_df.empty:
2279
+ raw_df = pd.DataFrame(columns=raw_columns)
2280
+ else:
2281
+ for col in raw_columns:
2282
+ if col not in raw_df.columns:
2283
+ raw_df[col] = ""
2284
+ raw_df = raw_df[raw_columns]
2285
+
2286
+ formula_total = sum_formula_percent(formula_df)
2287
+
2288
+ safe_country_name = "_".join([
2289
+ re.sub(r"[^a-zA-Z0-9κ°€-힣_-]", "_", str(c))
2290
+ for c in countries
2291
+ ])
2292
+
2293
+ product_part = safe_filename(product_name) if safe_str(product_name) else "product"
2294
+ out_path = str(OUTPUT_DIR / f"screening_result_{product_part}_{safe_country_name}.xlsx")
2295
+
2296
+ write_output_workbook(
2297
+ out_path=out_path,
2298
+ product_name=product_name,
2299
+ formula_df=formula_df,
2300
+ regulatory_df=regulatory_df,
2301
+ raw_df=raw_df,
2302
+ )
2303
+
2304
+ msg = (
2305
+ "βœ… 뢄석 μ™„λ£Œ\n"
2306
+ f"- Product Name: {safe_str(product_name) or '-'}\n"
2307
+ f"- μ „μ„±λΆ„ ν–‰ 수: {len(formula_df)}개\n"
2308
+ f"- In formula 합계: {format_amount(formula_total)}%\n"
2309
+ f"- μž¬κ²€ν†  ν•„μš” μ„±λΆ„: {len(regulatory_df)}개\n"
2310
+ f"- MFDS μƒνƒœ: {mfds_live_msg}\n"
2311
+ "- κ²°κ³Ό 파일 μ‹œνŠΈ:\n"
2312
+ " 1) Formula Ingredients Statement\n"
2313
+ " 2) Regulatory Screening Summary\n"
2314
+ " 3) Evidence Log\n"
2315
+ )
2316
+
2317
+ return formula_df, out_path, msg
2318
+
2319
+ except Exception as e:
2320
+ tb = traceback.format_exc()
2321
+ print(tb)
2322
+ return None, None, f"❌ 였λ₯˜ λ°œμƒ: {str(e)}\n\n{tb[-3000:]}"
2323
+
2324
+
2325
+ # ============================================================
2326
+ # 12. Gradio UI
2327
+ # ============================================================
2328
+
2329
+ with gr.Blocks(css=custom_css) as demo:
2330
+ gr.Markdown("# 🌍 reBom Regulatory Screening AI")
2331
+ gr.Markdown("### ꡭ가별 규제 폴더 검색 + μ‹μ•½μ²˜ μ‹€μ‹œκ°„ 쑰회 + Formular Ingredients Statement 좜λ ₯")
2332
+
2333
+ with gr.Row():
2334
+ gr.Button(
2335
+ "πŸšͺ λ‘œκ·Έμ•„μ›ƒ",
2336
+ link="/logout?all_session=false",
2337
+ variant="secondary",
2338
+ )
2339
+
2340
+ with gr.Tab("πŸš€ μŠ€ν¬λ¦¬λ‹"):
2341
+ country = gr.CheckboxGroup(
2342
+ choices=get_country_folders(),
2343
+ value=[],
2344
+ label="🌍 κ΅­κ°€ / 채널 선택",
2345
+ elem_id="country_checks",
2346
+ )
2347
+
2348
+ refresh = gr.Button("πŸ”„ 폴더/규제파일 μƒˆλ‘œκ³ μΉ¨")
2349
+
2350
+ product_name = gr.Textbox(
2351
+ label="μ œν’ˆλͺ… / PRODUCT NAME",
2352
+ placeholder="예: Mania Holic Sunscreen Pack",
2353
+ )
2354
+
2355
+ file = gr.File(
2356
+ label="μ „μ„±λΆ„ μ—‘μ…€ μ—…λ‘œλ“œ",
2357
+ file_types=[".xlsx"],
2358
+ )
2359
+
2360
+ use_mfds_live = gr.Checkbox(
2361
+ label="μ‹μ•½μ²˜ μ‚¬μ΄νŠΈ μ‹€μ‹œκ°„ 쑰회 μ‚¬μš©",
2362
+ value=False,
2363
+ )
2364
+
2365
+ mfds_max_terms = gr.Number(
2366
+ label="μ‹μ•½μ²˜ μ‹€μ‹œκ°„ 쑰회 μ΅œλŒ€ 검색어 수",
2367
+ value=5,
2368
+ precision=0,
2369
+ )
2370
+
2371
+ mfds_headless = gr.Checkbox(
2372
+ label="μ‹μ•½μ²˜ 쑰회 λΈŒλΌμš°μ € μˆ¨κΉ€ λͺ¨λ“œ",
2373
+ value=True,
2374
+ )
2375
+
2376
+ btn = gr.Button("πŸš€ 뢄석 μ‹œμž‘", variant="primary")
2377
+
2378
+ df_out = gr.Dataframe(
2379
+ label="미리보기 - Formular Ingredients Statement",
2380
+ wrap=True,
2381
+ interactive=False,
2382
+ )
2383
+
2384
+ file_out = gr.File(label="κ²°κ³Ό λ‹€μš΄λ‘œλ“œ")
2385
+
2386
+ msg_out = gr.Textbox(
2387
+ label="μƒνƒœ / 였λ₯˜ λ©”μ‹œμ§€",
2388
+ interactive=False,
2389
+ lines=12,
2390
+ )
2391
+
2392
+ refresh.click(
2393
+ fn=refresh_country_choices_and_clear_cache,
2394
+ inputs=country,
2395
+ outputs=country,
2396
+ )
2397
+
2398
+ try:
2399
+ auto_refresh_timer = gr.Timer(15)
2400
+ auto_refresh_timer.tick(
2401
+ fn=refresh_country_choices_keep_selection,
2402
+ inputs=country,
2403
+ outputs=country,
2404
+ )
2405
+ except Exception as e:
2406
+ print(f"μžλ™ κ΅­κ°€ λͺ©λ‘ κ°±μ‹  타이머 λΉ„ν™œμ„±ν™”: {e}")
2407
+
2408
+ file.change(
2409
+ fn=preview_excel,
2410
+ inputs=file,
2411
+ outputs=df_out,
2412
+ )
2413
+
2414
+ btn.click(
2415
+ process,
2416
+ inputs=[
2417
+ country,
2418
+ file,
2419
+ product_name,
2420
+ use_mfds_live,
2421
+ mfds_max_terms,
2422
+ mfds_headless,
2423
+ ],
2424
+ outputs=[
2425
+ df_out,
2426
+ file_out,
2427
+ msg_out,
2428
+ ],
2429
+ )
2430
+
2431
+
2432
+ # ============================================================
2433
+ # 13. 둜그인 인증
2434
+ # ============================================================
2435
+
2436
+ USER_DB = {
2437
+ "jin2li@rebom.kr": "qwer0515!",
2438
+ "jkh@rebom.kr": "rebom123!",
2439
+ "member2": "1111",
2440
+ }
2441
+
2442
+
2443
+ def auth_fn(username, password):
2444
+ username = str(username).strip()
2445
+ password = str(password).strip()
2446
+ return username in USER_DB and USER_DB[username] == password
2447
+
2448
+
2449
+ # ============================================================
2450
+ # 14. μ•± μ‹€ν–‰
2451
+ # ============================================================
2452
+
2453
+ try:
2454
+ demo.launch(
2455
+ server_name="0.0.0.0",
2456
+ server_port=7860,
2457
+ share=True,
2458
+ ssr_mode=False,
2459
+ auth=auth_fn,
2460
+ allowed_paths=ALLOWED_PATHS,
2461
+ blocked_paths=BLOCKED_PATHS,
2462
+ show_api=False,
2463
+ footer_links=[],
2464
+ app_kwargs={
2465
+ "docs_url": None,
2466
+ "redoc_url": None,
2467
+ "openapi_url": None,
2468
+ },
2469
+ )
2470
+ except TypeError:
2471
+ demo.launch(
2472
+ server_name="0.0.0.0",
2473
+ server_port=7860,
2474
+ share=True,
2475
+ auth=auth_fn,
2476
+ allowed_paths=ALLOWED_PATHS,
2477
+ blocked_paths=BLOCKED_PATHS,
2478
+ )