Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -21,6 +21,7 @@
|
|
| 21 |
# - GPT는 검색된 원문 안에서만 판정
|
| 22 |
# - 식약처 사이트 실시간 조회 옵션
|
| 23 |
# - COOS 사이트 실시간 조회 옵션
|
|
|
|
| 24 |
# - Formular Ingredients Statement 원본 양식 출력
|
| 25 |
# - 원본 TOTAL 행 제거 후 새 TOTAL 행 1개만 생성
|
| 26 |
# ============================================================
|
|
@@ -30,6 +31,8 @@ import re
|
|
| 30 |
import json
|
| 31 |
import hashlib
|
| 32 |
import traceback
|
|
|
|
|
|
|
| 33 |
from pathlib import Path
|
| 34 |
from collections import defaultdict
|
| 35 |
|
|
@@ -296,42 +299,12 @@ FUNCTIONAL_KOREA_RULES = {
|
|
| 296 |
}
|
| 297 |
|
| 298 |
FRAGRANCE_ALLERGEN_RULES = {
|
| 299 |
-
"limonene": {
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
},
|
| 305 |
-
"linalool": {
|
| 306 |
-
"label": "Linalool",
|
| 307 |
-
"aliases": ["linalool", "리날룰"],
|
| 308 |
-
"leave_on": 0.001,
|
| 309 |
-
"wash_off": 0.01,
|
| 310 |
-
},
|
| 311 |
-
"citral": {
|
| 312 |
-
"label": "Citral",
|
| 313 |
-
"aliases": ["citral", "시트랄"],
|
| 314 |
-
"leave_on": 0.001,
|
| 315 |
-
"wash_off": 0.01,
|
| 316 |
-
},
|
| 317 |
-
"geraniol": {
|
| 318 |
-
"label": "Geraniol",
|
| 319 |
-
"aliases": ["geraniol", "제라니올"],
|
| 320 |
-
"leave_on": 0.001,
|
| 321 |
-
"wash_off": 0.01,
|
| 322 |
-
},
|
| 323 |
-
"eugenol": {
|
| 324 |
-
"label": "Eugenol",
|
| 325 |
-
"aliases": ["eugenol", "유제놀"],
|
| 326 |
-
"leave_on": 0.001,
|
| 327 |
-
"wash_off": 0.01,
|
| 328 |
-
},
|
| 329 |
-
"benzyl alcohol": {
|
| 330 |
-
"label": "Benzyl Alcohol",
|
| 331 |
-
"aliases": ["benzyl alcohol", "벤질알코올"],
|
| 332 |
-
"leave_on": 0.001,
|
| 333 |
-
"wash_off": 0.01,
|
| 334 |
-
},
|
| 335 |
}
|
| 336 |
|
| 337 |
|
|
@@ -527,18 +500,8 @@ def is_country_result_issue(text):
|
|
| 527 |
return False
|
| 528 |
|
| 529 |
keywords = [
|
| 530 |
-
"배합금지",
|
| 531 |
-
"
|
| 532 |
-
"초과",
|
| 533 |
-
"부적합",
|
| 534 |
-
"재검토",
|
| 535 |
-
"확인 필요",
|
| 536 |
-
"자료 확인",
|
| 537 |
-
"표시 필요",
|
| 538 |
-
"라벨링",
|
| 539 |
-
"불가",
|
| 540 |
-
"주의",
|
| 541 |
-
"경고",
|
| 542 |
]
|
| 543 |
|
| 544 |
return any(k in text for k in keywords)
|
|
@@ -628,10 +591,7 @@ def resolve_country_folder(country):
|
|
| 628 |
alias = COUNTRY_FOLDER_ALIASES.get(raw, COUNTRY_FOLDER_ALIASES.get(raw.upper(), raw))
|
| 629 |
|
| 630 |
candidates = [
|
| 631 |
-
raw,
|
| 632 |
-
alias,
|
| 633 |
-
raw.upper(),
|
| 634 |
-
alias.upper(),
|
| 635 |
raw.replace("_", " "),
|
| 636 |
raw.replace("-", " "),
|
| 637 |
raw.replace("EU FUTURE", "EU (FUTURE)"),
|
|
@@ -667,15 +627,8 @@ def resolve_country_folder(country):
|
|
| 667 |
|
| 668 |
def get_country_folders():
|
| 669 |
exclude = [
|
| 670 |
-
".git",
|
| 671 |
-
"
|
| 672 |
-
"__pycache__",
|
| 673 |
-
".ipynb_checkpoints",
|
| 674 |
-
".venv",
|
| 675 |
-
"venv",
|
| 676 |
-
"node_modules",
|
| 677 |
-
FAISS_CACHE_DIR,
|
| 678 |
-
"outputs",
|
| 679 |
]
|
| 680 |
|
| 681 |
folders = [
|
|
@@ -801,11 +754,7 @@ def build_database(country):
|
|
| 801 |
if not files:
|
| 802 |
return None
|
| 803 |
|
| 804 |
-
signature = tuple(
|
| 805 |
-
(f["relative_path"], f["size"], f["mtime_ns"])
|
| 806 |
-
for f in files
|
| 807 |
-
)
|
| 808 |
-
|
| 809 |
sig_hash = stable_hash(signature)
|
| 810 |
cached = VECTOR_DB_CACHE.get(folder)
|
| 811 |
|
|
@@ -815,10 +764,7 @@ def build_database(country):
|
|
| 815 |
embeddings = get_embeddings()
|
| 816 |
os.makedirs(FAISS_CACHE_DIR, exist_ok=True)
|
| 817 |
|
| 818 |
-
cache_path = os.path.join(
|
| 819 |
-
FAISS_CACHE_DIR,
|
| 820 |
-
f"{safe_filename(folder)}_{sig_hash[:16]}",
|
| 821 |
-
)
|
| 822 |
meta_path = os.path.join(cache_path, "metadata.json")
|
| 823 |
|
| 824 |
if os.path.isdir(cache_path) and os.path.exists(meta_path):
|
|
@@ -828,15 +774,8 @@ def build_database(country):
|
|
| 828 |
|
| 829 |
if meta.get("signature_hash") == sig_hash:
|
| 830 |
print(f"✅ FAISS 디스크 캐시 로드: {folder}")
|
| 831 |
-
db = FAISS.load_local(
|
| 832 |
-
|
| 833 |
-
embeddings,
|
| 834 |
-
allow_dangerous_deserialization=True,
|
| 835 |
-
)
|
| 836 |
-
VECTOR_DB_CACHE[folder] = {
|
| 837 |
-
"signature_hash": sig_hash,
|
| 838 |
-
"db": db,
|
| 839 |
-
}
|
| 840 |
return db
|
| 841 |
|
| 842 |
except Exception as e:
|
|
@@ -845,11 +784,7 @@ def build_database(country):
|
|
| 845 |
print(f"🔄 규제 DB 재색인: {folder} / 파일 {len(files)}개")
|
| 846 |
EVAL_CACHE.clear()
|
| 847 |
|
| 848 |
-
splitter = RecursiveCharacterTextSplitter(
|
| 849 |
-
chunk_size=900,
|
| 850 |
-
chunk_overlap=120,
|
| 851 |
-
)
|
| 852 |
-
|
| 853 |
chunks = []
|
| 854 |
|
| 855 |
for item in files:
|
|
@@ -888,11 +823,7 @@ def build_database(country):
|
|
| 888 |
except Exception as e:
|
| 889 |
print(f"FAISS 캐시 저장 실패: {folder} / {e}")
|
| 890 |
|
| 891 |
-
VECTOR_DB_CACHE[folder] = {
|
| 892 |
-
"signature_hash": sig_hash,
|
| 893 |
-
"db": db,
|
| 894 |
-
}
|
| 895 |
-
|
| 896 |
return db
|
| 897 |
|
| 898 |
|
|
@@ -931,7 +862,6 @@ def find_best_col(df, keywords, default_index=None, exclude_cols=None):
|
|
| 931 |
header = str(col).lower()
|
| 932 |
values = df[col].dropna().astype(str).str.strip()
|
| 933 |
sample = " ".join(values.head(80).tolist()).lower()
|
| 934 |
-
|
| 935 |
score = 0
|
| 936 |
|
| 937 |
for kw in keywords:
|
|
@@ -1263,6 +1193,29 @@ def make_grouped_materials(df):
|
|
| 1263 |
# 6. 실시간 조회 공통
|
| 1264 |
# ============================================================
|
| 1265 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1266 |
def extract_terms_for_live_lookup(row_items):
|
| 1267 |
terms = []
|
| 1268 |
|
|
@@ -1473,20 +1426,9 @@ def parse_live_text(term, text, source_name, source_url):
|
|
| 1473 |
has_reg_keyword = any(
|
| 1474 |
k in snippet_lower
|
| 1475 |
for k in [
|
| 1476 |
-
"금지",
|
| 1477 |
-
"
|
| 1478 |
-
"
|
| 1479 |
-
"제한",
|
| 1480 |
-
"한도",
|
| 1481 |
-
"배합한도",
|
| 1482 |
-
"최대",
|
| 1483 |
-
"max",
|
| 1484 |
-
"maximum",
|
| 1485 |
-
"limit",
|
| 1486 |
-
"restricted",
|
| 1487 |
-
"prohibited",
|
| 1488 |
-
"banned",
|
| 1489 |
-
"%",
|
| 1490 |
]
|
| 1491 |
)
|
| 1492 |
|
|
@@ -1527,10 +1469,10 @@ def live_lookup_terms(site_name, site_url, terms, max_terms=30, headless=True):
|
|
| 1527 |
terms = [safe_str(t) for t in terms if safe_str(t)]
|
| 1528 |
terms = terms[:int(max_terms)] if max_terms else terms[:30]
|
| 1529 |
|
| 1530 |
-
|
| 1531 |
-
|
|
|
|
| 1532 |
|
| 1533 |
-
try:
|
| 1534 |
with sync_playwright() as p:
|
| 1535 |
browser = p.chromium.launch(headless=bool(headless))
|
| 1536 |
context = browser.new_context(
|
|
@@ -1547,7 +1489,7 @@ def live_lookup_terms(site_name, site_url, terms, max_terms=30, headless=True):
|
|
| 1547 |
page.wait_for_timeout(2500)
|
| 1548 |
|
| 1549 |
if not live_fill_search_input(page, term):
|
| 1550 |
-
|
| 1551 |
continue
|
| 1552 |
|
| 1553 |
if not live_click_search(page):
|
|
@@ -1564,18 +1506,37 @@ def live_lookup_terms(site_name, site_url, terms, max_terms=30, headless=True):
|
|
| 1564 |
rows = parse_live_text(term, text, site_name, site_url)
|
| 1565 |
|
| 1566 |
if rows:
|
| 1567 |
-
|
| 1568 |
else:
|
| 1569 |
-
|
| 1570 |
|
| 1571 |
except Exception as e:
|
| 1572 |
-
|
| 1573 |
|
| 1574 |
context.close()
|
| 1575 |
browser.close()
|
| 1576 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1577 |
except Exception as e:
|
| 1578 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1579 |
|
| 1580 |
df = pd.DataFrame(all_rows)
|
| 1581 |
msg = f"{site_name} 실시간 조회 완료: 검색어 {len(terms)}개, 결과 {len(df)}행"
|
|
@@ -1590,23 +1551,11 @@ def live_lookup_terms(site_name, site_url, terms, max_terms=30, headless=True):
|
|
| 1590 |
|
| 1591 |
|
| 1592 |
def mfds_live_lookup_terms(terms, max_terms=30, headless=True):
|
| 1593 |
-
return live_lookup_terms(
|
| 1594 |
-
site_name="MFDS",
|
| 1595 |
-
site_url=MFDS_LIVE_URL,
|
| 1596 |
-
terms=terms,
|
| 1597 |
-
max_terms=max_terms,
|
| 1598 |
-
headless=headless,
|
| 1599 |
-
)
|
| 1600 |
|
| 1601 |
|
| 1602 |
def coos_live_lookup_terms(terms, max_terms=30, headless=True):
|
| 1603 |
-
return live_lookup_terms(
|
| 1604 |
-
site_name="COOS",
|
| 1605 |
-
site_url=COOS_LIVE_URL,
|
| 1606 |
-
terms=terms,
|
| 1607 |
-
max_terms=max_terms,
|
| 1608 |
-
headless=headless,
|
| 1609 |
-
)
|
| 1610 |
|
| 1611 |
|
| 1612 |
def ingredient_matches_live_row(material, component, row):
|
|
@@ -1642,7 +1591,6 @@ def live_row_country_matches(country, row_country):
|
|
| 1642 |
aliases += ["EU", "유럽", "유럽연합", "European Union", "Europe"]
|
| 1643 |
|
| 1644 |
aliases_norm = [normalize_compact(x) for x in aliases if safe_str(x)]
|
| 1645 |
-
|
| 1646 |
return any(alias and alias in row_country_norm for alias in aliases_norm)
|
| 1647 |
|
| 1648 |
|
|
@@ -1742,12 +1690,10 @@ def evaluate_local_rules(country, material, component, ingredient_totals, ingred
|
|
| 1742 |
amount = component.get("amount_float")
|
| 1743 |
|
| 1744 |
uv_result = evaluate_limit_rule(country, material, component, UV_FILTER_RULES, "UV 필터")
|
| 1745 |
-
|
| 1746 |
if uv_result is not None:
|
| 1747 |
return uv_result
|
| 1748 |
|
| 1749 |
preservative_result = evaluate_limit_rule(country, material, component, PRESERVATIVE_RULES, "보존제/제한성분")
|
| 1750 |
-
|
| 1751 |
if preservative_result is not None:
|
| 1752 |
return preservative_result
|
| 1753 |
|
|
@@ -1872,16 +1818,8 @@ def sanitize_country_result(parsed, country_col="", component=None):
|
|
| 1872 |
)
|
| 1873 |
|
| 1874 |
bad_tokens = [
|
| 1875 |
-
"규제명",
|
| 1876 |
-
"
|
| 1877 |
-
"규제 / 총량",
|
| 1878 |
-
"{규제군명}",
|
| 1879 |
-
"{성분명",
|
| 1880 |
-
"{함량}",
|
| 1881 |
-
"{기준치}",
|
| 1882 |
-
"placeholder",
|
| 1883 |
-
"N/A",
|
| 1884 |
-
"n/a",
|
| 1885 |
]
|
| 1886 |
|
| 1887 |
if any(token in result_text for token in bad_tokens):
|
|
@@ -1944,12 +1882,7 @@ def evaluate_component_with_llm(country, material, component, llm, target_id="")
|
|
| 1944 |
amount_text = format_percent(amount) if amount is not None else "함량 확인 필요"
|
| 1945 |
|
| 1946 |
if not inci_name and not korean_name:
|
| 1947 |
-
return {
|
| 1948 |
-
"대표 INCI": "-",
|
| 1949 |
-
"결과": "",
|
| 1950 |
-
"표시문구": "",
|
| 1951 |
-
"비고": "-",
|
| 1952 |
-
}
|
| 1953 |
|
| 1954 |
if not db:
|
| 1955 |
result = {
|
|
@@ -2038,10 +1971,8 @@ INCI/CAS: {inci_name}
|
|
| 2038 |
response = llm.invoke(prompt).content
|
| 2039 |
parsed = parse_country_response(response)
|
| 2040 |
parsed = sanitize_country_result(parsed, country_col=country_col, component=component)
|
| 2041 |
-
|
| 2042 |
EVAL_CACHE[cache_key] = parsed
|
| 2043 |
log_search_context(target_id, country, component, parsed["결과"], "GPT_SINGLE", context)
|
| 2044 |
-
|
| 2045 |
return parsed
|
| 2046 |
|
| 2047 |
except Exception as e:
|
|
@@ -2076,14 +2007,7 @@ def evaluate_components_with_llm_batch(country, targets, llm):
|
|
| 2076 |
"비고": "-",
|
| 2077 |
}
|
| 2078 |
|
| 2079 |
-
log_search_context(
|
| 2080 |
-
item["target_id"],
|
| 2081 |
-
country,
|
| 2082 |
-
comp,
|
| 2083 |
-
NO_EVIDENCE_TEXT,
|
| 2084 |
-
"NO_DB",
|
| 2085 |
-
"해당 국가/채널 규제 DB 없음",
|
| 2086 |
-
)
|
| 2087 |
|
| 2088 |
return results
|
| 2089 |
|
|
@@ -2136,14 +2060,7 @@ def evaluate_components_with_llm_batch(country, targets, llm):
|
|
| 2136 |
}
|
| 2137 |
results[item["target_id"]] = result
|
| 2138 |
EVAL_CACHE[make_eval_cache_key(country, comp)] = result
|
| 2139 |
-
log_search_context(
|
| 2140 |
-
item["target_id"],
|
| 2141 |
-
country,
|
| 2142 |
-
comp,
|
| 2143 |
-
result["결과"],
|
| 2144 |
-
"NO_MEANINGFUL_HIT",
|
| 2145 |
-
context,
|
| 2146 |
-
)
|
| 2147 |
|
| 2148 |
uncached_targets = filtered_targets
|
| 2149 |
|
|
@@ -2156,7 +2073,6 @@ def evaluate_components_with_llm_batch(country, targets, llm):
|
|
| 2156 |
|
| 2157 |
for item in batch:
|
| 2158 |
comp = item["component"]
|
| 2159 |
-
|
| 2160 |
inci_name = safe_str(comp.get("INCI Name", ""))
|
| 2161 |
korean_name = safe_str(comp.get("한글 성분명", ""))
|
| 2162 |
amount = comp.get("amount_float")
|
|
@@ -2230,17 +2146,12 @@ def evaluate_components_with_llm_batch(country, targets, llm):
|
|
| 2230 |
continue
|
| 2231 |
|
| 2232 |
item_comp = None
|
| 2233 |
-
|
| 2234 |
for item in batch:
|
| 2235 |
if item["target_id"] == target_id:
|
| 2236 |
item_comp = item["component"]
|
| 2237 |
break
|
| 2238 |
|
| 2239 |
-
parsed_by_id[target_id] = sanitize_country_result(
|
| 2240 |
-
obj,
|
| 2241 |
-
country_col=country_col,
|
| 2242 |
-
component=item_comp or {},
|
| 2243 |
-
)
|
| 2244 |
|
| 2245 |
for item in batch:
|
| 2246 |
target_id = item["target_id"]
|
|
@@ -2302,11 +2213,7 @@ def make_formula_statement_rows(row_items, country_cols):
|
|
| 2302 |
korean_name = safe_str(comp.get("한글 성분명", ""))
|
| 2303 |
inci_name = safe_str(comp.get("INCI Name", ""))
|
| 2304 |
|
| 2305 |
-
if (
|
| 2306 |
-
is_total_like_text(no_value)
|
| 2307 |
-
or is_total_like_text(korean_name)
|
| 2308 |
-
or is_total_like_text(inci_name)
|
| 2309 |
-
):
|
| 2310 |
continue
|
| 2311 |
|
| 2312 |
row = {
|
|
@@ -2403,11 +2310,7 @@ def sum_formula_percent(formula_df):
|
|
| 2403 |
korean_name = safe_str(row.get("한글 표준화 명칭", ""))
|
| 2404 |
inci_name = safe_str(row.get("INGREDIENT NAME (INCI)", ""))
|
| 2405 |
|
| 2406 |
-
if (
|
| 2407 |
-
is_total_like_text(no_value)
|
| 2408 |
-
or is_total_like_text(korean_name)
|
| 2409 |
-
or is_total_like_text(inci_name)
|
| 2410 |
-
):
|
| 2411 |
continue
|
| 2412 |
|
| 2413 |
num = to_number(row.get("%(w/w)", ""))
|
|
@@ -2523,15 +2426,7 @@ def style_output_workbook(path):
|
|
| 2523 |
except Exception:
|
| 2524 |
pass
|
| 2525 |
|
| 2526 |
-
widths = {
|
| 2527 |
-
1: 6,
|
| 2528 |
-
2: 34,
|
| 2529 |
-
3: 34,
|
| 2530 |
-
4: 26,
|
| 2531 |
-
5: 16,
|
| 2532 |
-
6: 10,
|
| 2533 |
-
7: 12,
|
| 2534 |
-
}
|
| 2535 |
|
| 2536 |
for col_idx in range(1, ws.max_column + 1):
|
| 2537 |
col_letter = get_column_letter(col_idx)
|
|
@@ -2726,14 +2621,7 @@ def process(
|
|
| 2726 |
if note and note != "-":
|
| 2727 |
item["notes"].append(f"{col_name}: {note}")
|
| 2728 |
|
| 2729 |
-
log_search_context(
|
| 2730 |
-
item["target_id"],
|
| 2731 |
-
country,
|
| 2732 |
-
item["component"],
|
| 2733 |
-
mfds_result.get("결과", ""),
|
| 2734 |
-
"MFDS_LIVE",
|
| 2735 |
-
note,
|
| 2736 |
-
)
|
| 2737 |
continue
|
| 2738 |
|
| 2739 |
coos_result = None
|
|
@@ -2754,14 +2642,7 @@ def process(
|
|
| 2754 |
if note and note != "-":
|
| 2755 |
item["notes"].append(f"{col_name}: {note}")
|
| 2756 |
|
| 2757 |
-
log_search_context(
|
| 2758 |
-
item["target_id"],
|
| 2759 |
-
country,
|
| 2760 |
-
item["component"],
|
| 2761 |
-
coos_result.get("결과", ""),
|
| 2762 |
-
"COOS_LIVE",
|
| 2763 |
-
note,
|
| 2764 |
-
)
|
| 2765 |
continue
|
| 2766 |
|
| 2767 |
gpt_targets.append({
|
|
@@ -2770,11 +2651,7 @@ def process(
|
|
| 2770 |
"component": item["component"],
|
| 2771 |
})
|
| 2772 |
|
| 2773 |
-
batch_results = evaluate_components_with_llm_batch(
|
| 2774 |
-
country=country,
|
| 2775 |
-
targets=gpt_targets,
|
| 2776 |
-
llm=llm,
|
| 2777 |
-
)
|
| 2778 |
|
| 2779 |
for item in row_items:
|
| 2780 |
if col_name in item["row_data"]:
|
|
@@ -2819,11 +2696,7 @@ def process(
|
|
| 2819 |
|
| 2820 |
formula_total = sum_formula_percent(formula_df)
|
| 2821 |
|
| 2822 |
-
safe_country_name = "_".join([
|
| 2823 |
-
re.sub(r"[^a-zA-Z0-9가-힣_-]", "_", str(c))
|
| 2824 |
-
for c in countries
|
| 2825 |
-
])
|
| 2826 |
-
|
| 2827 |
product_part = safe_filename(product_name) if safe_str(product_name) else "product"
|
| 2828 |
out_path = str(OUTPUT_DIR / f"screening_result_{product_part}_{safe_country_name}.xlsx")
|
| 2829 |
|
|
@@ -2866,11 +2739,7 @@ with gr.Blocks(css=custom_css) as demo:
|
|
| 2866 |
gr.Markdown("### 국가별 규제 폴더 검색 + 식약처/COOS 실시간 조회 + Formular Ingredients Statement 출력")
|
| 2867 |
|
| 2868 |
with gr.Row():
|
| 2869 |
-
gr.Button(
|
| 2870 |
-
"🚪 로그아웃",
|
| 2871 |
-
link="/logout?all_session=false",
|
| 2872 |
-
variant="secondary",
|
| 2873 |
-
)
|
| 2874 |
|
| 2875 |
with gr.Tab("🚀 스크리닝"):
|
| 2876 |
country = gr.CheckboxGroup(
|
|
@@ -3016,4 +2885,4 @@ except TypeError:
|
|
| 3016 |
auth=auth_fn,
|
| 3017 |
allowed_paths=ALLOWED_PATHS,
|
| 3018 |
blocked_paths=BLOCKED_PATHS,
|
| 3019 |
-
)
|
|
|
|
| 21 |
# - GPT는 검색된 원문 안에서만 판정
|
| 22 |
# - 식약처 사이트 실시간 조회 옵션
|
| 23 |
# - COOS 사이트 실시간 조회 옵션
|
| 24 |
+
# - Playwright Chromium 자동 설치 재시도
|
| 25 |
# - Formular Ingredients Statement 원본 양식 출력
|
| 26 |
# - 원본 TOTAL 행 제거 후 새 TOTAL 행 1개만 생성
|
| 27 |
# ============================================================
|
|
|
|
| 31 |
import json
|
| 32 |
import hashlib
|
| 33 |
import traceback
|
| 34 |
+
import sys
|
| 35 |
+
import subprocess
|
| 36 |
from pathlib import Path
|
| 37 |
from collections import defaultdict
|
| 38 |
|
|
|
|
| 299 |
}
|
| 300 |
|
| 301 |
FRAGRANCE_ALLERGEN_RULES = {
|
| 302 |
+
"limonene": {"label": "Limonene", "aliases": ["limonene", "리모넨"], "leave_on": 0.001, "wash_off": 0.01},
|
| 303 |
+
"linalool": {"label": "Linalool", "aliases": ["linalool", "리날룰"], "leave_on": 0.001, "wash_off": 0.01},
|
| 304 |
+
"citral": {"label": "Citral", "aliases": ["citral", "시트랄"], "leave_on": 0.001, "wash_off": 0.01},
|
| 305 |
+
"geraniol": {"label": "Geraniol", "aliases": ["geraniol", "제라니올"], "leave_on": 0.001, "wash_off": 0.01},
|
| 306 |
+
"eugenol": {"label": "Eugenol", "aliases": ["eugenol", "유제놀"], "leave_on": 0.001, "wash_off": 0.01},
|
| 307 |
+
"benzyl alcohol": {"label": "Benzyl Alcohol", "aliases": ["benzyl alcohol", "벤질알코올"], "leave_on": 0.001, "wash_off": 0.01},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
}
|
| 309 |
|
| 310 |
|
|
|
|
| 500 |
return False
|
| 501 |
|
| 502 |
keywords = [
|
| 503 |
+
"배합금지", "금지", "초과", "부적합", "재검토", "확인 필요",
|
| 504 |
+
"자료 확인", "표시 필요", "라벨링", "불가", "주의", "경고",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 505 |
]
|
| 506 |
|
| 507 |
return any(k in text for k in keywords)
|
|
|
|
| 591 |
alias = COUNTRY_FOLDER_ALIASES.get(raw, COUNTRY_FOLDER_ALIASES.get(raw.upper(), raw))
|
| 592 |
|
| 593 |
candidates = [
|
| 594 |
+
raw, alias, raw.upper(), alias.upper(),
|
|
|
|
|
|
|
|
|
|
| 595 |
raw.replace("_", " "),
|
| 596 |
raw.replace("-", " "),
|
| 597 |
raw.replace("EU FUTURE", "EU (FUTURE)"),
|
|
|
|
| 627 |
|
| 628 |
def get_country_folders():
|
| 629 |
exclude = [
|
| 630 |
+
".git", ".cache", "__pycache__", ".ipynb_checkpoints", ".venv",
|
| 631 |
+
"venv", "node_modules", FAISS_CACHE_DIR, "outputs",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 632 |
]
|
| 633 |
|
| 634 |
folders = [
|
|
|
|
| 754 |
if not files:
|
| 755 |
return None
|
| 756 |
|
| 757 |
+
signature = tuple((f["relative_path"], f["size"], f["mtime_ns"]) for f in files)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 758 |
sig_hash = stable_hash(signature)
|
| 759 |
cached = VECTOR_DB_CACHE.get(folder)
|
| 760 |
|
|
|
|
| 764 |
embeddings = get_embeddings()
|
| 765 |
os.makedirs(FAISS_CACHE_DIR, exist_ok=True)
|
| 766 |
|
| 767 |
+
cache_path = os.path.join(FAISS_CACHE_DIR, f"{safe_filename(folder)}_{sig_hash[:16]}")
|
|
|
|
|
|
|
|
|
|
| 768 |
meta_path = os.path.join(cache_path, "metadata.json")
|
| 769 |
|
| 770 |
if os.path.isdir(cache_path) and os.path.exists(meta_path):
|
|
|
|
| 774 |
|
| 775 |
if meta.get("signature_hash") == sig_hash:
|
| 776 |
print(f"✅ FAISS 디스크 캐시 로드: {folder}")
|
| 777 |
+
db = FAISS.load_local(cache_path, embeddings, allow_dangerous_deserialization=True)
|
| 778 |
+
VECTOR_DB_CACHE[folder] = {"signature_hash": sig_hash, "db": db}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 779 |
return db
|
| 780 |
|
| 781 |
except Exception as e:
|
|
|
|
| 784 |
print(f"🔄 규제 DB 재색인: {folder} / 파일 {len(files)}개")
|
| 785 |
EVAL_CACHE.clear()
|
| 786 |
|
| 787 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=900, chunk_overlap=120)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 788 |
chunks = []
|
| 789 |
|
| 790 |
for item in files:
|
|
|
|
| 823 |
except Exception as e:
|
| 824 |
print(f"FAISS 캐시 저장 실패: {folder} / {e}")
|
| 825 |
|
| 826 |
+
VECTOR_DB_CACHE[folder] = {"signature_hash": sig_hash, "db": db}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 827 |
return db
|
| 828 |
|
| 829 |
|
|
|
|
| 862 |
header = str(col).lower()
|
| 863 |
values = df[col].dropna().astype(str).str.strip()
|
| 864 |
sample = " ".join(values.head(80).tolist()).lower()
|
|
|
|
| 865 |
score = 0
|
| 866 |
|
| 867 |
for kw in keywords:
|
|
|
|
| 1193 |
# 6. 실시간 조회 공통
|
| 1194 |
# ============================================================
|
| 1195 |
|
| 1196 |
+
def install_playwright_chromium_once():
|
| 1197 |
+
try:
|
| 1198 |
+
print("🔧 Playwright Chromium 설치 시도 중...")
|
| 1199 |
+
result = subprocess.run(
|
| 1200 |
+
[sys.executable, "-m", "playwright", "install", "chromium"],
|
| 1201 |
+
capture_output=True,
|
| 1202 |
+
text=True,
|
| 1203 |
+
timeout=300,
|
| 1204 |
+
)
|
| 1205 |
+
|
| 1206 |
+
if result.returncode == 0:
|
| 1207 |
+
print("✅ Playwright Chromium 설치 완료")
|
| 1208 |
+
return True, "Chromium 설치 완료"
|
| 1209 |
+
|
| 1210 |
+
msg = (result.stdout or "") + "\n" + (result.stderr or "")
|
| 1211 |
+
print("❌ Playwright Chromium 설치 실패:", msg[-1000:])
|
| 1212 |
+
return False, msg[-1000:]
|
| 1213 |
+
|
| 1214 |
+
except Exception as e:
|
| 1215 |
+
print("❌ Playwright Chromium 설치 예외:", e)
|
| 1216 |
+
return False, str(e)
|
| 1217 |
+
|
| 1218 |
+
|
| 1219 |
def extract_terms_for_live_lookup(row_items):
|
| 1220 |
terms = []
|
| 1221 |
|
|
|
|
| 1426 |
has_reg_keyword = any(
|
| 1427 |
k in snippet_lower
|
| 1428 |
for k in [
|
| 1429 |
+
"금지", "사용금지", "배합금지", "제한", "한도", "배합한도",
|
| 1430 |
+
"최대", "max", "maximum", "limit", "restricted",
|
| 1431 |
+
"prohibited", "banned", "%",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1432 |
]
|
| 1433 |
)
|
| 1434 |
|
|
|
|
| 1469 |
terms = [safe_str(t) for t in terms if safe_str(t)]
|
| 1470 |
terms = terms[:int(max_terms)] if max_terms else terms[:30]
|
| 1471 |
|
| 1472 |
+
def run_browser_lookup():
|
| 1473 |
+
local_rows = []
|
| 1474 |
+
local_errors = []
|
| 1475 |
|
|
|
|
| 1476 |
with sync_playwright() as p:
|
| 1477 |
browser = p.chromium.launch(headless=bool(headless))
|
| 1478 |
context = browser.new_context(
|
|
|
|
| 1489 |
page.wait_for_timeout(2500)
|
| 1490 |
|
| 1491 |
if not live_fill_search_input(page, term):
|
| 1492 |
+
local_errors.append(f"{term}: 검색 입력창 찾기 실패")
|
| 1493 |
continue
|
| 1494 |
|
| 1495 |
if not live_click_search(page):
|
|
|
|
| 1506 |
rows = parse_live_text(term, text, site_name, site_url)
|
| 1507 |
|
| 1508 |
if rows:
|
| 1509 |
+
local_rows.extend(rows)
|
| 1510 |
else:
|
| 1511 |
+
local_errors.append(f"{term}: 국가별 배합한도/제한 정보 미검출")
|
| 1512 |
|
| 1513 |
except Exception as e:
|
| 1514 |
+
local_errors.append(f"{term}: {e}")
|
| 1515 |
|
| 1516 |
context.close()
|
| 1517 |
browser.close()
|
| 1518 |
|
| 1519 |
+
return local_rows, local_errors
|
| 1520 |
+
|
| 1521 |
+
try:
|
| 1522 |
+
all_rows, errors = run_browser_lookup()
|
| 1523 |
+
|
| 1524 |
except Exception as e:
|
| 1525 |
+
err_text = str(e)
|
| 1526 |
+
|
| 1527 |
+
if "Executable doesn't exist" in err_text or "playwright install" in err_text.lower():
|
| 1528 |
+
ok, install_msg = install_playwright_chromium_once()
|
| 1529 |
+
|
| 1530 |
+
if not ok:
|
| 1531 |
+
return pd.DataFrame(), f"{site_name} 브라우저 설치 실패: {install_msg}"
|
| 1532 |
+
|
| 1533 |
+
try:
|
| 1534 |
+
all_rows, errors = run_browser_lookup()
|
| 1535 |
+
except Exception as e2:
|
| 1536 |
+
return pd.DataFrame(), f"{site_name} 브라우저 실행 실패: {e2}"
|
| 1537 |
+
|
| 1538 |
+
else:
|
| 1539 |
+
return pd.DataFrame(), f"{site_name} 브라우저 실행 실패: {e}"
|
| 1540 |
|
| 1541 |
df = pd.DataFrame(all_rows)
|
| 1542 |
msg = f"{site_name} 실시간 조회 완료: 검색어 {len(terms)}개, 결과 {len(df)}행"
|
|
|
|
| 1551 |
|
| 1552 |
|
| 1553 |
def mfds_live_lookup_terms(terms, max_terms=30, headless=True):
|
| 1554 |
+
return live_lookup_terms("MFDS", MFDS_LIVE_URL, terms, max_terms, headless)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1555 |
|
| 1556 |
|
| 1557 |
def coos_live_lookup_terms(terms, max_terms=30, headless=True):
|
| 1558 |
+
return live_lookup_terms("COOS", COOS_LIVE_URL, terms, max_terms, headless)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1559 |
|
| 1560 |
|
| 1561 |
def ingredient_matches_live_row(material, component, row):
|
|
|
|
| 1591 |
aliases += ["EU", "유럽", "유럽연합", "European Union", "Europe"]
|
| 1592 |
|
| 1593 |
aliases_norm = [normalize_compact(x) for x in aliases if safe_str(x)]
|
|
|
|
| 1594 |
return any(alias and alias in row_country_norm for alias in aliases_norm)
|
| 1595 |
|
| 1596 |
|
|
|
|
| 1690 |
amount = component.get("amount_float")
|
| 1691 |
|
| 1692 |
uv_result = evaluate_limit_rule(country, material, component, UV_FILTER_RULES, "UV 필터")
|
|
|
|
| 1693 |
if uv_result is not None:
|
| 1694 |
return uv_result
|
| 1695 |
|
| 1696 |
preservative_result = evaluate_limit_rule(country, material, component, PRESERVATIVE_RULES, "보존제/제한성분")
|
|
|
|
| 1697 |
if preservative_result is not None:
|
| 1698 |
return preservative_result
|
| 1699 |
|
|
|
|
| 1818 |
)
|
| 1819 |
|
| 1820 |
bad_tokens = [
|
| 1821 |
+
"규제명", "총량 계산", "규제 / 총량", "{규제군명}",
|
| 1822 |
+
"{성분명", "{함량}", "{기준치}", "placeholder", "N/A", "n/a",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1823 |
]
|
| 1824 |
|
| 1825 |
if any(token in result_text for token in bad_tokens):
|
|
|
|
| 1882 |
amount_text = format_percent(amount) if amount is not None else "함량 확인 필요"
|
| 1883 |
|
| 1884 |
if not inci_name and not korean_name:
|
| 1885 |
+
return {"대표 INCI": "-", "결과": "", "표시문구": "", "비고": "-"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1886 |
|
| 1887 |
if not db:
|
| 1888 |
result = {
|
|
|
|
| 1971 |
response = llm.invoke(prompt).content
|
| 1972 |
parsed = parse_country_response(response)
|
| 1973 |
parsed = sanitize_country_result(parsed, country_col=country_col, component=component)
|
|
|
|
| 1974 |
EVAL_CACHE[cache_key] = parsed
|
| 1975 |
log_search_context(target_id, country, component, parsed["결과"], "GPT_SINGLE", context)
|
|
|
|
| 1976 |
return parsed
|
| 1977 |
|
| 1978 |
except Exception as e:
|
|
|
|
| 2007 |
"비고": "-",
|
| 2008 |
}
|
| 2009 |
|
| 2010 |
+
log_search_context(item["target_id"], country, comp, NO_EVIDENCE_TEXT, "NO_DB", "해당 국가/채널 규제 DB 없음")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2011 |
|
| 2012 |
return results
|
| 2013 |
|
|
|
|
| 2060 |
}
|
| 2061 |
results[item["target_id"]] = result
|
| 2062 |
EVAL_CACHE[make_eval_cache_key(country, comp)] = result
|
| 2063 |
+
log_search_context(item["target_id"], country, comp, result["결과"], "NO_MEANINGFUL_HIT", context)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2064 |
|
| 2065 |
uncached_targets = filtered_targets
|
| 2066 |
|
|
|
|
| 2073 |
|
| 2074 |
for item in batch:
|
| 2075 |
comp = item["component"]
|
|
|
|
| 2076 |
inci_name = safe_str(comp.get("INCI Name", ""))
|
| 2077 |
korean_name = safe_str(comp.get("한글 성분명", ""))
|
| 2078 |
amount = comp.get("amount_float")
|
|
|
|
| 2146 |
continue
|
| 2147 |
|
| 2148 |
item_comp = None
|
|
|
|
| 2149 |
for item in batch:
|
| 2150 |
if item["target_id"] == target_id:
|
| 2151 |
item_comp = item["component"]
|
| 2152 |
break
|
| 2153 |
|
| 2154 |
+
parsed_by_id[target_id] = sanitize_country_result(obj, country_col=country_col, component=item_comp or {})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2155 |
|
| 2156 |
for item in batch:
|
| 2157 |
target_id = item["target_id"]
|
|
|
|
| 2213 |
korean_name = safe_str(comp.get("한글 성분명", ""))
|
| 2214 |
inci_name = safe_str(comp.get("INCI Name", ""))
|
| 2215 |
|
| 2216 |
+
if is_total_like_text(no_value) or is_total_like_text(korean_name) or is_total_like_text(inci_name):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2217 |
continue
|
| 2218 |
|
| 2219 |
row = {
|
|
|
|
| 2310 |
korean_name = safe_str(row.get("한글 표준화 명칭", ""))
|
| 2311 |
inci_name = safe_str(row.get("INGREDIENT NAME (INCI)", ""))
|
| 2312 |
|
| 2313 |
+
if is_total_like_text(no_value) or is_total_like_text(korean_name) or is_total_like_text(inci_name):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2314 |
continue
|
| 2315 |
|
| 2316 |
num = to_number(row.get("%(w/w)", ""))
|
|
|
|
| 2426 |
except Exception:
|
| 2427 |
pass
|
| 2428 |
|
| 2429 |
+
widths = {1: 6, 2: 34, 3: 34, 4: 26, 5: 16, 6: 10, 7: 12}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2430 |
|
| 2431 |
for col_idx in range(1, ws.max_column + 1):
|
| 2432 |
col_letter = get_column_letter(col_idx)
|
|
|
|
| 2621 |
if note and note != "-":
|
| 2622 |
item["notes"].append(f"{col_name}: {note}")
|
| 2623 |
|
| 2624 |
+
log_search_context(item["target_id"], country, item["component"], mfds_result.get("결과", ""), "MFDS_LIVE", note)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2625 |
continue
|
| 2626 |
|
| 2627 |
coos_result = None
|
|
|
|
| 2642 |
if note and note != "-":
|
| 2643 |
item["notes"].append(f"{col_name}: {note}")
|
| 2644 |
|
| 2645 |
+
log_search_context(item["target_id"], country, item["component"], coos_result.get("결과", ""), "COOS_LIVE", note)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2646 |
continue
|
| 2647 |
|
| 2648 |
gpt_targets.append({
|
|
|
|
| 2651 |
"component": item["component"],
|
| 2652 |
})
|
| 2653 |
|
| 2654 |
+
batch_results = evaluate_components_with_llm_batch(country=country, targets=gpt_targets, llm=llm)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2655 |
|
| 2656 |
for item in row_items:
|
| 2657 |
if col_name in item["row_data"]:
|
|
|
|
| 2696 |
|
| 2697 |
formula_total = sum_formula_percent(formula_df)
|
| 2698 |
|
| 2699 |
+
safe_country_name = "_".join([re.sub(r"[^a-zA-Z0-9가-힣_-]", "_", str(c)) for c in countries])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2700 |
product_part = safe_filename(product_name) if safe_str(product_name) else "product"
|
| 2701 |
out_path = str(OUTPUT_DIR / f"screening_result_{product_part}_{safe_country_name}.xlsx")
|
| 2702 |
|
|
|
|
| 2739 |
gr.Markdown("### 국가별 규제 폴더 검색 + 식약처/COOS 실시간 조회 + Formular Ingredients Statement 출력")
|
| 2740 |
|
| 2741 |
with gr.Row():
|
| 2742 |
+
gr.Button("🚪 로그아웃", link="/logout?all_session=false", variant="secondary")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2743 |
|
| 2744 |
with gr.Tab("🚀 스크리닝"):
|
| 2745 |
country = gr.CheckboxGroup(
|
|
|
|
| 2885 |
auth=auth_fn,
|
| 2886 |
allowed_paths=ALLOWED_PATHS,
|
| 2887 |
blocked_paths=BLOCKED_PATHS,
|
| 2888 |
+
)
|