jin2li commited on
Commit
7dcff31
Β·
verified Β·
1 Parent(s): c1994a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +476 -159
app.py CHANGED
@@ -2,16 +2,16 @@
2
  # reBom Regulatory Screening AI
3
  # - κ΅­κ°€/채널 폴더 μžλ™ 인식
4
  # - 규제 파일 μžλ™ λ³€κ²½ 감지
5
- # - FAISS 벑터 DB λ””μŠ€ν¬ μΊμ‹œ
6
- # - ν–₯료 μ•Œλ ˆλ₯΄κ²/κΈ°λŠ₯μ„±/μ •μœ λ₯˜/κ³ λΆ„μž 둜컬 κ·œμΉ™ μš°μ„  νŒμ •
7
- # - ꡭ가별 batch GPT νŒμ •μœΌλ‘œ 속도 κ°œμ„ 
8
  # - ꡭ가별 λ¬Έμ„œ 격리 κ²€μƒ‰μœΌλ‘œ 타ꡭ κ·œμ • ν™•μ‚° λ°©μ§€
 
 
 
9
  # - Formula Ingredients Statement κ°„μ†Œν™” 좜λ ₯
10
  # - 문제 μ„±λΆ„λ§Œ Regulatory Screening Summary 좜λ ₯
11
  # - Raw Search Log 별도 μ €μž₯
12
- # - κ²°κ³Ό μ—‘μ…€ 병합/μŠ€νƒ€μΌ 적용
13
- # - Gradio 둜그인 인증 적용
14
- # - ν˜„μž¬ λΈŒλΌμš°μ € μ„Έμ…˜ λ‘œκ·Έμ•„μ›ƒ λ²„νŠΌ 적용
15
  # ============================================================
16
 
17
  import os
@@ -41,13 +41,18 @@ from langchain_text_splitters import RecursiveCharacterTextSplitter
41
  api_key = os.getenv("OPENAI_API_KEY")
42
  print("βœ… OPENAI_API_KEY 정상" if api_key else "❌ OPENAI_API_KEY μ—†μŒ")
43
 
 
 
 
 
 
 
 
44
  VECTOR_DB_CACHE = {}
45
  EVAL_CACHE = {}
46
  EMBEDDINGS_CACHE = None
47
  RAW_SEARCH_LOGS = []
48
 
49
- FAISS_CACHE_DIR = ".faiss_cache"
50
-
51
  SUPPORTED_REG_FILE_EXTENSIONS = {
52
  ".pdf",
53
  ".txt",
@@ -56,11 +61,6 @@ SUPPORTED_REG_FILE_EXTENSIONS = {
56
  ".xls",
57
  }
58
 
59
- BASE_DIR = Path.cwd().resolve()
60
-
61
- OUTPUT_DIR = (BASE_DIR / "outputs").resolve()
62
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
63
-
64
  COUNTRY_ORDER = [
65
  "ASEAN",
66
  "CALIFORNIA",
@@ -99,7 +99,7 @@ COUNTRY_DISPLAY = {
99
  "EUROPE": "EU",
100
  "유럽": "EU",
101
 
102
- "FDA": "FDA",
103
  "USA": "λ―Έκ΅­",
104
  "US": "λ―Έκ΅­",
105
  "λ―Έκ΅­": "λ―Έκ΅­",
@@ -195,6 +195,7 @@ BLOCKED_PATHS = [
195
 
196
  ALLOWED_PATHS = [
197
  str(OUTPUT_DIR),
 
198
  ]
199
 
200
  BATCH_SIZE = 25
@@ -223,7 +224,7 @@ custom_css = """
223
 
224
 
225
  # ============================================================
226
- # 1. 둜컬 κ·œμΉ™ 데이터
227
  # ============================================================
228
 
229
  UV_FILTER_RULES = {
@@ -339,41 +340,6 @@ FRAGRANCE_ALLERGEN_RULES = {
339
  "wash_off": 0.01,
340
  "extra": "-",
341
  },
342
- "alpha-terpinene": {
343
- "label": "Alpha-Terpinene",
344
- "aliases": ["alpha-terpinene", "alpha terpinene", "Ξ±-terpinene", "Ξ± terpinene", "μ•ŒνŒŒ-터피넨"],
345
- "leave_on": 0.001,
346
- "wash_off": 0.01,
347
- "extra": "peroxide value <10 mmol/L 확인 ν•„μš”",
348
- },
349
- "terpinolene": {
350
- "label": "Terpinolene",
351
- "aliases": ["terpinolene", "ν„°ν”Όλ†€λ Œ"],
352
- "leave_on": 0.001,
353
- "wash_off": 0.01,
354
- "extra": "peroxide value <10 mmol/L 확인 ν•„μš”",
355
- },
356
- "pinene": {
357
- "label": "Pinene",
358
- "aliases": ["pinene", "alpha-pinene", "beta-pinene", "Ξ±-pinene", "Ξ²-pinene", "피넨"],
359
- "leave_on": 0.001,
360
- "wash_off": 0.01,
361
- "extra": "peroxide value <10 mmol/L 확인 ν•„μš”",
362
- },
363
- "terpineol": {
364
- "label": "Terpineol",
365
- "aliases": ["terpineol", "alpha-terpineol", "Ξ±-terpineol", "ν„°ν”Όλ„€μ˜¬"],
366
- "leave_on": 0.001,
367
- "wash_off": 0.01,
368
- "extra": "-",
369
- },
370
- "beta-caryophyllene": {
371
- "label": "Beta-Caryophyllene",
372
- "aliases": ["beta-caryophyllene", "Ξ²-caryophyllene", "caryophyllene", "베타-μΉ΄λ¦¬μ˜€ν•„λ Œ"],
373
- "leave_on": 0.001,
374
- "wash_off": 0.01,
375
- "extra": "-",
376
- },
377
  "geraniol": {
378
  "label": "Geraniol",
379
  "aliases": ["geraniol", "μ œλΌλ‹ˆμ˜¬"],
@@ -415,6 +381,17 @@ def safe_str(x):
415
  return str(x).strip()
416
 
417
 
 
 
 
 
 
 
 
 
 
 
 
418
  def display_country(country):
419
  return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), str(country)))
420
 
@@ -454,11 +431,27 @@ def country_key(country):
454
  return text
455
 
456
 
457
- def normalize_text(text):
458
- text = safe_str(text).lower()
459
- text = text.replace("Ξ±", "alpha").replace("Ξ²", "beta")
460
- text = re.sub(r"[^a-z0-9κ°€-힣]+", " ", text)
461
- return re.sub(r"\s+", " ", text).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462
 
463
 
464
  def to_number(value):
@@ -532,19 +525,6 @@ def get_embeddings():
532
  return EMBEDDINGS_CACHE
533
 
534
 
535
- def sum_output_column(output_rows, column_name):
536
- total = 0.0
537
-
538
- for row in output_rows:
539
- value = row.get(column_name, "")
540
- number = to_number(value)
541
-
542
- if number is not None:
543
- total += number
544
-
545
- return total
546
-
547
-
548
  def amount_status(amount, threshold, action_text):
549
  threshold_text = format_percent(threshold)
550
 
@@ -655,7 +635,6 @@ def compact_result_reason(text, max_len=18):
655
 
656
  text = text.replace("확인 ν•„μš” / 규제 μ„ΈλΆ€ 계산 μž¬ν™•μΈ ν•„μš”", "확인 ν•„μš”")
657
  text = text.replace("κΈ°λŠ₯μ„±ν™”μž₯ν’ˆ κ²€ν† ", "κΈ°λŠ₯μ„± κ²€ν† ")
658
- text = text.replace("Sunscreen active ingredients", "μ„ μŠ€ν¬λ¦°")
659
  text = text.replace("Leave-on", "LO")
660
  text = text.replace("Wash-off", "WO")
661
 
@@ -684,8 +663,253 @@ def build_integrated_result(row_data, selected_country_display_names):
684
  return "μž¬κ²€ν†  ν•„μš”: " + ", ".join(issue_items)
685
 
686
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
687
  # ============================================================
688
- # 3. κ΅­κ°€ 폴더 μžλ™ 인식
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
689
  # ============================================================
690
 
691
  def resolve_country_folder(country):
@@ -780,7 +1004,7 @@ def refresh_country_choices_and_clear_cache(current_values=None):
780
 
781
 
782
  # ============================================================
783
- # 4. μ—‘μ…€ 미리보기 / 컬럼 인식
784
  # ============================================================
785
 
786
  def preview_excel(file):
@@ -828,6 +1052,7 @@ def find_best_col(df, keywords, default_index=None, exclude_cols=None):
828
  "acid",
829
  "ceramide",
830
  "glycol",
 
831
  ]
832
 
833
  if any(x in sample for x in markers):
@@ -866,6 +1091,7 @@ def find_numeric_col(df, keywords, default_index=None, exclude_cols=None, prefer
866
  continue
867
 
868
  score = 0
 
869
  for kw in keywords:
870
  if kw.lower() in header:
871
  score += 30
@@ -940,6 +1166,7 @@ def find_main_columns(df):
940
 
941
  if contents_col == formula_col:
942
  numeric_cols = []
 
943
  for col in df.columns:
944
  if col in [no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col]:
945
  continue
@@ -968,7 +1195,7 @@ def find_main_columns(df):
968
 
969
 
970
  # ============================================================
971
- # 5. μž…λ ₯ μ—‘μ…€ 정리 / κ·Έλ£Ήν™”
972
  # ============================================================
973
 
974
  def clean_input_df(df, cols):
@@ -1141,7 +1368,7 @@ def make_grouped_materials(df):
1141
 
1142
 
1143
  # ============================================================
1144
- # 6. 규제 λ¬Έμ„œ DB
1145
  # ============================================================
1146
 
1147
  def get_regulatory_file_list(country_folder):
@@ -1399,7 +1626,7 @@ def build_database(country_folder):
1399
 
1400
 
1401
  # ============================================================
1402
- # 7. 둜컬 κ·œμΉ™ νŒμ •
1403
  # ============================================================
1404
 
1405
  def evaluate_limit_rule(country, material, component, rule_group, rule_type_name):
@@ -1572,7 +1799,7 @@ def evaluate_local_rules(country, material, component, ingredient_totals, ingred
1572
 
1573
 
1574
  # ============================================================
1575
- # 8. GPT 보쑰 νŒμ •
1576
  # ============================================================
1577
 
1578
  def parse_country_response(text):
@@ -1662,18 +1889,6 @@ def make_eval_cache_key(country, component):
1662
  )
1663
 
1664
 
1665
- def log_search_context(target_id, country, component, result_text, source, context):
1666
- RAW_SEARCH_LOGS.append({
1667
- "target_id": target_id,
1668
- "κ΅­κ°€/채널": display_country(country),
1669
- "μ„±λΆ„λͺ…": safe_str(component.get("ν•œκΈ€ μ„±λΆ„λͺ…", "")),
1670
- "INCI Name": safe_str(component.get("INCI Name", "")),
1671
- "νŒμ •": safe_str(result_text),
1672
- "좜처": safe_str(source),
1673
- "검색 원문": safe_str(context)[:3000],
1674
- })
1675
-
1676
-
1677
  def evaluate_component_with_llm(country, material, component, llm, target_id=""):
1678
  db = build_database(country)
1679
 
@@ -1791,12 +2006,22 @@ def evaluate_components_with_llm_batch(country, targets, llm):
1791
  for item in targets:
1792
  comp = item["component"]
1793
  inci_name = safe_str(comp.get("INCI Name", ""))
 
1794
  results[item["target_id"]] = {
1795
  "λŒ€ν‘œ INCI": inci_name or "-",
1796
  "κ²°κ³Ό": "μ œν•œ μ—†μŒ (톡과)",
1797
  "λΉ„κ³ ": "-",
1798
  }
1799
- log_search_context(item["target_id"], country, comp, "μ œν•œ μ—†μŒ (톡과)", "NO_DB", "ν•΄λ‹Ή κ΅­κ°€/채널 규제 DB μ—†μŒ")
 
 
 
 
 
 
 
 
 
1800
  return results
1801
 
1802
  uncached_targets = []
@@ -1962,7 +2187,7 @@ def evaluate_components_with_llm_batch(country, targets, llm):
1962
 
1963
 
1964
  # ============================================================
1965
- # 9. 좜λ ₯ 데이터 ꡬ성
1966
  # ============================================================
1967
 
1968
  def make_formula_statement_rows(row_items):
@@ -2003,6 +2228,7 @@ def make_regulatory_summary_rows(row_items, country_cols):
2003
 
2004
  for country_col in country_cols:
2005
  value = safe_str(row_data.get(country_col, ""))
 
2006
  if is_country_result_issue(value):
2007
  row[country_col] = value
2008
  else:
@@ -2020,7 +2246,7 @@ def make_regulatory_summary_rows(row_items, country_cols):
2020
 
2021
 
2022
  # ============================================================
2023
- # 10. μ—‘μ…€ μ €μž₯ / μŠ€νƒ€μΌ
2024
  # ============================================================
2025
 
2026
  def write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw_df):
@@ -2035,6 +2261,7 @@ def write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw
2035
  ws["A1"] = f"PRODUCT NAME : {safe_str(product_name)}"
2036
  ws["A1"].font = Font(bold=True, size=13)
2037
  ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=max(1, ws.max_column))
 
2038
 
2039
  style_output_workbook(out_path)
2040
 
@@ -2118,10 +2345,10 @@ def style_output_workbook(path):
2118
 
2119
 
2120
  # ============================================================
2121
- # 11. 메인 처리
2122
  # ============================================================
2123
 
2124
- def process(countries, file, product_name=""):
2125
  global RAW_SEARCH_LOGS
2126
  RAW_SEARCH_LOGS = []
2127
 
@@ -2141,6 +2368,8 @@ def process(countries, file, product_name=""):
2141
  ingredient_totals = meta["ingredient_totals"]
2142
  ingredient_amount_parts = meta["ingredient_amount_parts"]
2143
 
 
 
2144
  llm = ChatOpenAI(
2145
  model="gpt-4o-mini",
2146
  temperature=0,
@@ -2202,13 +2431,40 @@ def process(countries, file, product_name=""):
2202
  source="LOCAL_RULE",
2203
  context=note if note and note != "-" else "둜컬 κ³ μ • κ·œμΉ™ μš°μ„  νŒμ •",
2204
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2205
 
2206
- else:
2207
- gpt_targets.append({
2208
- "target_id": item["target_id"],
2209
- "material": item["material"],
2210
- "component": item["component"],
2211
- })
2212
 
2213
  batch_results = evaluate_components_with_llm_batch(
2214
  country=country,
@@ -2261,10 +2517,7 @@ def process(countries, file, product_name=""):
2261
  raw_df[col] = ""
2262
  raw_df = raw_df[raw_columns]
2263
 
2264
- formula_total = sum_output_column(
2265
- [{"In formula\n(w/w %)": x.get("%(w/w)", "")} for x in formula_df.to_dict(orient="records")],
2266
- "In formula\n(w/w %)",
2267
- )
2268
 
2269
  safe_country_name = "_".join([
2270
  re.sub(r"[^a-zA-Z0-9κ°€-힣_-]", "_", str(c))
@@ -2283,6 +2536,7 @@ def process(countries, file, product_name=""):
2283
  )
2284
 
2285
  issue_count = len(regulatory_df)
 
2286
 
2287
  msg = (
2288
  "βœ… 뢄석 μ™„λ£Œ\n"
@@ -2290,12 +2544,15 @@ def process(countries, file, product_name=""):
2290
  f"- μ „μ„±λΆ„ ν–‰ 수: {len(formula_df)}개\n"
2291
  f"- In formula 합계: {format_amount(formula_total)}%\n"
2292
  f"- μž¬κ²€ν†  ν•„μš” μ„±λΆ„: {issue_count}개\n"
 
2293
  "- κ²°κ³Ό νŒŒμΌμ€ 3개 μ‹œνŠΈλ‘œ μ €μž₯ν–ˆμŠ΅λ‹ˆλ‹€.\n"
2294
- " 1) Formula Ingredients Statement: 사진 양식에 맞좘 κ°„μ†Œν™” μ „μ„±λΆ„ν‘œ\n"
2295
  " 2) Regulatory Screening Summary: 문제 μžˆλŠ” μ„±λΆ„λ§Œ ꡭ가별 μš”μ•½\n"
2296
- " 3) Raw Search Log: 둜컬 κ·œμΉ™/GPT 검색 κ·Όκ±° 둜그\n"
2297
- "- ꡭ가별 FAISS DBλ₯Ό λΆ„λ¦¬ν•΄μ„œ κ²€μƒ‰ν•˜λ―€λ‘œ EU κ²°κ³Όκ°€ ν•œκ΅­/일본/미ꡭ으둜 μžλ™ ν™•μ‚°λ˜μ§€ μ•Šλ„λ‘ μˆ˜μ •ν–ˆμŠ΅λ‹ˆλ‹€.\n"
2298
- "- GPT ν”„λ‘¬ν”„νŠΈμ—λ„ ν˜„μž¬ 선택 κ΅­κ°€ μ™Έ κ·œμ •μ„ μž„μ˜ μ μš©ν•˜μ§€ λ§λΌλŠ” 쑰건을 μΆ”κ°€ν–ˆμŠ΅λ‹ˆλ‹€."
 
 
2299
  )
2300
 
2301
  return formula_df, out_path, msg
@@ -2307,12 +2564,12 @@ def process(countries, file, product_name=""):
2307
 
2308
 
2309
  # ============================================================
2310
- # 12. Gradio UI
2311
  # ============================================================
2312
 
2313
  with gr.Blocks(css=custom_css) as demo:
2314
  gr.Markdown("# 🌍 reBom Regulatory Screening AI")
2315
- gr.Markdown("### κΈ€λ‘œλ²Œ ν™”μž₯ν’ˆ 규제 기반 μ „μ„±λΆ„ μŠ€ν¬λ¦¬λ‹")
2316
 
2317
  with gr.Row():
2318
  gr.Button(
@@ -2321,73 +2578,131 @@ with gr.Blocks(css=custom_css) as demo:
2321
  variant="secondary",
2322
  )
2323
 
2324
- country = gr.CheckboxGroup(
2325
- choices=get_country_folders(),
2326
- value=[],
2327
- label="🌍 κ΅­κ°€ / 채널 선택",
2328
- elem_id="country_checks",
2329
- )
2330
-
2331
- refresh = gr.Button("πŸ”„ 폴더/규제파일 μƒˆλ‘œκ³ μΉ¨")
2332
 
2333
- product_name = gr.Textbox(
2334
- label="μ œν’ˆλͺ… / PRODUCT NAME",
2335
- placeholder="예: Mania Holic Sunscreen Pack",
2336
- )
2337
 
2338
- file = gr.File(
2339
- label="μ—‘μ…€ μ—…λ‘œλ“œ",
2340
- file_types=[".xlsx"],
2341
- )
2342
 
2343
- btn = gr.Button("πŸš€ 뢄석 μ‹œμž‘", variant="primary")
 
 
 
2344
 
2345
- df_out = gr.Dataframe(
2346
- label="미리보기 - Formula Ingredients Statement",
2347
- wrap=True,
2348
- interactive=False,
2349
- )
2350
 
2351
- file_out = gr.File(label="κ²°κ³Ό λ‹€μš΄λ‘œλ“œ")
2352
 
2353
- msg_out = gr.Textbox(
2354
- label="μƒνƒœ / 였λ₯˜ λ©”μ‹œμ§€",
2355
- interactive=False,
2356
- lines=12,
2357
- )
2358
 
2359
- refresh.click(
2360
- fn=refresh_country_choices_and_clear_cache,
2361
- inputs=country,
2362
- outputs=country,
2363
- )
2364
 
2365
- try:
2366
- auto_refresh_timer = gr.Timer(15)
 
 
 
2367
 
2368
- auto_refresh_timer.tick(
2369
- fn=refresh_country_choices_keep_selection,
2370
  inputs=country,
2371
  outputs=country,
2372
  )
2373
- except Exception as e:
2374
- print(f"μžλ™ κ΅­κ°€ λͺ©λ‘ κ°±μ‹  타이머 λΉ„ν™œμ„±ν™”: {e}")
2375
 
2376
- file.change(
2377
- fn=preview_excel,
2378
- inputs=file,
2379
- outputs=df_out,
2380
- )
2381
 
2382
- btn.click(
2383
- process,
2384
- inputs=[country, file, product_name],
2385
- outputs=[df_out, file_out, msg_out],
2386
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2387
 
2388
 
2389
  # ============================================================
2390
- # 13. 둜그인 인증
2391
  # ============================================================
2392
 
2393
  USER_DB = {
@@ -2408,13 +2723,14 @@ def auth_fn(username, password):
2408
 
2409
 
2410
  # ============================================================
2411
- # 14. μ•± μ‹€ν–‰
2412
  # ============================================================
2413
 
2414
  try:
2415
  demo.launch(
2416
  server_name="0.0.0.0",
2417
  server_port=7860,
 
2418
  ssr_mode=False,
2419
  auth=auth_fn,
2420
  allowed_paths=ALLOWED_PATHS,
@@ -2431,6 +2747,7 @@ except TypeError:
2431
  demo.launch(
2432
  server_name="0.0.0.0",
2433
  server_port=7860,
 
2434
  auth=auth_fn,
2435
  allowed_paths=ALLOWED_PATHS,
2436
  blocked_paths=BLOCKED_PATHS,
 
2
  # reBom Regulatory Screening AI
3
  # - κ΅­κ°€/채널 폴더 μžλ™ 인식
4
  # - 규제 파일 μžλ™ λ³€κ²½ 감지
5
+ # - ꡭ가별 FAISS 벑터 DB λ””μŠ€ν¬ μΊμ‹œ
 
 
6
  # - ꡭ가별 λ¬Έμ„œ 격리 κ²€μƒ‰μœΌλ‘œ 타ꡭ κ·œμ • ν™•μ‚° λ°©μ§€
7
+ # - 둜컬 κ·œμΉ™ μš°μ„  νŒμ •
8
+ # - MFDS μ˜μ•½ν’ˆμ•ˆμ „λ‚˜λΌ 상세 DB μ—‘μ…€ 연동
9
+ # - ꡭ가별 batch GPT νŒμ •
10
  # - Formula Ingredients Statement κ°„μ†Œν™” 좜λ ₯
11
  # - 문제 μ„±λΆ„λ§Œ Regulatory Screening Summary 좜λ ₯
12
  # - Raw Search Log 별도 μ €μž₯
13
+ # - Gradio 둜그인 인증
14
+ # - Gradio public share link 적용
 
15
  # ============================================================
16
 
17
  import os
 
41
  api_key = os.getenv("OPENAI_API_KEY")
42
  print("βœ… OPENAI_API_KEY 정상" if api_key else "❌ OPENAI_API_KEY μ—†μŒ")
43
 
44
+ BASE_DIR = Path.cwd().resolve()
45
+ OUTPUT_DIR = (BASE_DIR / "outputs").resolve()
46
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
47
+
48
+ FAISS_CACHE_DIR = ".faiss_cache"
49
+ MFDS_DETAIL_DB_PATH = BASE_DIR / "MFDS_ꡭ가별_κΈˆμ§€μ œν•œ_상세.xlsx"
50
+
51
  VECTOR_DB_CACHE = {}
52
  EVAL_CACHE = {}
53
  EMBEDDINGS_CACHE = None
54
  RAW_SEARCH_LOGS = []
55
 
 
 
56
  SUPPORTED_REG_FILE_EXTENSIONS = {
57
  ".pdf",
58
  ".txt",
 
61
  ".xls",
62
  }
63
 
 
 
 
 
 
64
  COUNTRY_ORDER = [
65
  "ASEAN",
66
  "CALIFORNIA",
 
99
  "EUROPE": "EU",
100
  "유럽": "EU",
101
 
102
+ "FDA": "λ―Έκ΅­",
103
  "USA": "λ―Έκ΅­",
104
  "US": "λ―Έκ΅­",
105
  "λ―Έκ΅­": "λ―Έκ΅­",
 
195
 
196
  ALLOWED_PATHS = [
197
  str(OUTPUT_DIR),
198
+ str(BASE_DIR),
199
  ]
200
 
201
  BATCH_SIZE = 25
 
224
 
225
 
226
  # ============================================================
227
+ # 1. 둜컬 κ³ μ • κ·œμΉ™
228
  # ============================================================
229
 
230
  UV_FILTER_RULES = {
 
340
  "wash_off": 0.01,
341
  "extra": "-",
342
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
  "geraniol": {
344
  "label": "Geraniol",
345
  "aliases": ["geraniol", "μ œλΌλ‹ˆμ˜¬"],
 
381
  return str(x).strip()
382
 
383
 
384
+ def normalize_text(text):
385
+ text = safe_str(text).lower()
386
+ text = text.replace("Ξ±", "alpha").replace("Ξ²", "beta")
387
+ text = re.sub(r"[^a-z0-9κ°€-힣]+", " ", text)
388
+ return re.sub(r"\s+", " ", text).strip()
389
+
390
+
391
+ def normalize_compact(text):
392
+ return re.sub(r"\s+", "", normalize_text(text))
393
+
394
+
395
  def display_country(country):
396
  return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), str(country)))
397
 
 
431
  return text
432
 
433
 
434
+ def mfds_country_aliases(country):
435
+ ckey = country_key(country)
436
+
437
+ alias_map = {
438
+ "EU": ["EU", "유럽", "μœ λŸ½μ—°ν•©", "European Union", "Europe"],
439
+ "EU_FUTURE": ["EU", "유럽", "μœ λŸ½μ—°ν•©", "European Union", "Europe", "EU FUTURE"],
440
+ "KOREA": ["ν•œκ΅­", "λŒ€ν•œλ―Όκ΅­", "KOREA", "KR"],
441
+ "JAPAN": ["일본", "JAPAN", "JP"],
442
+ "CHINA": ["쀑ꡭ", "CHINA", "CN"],
443
+ "FDA": ["λ―Έκ΅­", "USA", "US", "FDA", "United States"],
444
+ "ASEAN": ["ASEAN", "μ•„μ„Έμ•ˆ"],
445
+ "UK": ["UK", "영ꡭ", "United Kingdom"],
446
+ "CALIFORNIA": ["California", "μΊ˜λ¦¬ν¬λ‹ˆμ•„", "CA"],
447
+ "MEXICO": ["Mexico", "λ©•μ‹œμ½”", "MX"],
448
+ "SEPHORA": ["SEPHORA"],
449
+ "TARGET": ["TARGET"],
450
+ "ULTA": ["ULTA"],
451
+ }
452
+
453
+ aliases = alias_map.get(ckey, [display_country(country), ckey, country])
454
+ return [normalize_compact(x) for x in aliases if safe_str(x)]
455
 
456
 
457
  def to_number(value):
 
525
  return EMBEDDINGS_CACHE
526
 
527
 
 
 
 
 
 
 
 
 
 
 
 
 
 
528
  def amount_status(amount, threshold, action_text):
529
  threshold_text = format_percent(threshold)
530
 
 
635
 
636
  text = text.replace("확인 ν•„μš” / 규제 μ„ΈλΆ€ 계산 μž¬ν™•μΈ ν•„μš”", "확인 ν•„μš”")
637
  text = text.replace("κΈ°λŠ₯μ„±ν™”μž₯ν’ˆ κ²€ν† ", "κΈ°λŠ₯μ„± κ²€ν† ")
 
638
  text = text.replace("Leave-on", "LO")
639
  text = text.replace("Wash-off", "WO")
640
 
 
663
  return "μž¬κ²€ν†  ν•„μš”: " + ", ".join(issue_items)
664
 
665
 
666
+ def log_search_context(target_id, country, component, result_text, source, context):
667
+ RAW_SEARCH_LOGS.append({
668
+ "target_id": target_id,
669
+ "κ΅­κ°€/채널": display_country(country),
670
+ "μ„±λΆ„λͺ…": safe_str(component.get("ν•œκΈ€ μ„±λΆ„λͺ…", "")),
671
+ "INCI Name": safe_str(component.get("INCI Name", "")),
672
+ "νŒμ •": safe_str(result_text),
673
+ "좜처": safe_str(source),
674
+ "검색 원문": safe_str(context)[:3000],
675
+ })
676
+
677
+
678
+ def sum_formula_percent(formula_df):
679
+ total = 0.0
680
+
681
+ if formula_df is None or formula_df.empty:
682
+ return total
683
+
684
+ for value in formula_df.get("%(w/w)", []):
685
+ num = to_number(value)
686
+ if num is not None:
687
+ total += num
688
+
689
+ return total
690
+
691
+
692
  # ============================================================
693
+ # 3. MFDS 상세 DB μ—‘μ…€ 연동
694
+ # ============================================================
695
+
696
+ def load_mfds_detail_db():
697
+ columns = [
698
+ "μ›λ£Œλͺ…",
699
+ "INCI",
700
+ "CAS.No",
701
+ "ꡬ뢄",
702
+ "κ΅­κ°€",
703
+ "κ·œμ œλ‚΄μš©",
704
+ "ν•œλ„",
705
+ "쑰건",
706
+ "좜처",
707
+ "상세원문",
708
+ ]
709
+
710
+ if not MFDS_DETAIL_DB_PATH.exists():
711
+ return pd.DataFrame(columns=columns)
712
+
713
+ try:
714
+ df = pd.read_excel(MFDS_DETAIL_DB_PATH, dtype=str).fillna("")
715
+ for col in columns:
716
+ if col not in df.columns:
717
+ df[col] = ""
718
+ return df[columns]
719
+ except Exception as e:
720
+ print(f"MFDS 상세 DB λ‘œλ”© μ‹€νŒ¨: {e}")
721
+ return pd.DataFrame(columns=columns)
722
+
723
+
724
+ def save_mfds_detail_db(df):
725
+ columns = [
726
+ "μ›λ£Œλͺ…",
727
+ "INCI",
728
+ "CAS.No",
729
+ "ꡬ뢄",
730
+ "κ΅­κ°€",
731
+ "κ·œμ œλ‚΄μš©",
732
+ "ν•œλ„",
733
+ "쑰건",
734
+ "좜처",
735
+ "상세원문",
736
+ ]
737
+
738
+ if df is None or df.empty:
739
+ df = pd.DataFrame(columns=columns)
740
+
741
+ for col in columns:
742
+ if col not in df.columns:
743
+ df[col] = ""
744
+
745
+ df = df[columns].fillna("").drop_duplicates()
746
+ df.to_excel(MFDS_DETAIL_DB_PATH, index=False)
747
+ return str(MFDS_DETAIL_DB_PATH)
748
+
749
+
750
+ def create_empty_mfds_template():
751
+ columns = [
752
+ "μ›λ£Œλͺ…",
753
+ "INCI",
754
+ "CAS.No",
755
+ "ꡬ뢄",
756
+ "κ΅­κ°€",
757
+ "κ·œμ œλ‚΄μš©",
758
+ "ν•œλ„",
759
+ "쑰건",
760
+ "좜처",
761
+ "상세원문",
762
+ ]
763
+
764
+ template = pd.DataFrame([
765
+ {
766
+ "μ›λ£Œλͺ…": "Retinol",
767
+ "INCI": "Retinol",
768
+ "CAS.No": "68-26-8",
769
+ "ꡬ뢄": "μ œν•œ",
770
+ "κ΅­κ°€": "EU",
771
+ "κ·œμ œλ‚΄μš©": "μ œν’ˆμœ ν˜•λ³„ λ°°ν•©ν•œλ„ 적용",
772
+ "ν•œλ„": "0.05% / 0.3%",
773
+ "쑰건": "μ œν’ˆμœ ν˜• 확인",
774
+ "좜처": "MFDS 상세화면",
775
+ "상세원문": "μ‹μ•½μ²˜ μƒμ„Έν™”λ©΄μ—μ„œ λ³΅μ‚¬ν•œ 원문 μž…λ ₯",
776
+ }
777
+ ], columns=columns)
778
+
779
+ out_path = str(OUTPUT_DIR / "MFDS_ꡭ가별_κΈˆμ§€μ œν•œ_상세_ν…œν”Œλ¦Ώ.xlsx")
780
+ template.to_excel(out_path, index=False)
781
+ return out_path
782
+
783
+
784
+ def ingredient_matches_mfds_row(material, component, row):
785
+ identity_values = [
786
+ component.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""),
787
+ component.get("INCI Name", ""),
788
+ material.get("Trade name(κ΅­λ¬Έ)", ""),
789
+ material.get("Trade name(영문)", ""),
790
+ ]
791
+
792
+ identity = normalize_compact(" ".join([safe_str(x) for x in identity_values if safe_str(x)]))
793
+
794
+ row_terms = [
795
+ row.get("μ›λ£Œλͺ…", ""),
796
+ row.get("INCI", ""),
797
+ row.get("CAS.No", ""),
798
+ ]
799
+
800
+ for term in row_terms:
801
+ term_norm = normalize_compact(term)
802
+ if term_norm and len(term_norm) >= 3 and term_norm in identity:
803
+ return True
804
+
805
+ return False
806
+
807
+
808
+ def mfds_row_country_matches(country, row_country):
809
+ row_country_norm = normalize_compact(row_country)
810
+ if not row_country_norm:
811
+ return False
812
+
813
+ aliases = mfds_country_aliases(country)
814
+ return any(alias and alias in row_country_norm for alias in aliases)
815
+
816
+
817
+ def evaluate_mfds_detail_rule(country, material, component, mfds_df):
818
+ if mfds_df is None or mfds_df.empty:
819
+ return None
820
+
821
+ hits = []
822
+
823
+ for _, row in mfds_df.iterrows():
824
+ if not ingredient_matches_mfds_row(material, component, row):
825
+ continue
826
+
827
+ if not mfds_row_country_matches(country, row.get("κ΅­κ°€", "")):
828
+ continue
829
+
830
+ hits.append(row)
831
+
832
+ if not hits:
833
+ return None
834
+
835
+ priority = {
836
+ "κΈˆμ§€": 1,
837
+ "λ°°ν•©κΈˆμ§€": 1,
838
+ "μ‚¬μš©κΈˆμ§€": 1,
839
+ "μ œν•œ": 2,
840
+ "ν•œλ„": 2,
841
+ "ν‘œμ‹œ": 3,
842
+ "확인 ν•„μš”": 4,
843
+ }
844
+
845
+ hits = sorted(
846
+ hits,
847
+ key=lambda r: priority.get(safe_str(r.get("ꡬ뢄", "")), 9),
848
+ )
849
+
850
+ row = hits[0]
851
+
852
+ category = safe_str(row.get("ꡬ뢄", "")) or "μ œν•œ"
853
+ regulation = safe_str(row.get("κ·œμ œλ‚΄μš©", ""))
854
+ limit = safe_str(row.get("ν•œλ„", ""))
855
+ condition = safe_str(row.get("쑰건", ""))
856
+ source = safe_str(row.get("좜처", "MFDS 상세정보"))
857
+
858
+ parts = [category]
859
+
860
+ if limit:
861
+ parts.append(f"ν•œλ„ {limit}")
862
+
863
+ if regulation:
864
+ parts.append(regulation[:300])
865
+
866
+ if condition:
867
+ parts.append(condition)
868
+
869
+ result_text = " / ".join([p for p in parts if p])
870
+
871
+ if not result_text:
872
+ result_text = "MFDS ꡭ가별 κΈˆμ§€/μ œν•œ 상세정보 확인 ν•„μš”"
873
+
874
+ return {
875
+ "λŒ€ν‘œ INCI": safe_str(component.get("INCI Name", "")) or safe_str(row.get("μ›λ£Œλͺ…", "")) or "-",
876
+ "κ²°κ³Ό": f"MFDS ꡭ가별 참고정보 / {result_text}",
877
+ "λΉ„κ³ ": source,
878
+ }
879
+
880
+
881
+ def upload_mfds_db(file):
882
+ if not file:
883
+ return None, "❌ MFDS 상세 DB μ—‘μ…€ νŒŒμΌμ„ μ—…λ‘œλ“œν•΄μ£Όμ„Έμš”."
884
+
885
+ try:
886
+ df = pd.read_excel(file.name, dtype=str).fillna("")
887
+ out_path = save_mfds_detail_db(df)
888
+ loaded = load_mfds_detail_db()
889
+
890
+ return out_path, (
891
+ "βœ… MFDS 상세 DB μ €μž₯ μ™„λ£Œ\n"
892
+ f"- μ €μž₯ μœ„μΉ˜: {out_path}\n"
893
+ f"- ν–‰ 수: {len(loaded)}개\n"
894
+ "- 이후 μŠ€ν¬λ¦¬λ‹ νƒ­μ—μ„œ 'MFDS 상세 DB μš°μ„  반영'을 μ²΄ν¬ν•˜λ©΄ μ μš©λ©λ‹ˆλ‹€."
895
+ )
896
+
897
+ except Exception as e:
898
+ tb = traceback.format_exc()
899
+ print(tb)
900
+ return None, f"❌ MFDS 상세 DB μ €μž₯ μ‹€νŒ¨: {e}"
901
+
902
+
903
+ def download_mfds_template():
904
+ try:
905
+ out_path = create_empty_mfds_template()
906
+ return out_path, "βœ… MFDS 상세 DB ν…œν”Œλ¦Ώ 생성 μ™„λ£Œ"
907
+ except Exception as e:
908
+ return None, f"❌ ν…œν”Œλ¦Ώ 생성 μ‹€νŒ¨: {e}"
909
+
910
+
911
+ # ============================================================
912
+ # 4. κ΅­κ°€ 폴더 μžλ™ 인식
913
  # ============================================================
914
 
915
  def resolve_country_folder(country):
 
1004
 
1005
 
1006
  # ============================================================
1007
+ # 5. μž…λ ₯ μ—‘μ…€ 미리보기 / 컬럼 인식
1008
  # ============================================================
1009
 
1010
  def preview_excel(file):
 
1052
  "acid",
1053
  "ceramide",
1054
  "glycol",
1055
+ "retinol",
1056
  ]
1057
 
1058
  if any(x in sample for x in markers):
 
1091
  continue
1092
 
1093
  score = 0
1094
+
1095
  for kw in keywords:
1096
  if kw.lower() in header:
1097
  score += 30
 
1166
 
1167
  if contents_col == formula_col:
1168
  numeric_cols = []
1169
+
1170
  for col in df.columns:
1171
  if col in [no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col]:
1172
  continue
 
1195
 
1196
 
1197
  # ============================================================
1198
+ # 6. μž…λ ₯ μ—‘μ…€ 정리 / κ·Έλ£Ήν™”
1199
  # ============================================================
1200
 
1201
  def clean_input_df(df, cols):
 
1368
 
1369
 
1370
  # ============================================================
1371
+ # 7. 규제 λ¬Έμ„œ FAISS DB
1372
  # ============================================================
1373
 
1374
  def get_regulatory_file_list(country_folder):
 
1626
 
1627
 
1628
  # ============================================================
1629
+ # 8. 둜컬 κ·œμΉ™ νŒμ •
1630
  # ============================================================
1631
 
1632
  def evaluate_limit_rule(country, material, component, rule_group, rule_type_name):
 
1799
 
1800
 
1801
  # ============================================================
1802
+ # 9. GPT 보쑰 νŒμ •
1803
  # ============================================================
1804
 
1805
  def parse_country_response(text):
 
1889
  )
1890
 
1891
 
 
 
 
 
 
 
 
 
 
 
 
 
1892
  def evaluate_component_with_llm(country, material, component, llm, target_id=""):
1893
  db = build_database(country)
1894
 
 
2006
  for item in targets:
2007
  comp = item["component"]
2008
  inci_name = safe_str(comp.get("INCI Name", ""))
2009
+
2010
  results[item["target_id"]] = {
2011
  "λŒ€ν‘œ INCI": inci_name or "-",
2012
  "κ²°κ³Ό": "μ œν•œ μ—†μŒ (톡과)",
2013
  "λΉ„κ³ ": "-",
2014
  }
2015
+
2016
+ log_search_context(
2017
+ item["target_id"],
2018
+ country,
2019
+ comp,
2020
+ "μ œν•œ μ—†μŒ (톡과)",
2021
+ "NO_DB",
2022
+ "ν•΄λ‹Ή κ΅­κ°€/채널 규제 DB μ—†μŒ",
2023
+ )
2024
+
2025
  return results
2026
 
2027
  uncached_targets = []
 
2187
 
2188
 
2189
  # ============================================================
2190
+ # 10. 좜λ ₯ 데이터 ꡬ성
2191
  # ============================================================
2192
 
2193
  def make_formula_statement_rows(row_items):
 
2228
 
2229
  for country_col in country_cols:
2230
  value = safe_str(row_data.get(country_col, ""))
2231
+
2232
  if is_country_result_issue(value):
2233
  row[country_col] = value
2234
  else:
 
2246
 
2247
 
2248
  # ============================================================
2249
+ # 11. μ—‘μ…€ μ €μž₯ / μŠ€νƒ€μΌ
2250
  # ============================================================
2251
 
2252
  def write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw_df):
 
2261
  ws["A1"] = f"PRODUCT NAME : {safe_str(product_name)}"
2262
  ws["A1"].font = Font(bold=True, size=13)
2263
  ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=max(1, ws.max_column))
2264
+ wb.save(out_path)
2265
 
2266
  style_output_workbook(out_path)
2267
 
 
2345
 
2346
 
2347
  # ============================================================
2348
+ # 12. 메인 처리
2349
  # ============================================================
2350
 
2351
+ def process(countries, file, product_name="", use_mfds_db=True):
2352
  global RAW_SEARCH_LOGS
2353
  RAW_SEARCH_LOGS = []
2354
 
 
2368
  ingredient_totals = meta["ingredient_totals"]
2369
  ingredient_amount_parts = meta["ingredient_amount_parts"]
2370
 
2371
+ mfds_df = load_mfds_detail_db() if use_mfds_db else pd.DataFrame()
2372
+
2373
  llm = ChatOpenAI(
2374
  model="gpt-4o-mini",
2375
  temperature=0,
 
2431
  source="LOCAL_RULE",
2432
  context=note if note and note != "-" else "둜컬 κ³ μ • κ·œμΉ™ μš°μ„  νŒμ •",
2433
  )
2434
+ continue
2435
+
2436
+ mfds_result = None
2437
+
2438
+ if use_mfds_db and mfds_df is not None and not mfds_df.empty:
2439
+ mfds_result = evaluate_mfds_detail_rule(
2440
+ country=country,
2441
+ material=item["material"],
2442
+ component=item["component"],
2443
+ mfds_df=mfds_df,
2444
+ )
2445
+
2446
+ if mfds_result is not None:
2447
+ item["row_data"][col_name] = mfds_result.get("κ²°κ³Ό", "")
2448
+
2449
+ note = safe_str(mfds_result.get("λΉ„κ³ ", "-"))
2450
+ if note and note != "-":
2451
+ item["notes"].append(f"{col_name}: {note}")
2452
+
2453
+ log_search_context(
2454
+ target_id=item["target_id"],
2455
+ country=country,
2456
+ component=item["component"],
2457
+ result_text=mfds_result.get("κ²°κ³Ό", ""),
2458
+ source="MFDS_DETAIL_DB",
2459
+ context=note,
2460
+ )
2461
+ continue
2462
 
2463
+ gpt_targets.append({
2464
+ "target_id": item["target_id"],
2465
+ "material": item["material"],
2466
+ "component": item["component"],
2467
+ })
 
2468
 
2469
  batch_results = evaluate_components_with_llm_batch(
2470
  country=country,
 
2517
  raw_df[col] = ""
2518
  raw_df = raw_df[raw_columns]
2519
 
2520
+ formula_total = sum_formula_percent(formula_df)
 
 
 
2521
 
2522
  safe_country_name = "_".join([
2523
  re.sub(r"[^a-zA-Z0-9κ°€-힣_-]", "_", str(c))
 
2536
  )
2537
 
2538
  issue_count = len(regulatory_df)
2539
+ mfds_count = len(mfds_df) if mfds_df is not None else 0
2540
 
2541
  msg = (
2542
  "βœ… 뢄석 μ™„λ£Œ\n"
 
2544
  f"- μ „μ„±λΆ„ ν–‰ 수: {len(formula_df)}개\n"
2545
  f"- In formula 합계: {format_amount(formula_total)}%\n"
2546
  f"- μž¬κ²€ν†  ν•„μš” μ„±λΆ„: {issue_count}개\n"
2547
+ f"- MFDS 상세 DB ν–‰ 수: {mfds_count}개\n"
2548
  "- κ²°κ³Ό νŒŒμΌμ€ 3개 μ‹œνŠΈλ‘œ μ €μž₯ν–ˆμŠ΅λ‹ˆλ‹€.\n"
2549
+ " 1) Formula Ingredients Statement: κ°„μ†Œν™” μ „μ„±λΆ„ν‘œ\n"
2550
  " 2) Regulatory Screening Summary: 문제 μžˆλŠ” μ„±λΆ„λ§Œ ꡭ가별 μš”μ•½\n"
2551
+ " 3) Raw Search Log: 둜컬 κ·œμΉ™/MFDS/GPT 검색 κ·Όκ±° 둜그\n"
2552
+ "- νŒμ • μš°μ„ μˆœμœ„: 둜컬 κ³ μ • κ·œμΉ™ β†’ MFDS 상세 DB β†’ ꡭ가별 FAISS/GPT\n"
2553
+ "- MFDS 상세 DBλŠ” ν•΄λ‹Ή κ΅­κ°€ μΉΈμ—λ§Œ 반영되며, ν•œκ΅­ κ·œμ •μœΌλ‘œ μžλ™ μ²˜λ¦¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.\n"
2554
+ "- ꡭ가별 FAISS DBλ₯Ό λΆ„λ¦¬ν•΄μ„œ EU κ²°κ³Όκ°€ ν•œκ΅­/일본/미ꡭ으둜 μžλ™ ν™•μ‚°λ˜μ§€ μ•Šλ„λ‘ μˆ˜μ •ν–ˆμŠ΅λ‹ˆλ‹€.\n"
2555
+ "- public share linkκ°€ μƒμ„±λ˜λ„λ‘ share=True둜 μ‹€ν–‰ν•©λ‹ˆλ‹€."
2556
  )
2557
 
2558
  return formula_df, out_path, msg
 
2564
 
2565
 
2566
  # ============================================================
2567
+ # 13. Gradio UI
2568
  # ============================================================
2569
 
2570
  with gr.Blocks(css=custom_css) as demo:
2571
  gr.Markdown("# 🌍 reBom Regulatory Screening AI")
2572
+ gr.Markdown("### κΈ€λ‘œλ²Œ ν™”μž₯ν’ˆ 규제 기반 μ „μ„±λΆ„ μŠ€ν¬λ¦¬λ‹ + MFDS 상세 DB 연동")
2573
 
2574
  with gr.Row():
2575
  gr.Button(
 
2578
  variant="secondary",
2579
  )
2580
 
2581
+ with gr.Tab("πŸš€ μŠ€ν¬λ¦¬λ‹"):
2582
+ country = gr.CheckboxGroup(
2583
+ choices=get_country_folders(),
2584
+ value=[],
2585
+ label="🌍 κ΅­κ°€ / 채널 선택",
2586
+ elem_id="country_checks",
2587
+ )
 
2588
 
2589
+ refresh = gr.Button("πŸ”„ 폴더/규제파일 μƒˆλ‘œκ³ μΉ¨")
 
 
 
2590
 
2591
+ product_name = gr.Textbox(
2592
+ label="μ œν’ˆλͺ… / PRODUCT NAME",
2593
+ placeholder="예: Mania Holic Sunscreen Pack",
2594
+ )
2595
 
2596
+ file = gr.File(
2597
+ label="μ „μ„±λΆ„ μ—‘μ…€ μ—…λ‘œλ“œ",
2598
+ file_types=[".xlsx"],
2599
+ )
2600
 
2601
+ use_mfds_db = gr.Checkbox(
2602
+ label="MFDS 상세 DB μš°μ„  반영",
2603
+ value=True,
2604
+ )
 
2605
 
2606
+ btn = gr.Button("πŸš€ 뢄석 μ‹œμž‘", variant="primary")
2607
 
2608
+ df_out = gr.Dataframe(
2609
+ label="미리보기 - Formula Ingredients Statement",
2610
+ wrap=True,
2611
+ interactive=False,
2612
+ )
2613
 
2614
+ file_out = gr.File(label="κ²°κ³Ό λ‹€μš΄λ‘œλ“œ")
 
 
 
 
2615
 
2616
+ msg_out = gr.Textbox(
2617
+ label="μƒνƒœ / 였λ₯˜ λ©”μ‹œμ§€",
2618
+ interactive=False,
2619
+ lines=14,
2620
+ )
2621
 
2622
+ refresh.click(
2623
+ fn=refresh_country_choices_and_clear_cache,
2624
  inputs=country,
2625
  outputs=country,
2626
  )
 
 
2627
 
2628
+ try:
2629
+ auto_refresh_timer = gr.Timer(15)
 
 
 
2630
 
2631
+ auto_refresh_timer.tick(
2632
+ fn=refresh_country_choices_keep_selection,
2633
+ inputs=country,
2634
+ outputs=country,
2635
+ )
2636
+ except Exception as e:
2637
+ print(f"μžλ™ κ΅­κ°€ λͺ©λ‘ κ°±μ‹  타이머 λΉ„ν™œμ„±ν™”: {e}")
2638
+
2639
+ file.change(
2640
+ fn=preview_excel,
2641
+ inputs=file,
2642
+ outputs=df_out,
2643
+ )
2644
+
2645
+ btn.click(
2646
+ process,
2647
+ inputs=[country, file, product_name, use_mfds_db],
2648
+ outputs=[df_out, file_out, msg_out],
2649
+ )
2650
+
2651
+ with gr.Tab("πŸ‡°πŸ‡· MFDS 상세 DB 관리"):
2652
+ gr.Markdown(
2653
+ """
2654
+ ### MFDS 상세 DB μ‚¬μš© 방식
2655
+
2656
+ μ˜μ•½ν’ˆμ•ˆμ „λ‚˜λΌ μ‚¬μ΄νŠΈλŠ” μžλ™ 접속이 λ§‰νžˆκ±°λ‚˜ 동적 νŽ˜μ΄μ§€ 문제둜 λΆˆμ•ˆμ •ν•  수 μžˆμ–΄μ„œ,
2657
+ 이 μ•±μ—μ„œλŠ” **μ‚¬μ΄νŠΈ μ‹€μ‹œκ°„ 크둀링 λŒ€μ‹  상세정보 μ—‘μ…€ DB 방식**으둜 μ—°λ™ν•©λ‹ˆλ‹€.
2658
+
2659
+ μ—‘μ…€ 파일λͺ…은 μžλ™μœΌλ‘œ μ•„λž˜ μ΄λ¦„μœΌλ‘œ μ €μž₯λ©λ‹ˆλ‹€.
2660
+
2661
+ `MFDS_ꡭ가별_κΈˆμ§€μ œν•œ_상세.xlsx`
2662
+
2663
+ ν•„μˆ˜ 컬럼:
2664
+ - μ›λ£Œλͺ…
2665
+ - INCI
2666
+ - CAS.No
2667
+ - ꡬ뢄
2668
+ - κ΅­κ°€
2669
+ - κ·œμ œλ‚΄μš©
2670
+ - ν•œλ„
2671
+ - 쑰건
2672
+ - 좜처
2673
+ - 상세원문
2674
+ """
2675
+ )
2676
+
2677
+ template_btn = gr.Button("πŸ“„ MFDS 상세 DB ν…œν”Œλ¦Ώ λ‹€μš΄λ‘œλ“œ")
2678
+ template_file = gr.File(label="ν…œν”Œλ¦Ώ λ‹€μš΄λ‘œλ“œ")
2679
+ template_msg = gr.Textbox(label="ν…œν”Œλ¦Ώ μƒνƒœ", interactive=False, lines=3)
2680
+
2681
+ template_btn.click(
2682
+ download_mfds_template,
2683
+ inputs=[],
2684
+ outputs=[template_file, template_msg],
2685
+ )
2686
+
2687
+ mfds_upload = gr.File(
2688
+ label="MFDS 상세 DB μ—‘μ…€ μ—…λ‘œλ“œ",
2689
+ file_types=[".xlsx"],
2690
+ )
2691
+
2692
+ mfds_save_btn = gr.Button("πŸ“₯ μ—…λ‘œλ“œ 엑셀을 MFDS 상세 DB둜 μ €μž₯", variant="primary")
2693
+
2694
+ mfds_db_file = gr.File(label="ν˜„μž¬ MFDS 상세 DB λ‹€μš΄λ‘œλ“œ")
2695
+ mfds_db_msg = gr.Textbox(label="MFDS DB μƒνƒœ", lines=8, interactive=False)
2696
+
2697
+ mfds_save_btn.click(
2698
+ upload_mfds_db,
2699
+ inputs=mfds_upload,
2700
+ outputs=[mfds_db_file, mfds_db_msg],
2701
+ )
2702
 
2703
 
2704
  # ============================================================
2705
+ # 14. 둜그인 인증
2706
  # ============================================================
2707
 
2708
  USER_DB = {
 
2723
 
2724
 
2725
  # ============================================================
2726
+ # 15. μ•± μ‹€ν–‰
2727
  # ============================================================
2728
 
2729
  try:
2730
  demo.launch(
2731
  server_name="0.0.0.0",
2732
  server_port=7860,
2733
+ share=True,
2734
  ssr_mode=False,
2735
  auth=auth_fn,
2736
  allowed_paths=ALLOWED_PATHS,
 
2747
  demo.launch(
2748
  server_name="0.0.0.0",
2749
  server_port=7860,
2750
+ share=True,
2751
  auth=auth_fn,
2752
  allowed_paths=ALLOWED_PATHS,
2753
  blocked_paths=BLOCKED_PATHS,