jin2li commited on
Commit
fcc11e3
ยท
verified ยท
1 Parent(s): ae92da5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +650 -540
app.py CHANGED
@@ -1,13 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import re
3
  import json
4
- import time
5
- import shutil
6
  import hashlib
7
  import traceback
8
- import threading
9
  from collections import defaultdict
10
- from concurrent.futures import ThreadPoolExecutor, as_completed
11
 
12
  import pandas as pd
13
  import pdfplumber
@@ -20,38 +28,19 @@ from langchain_community.vectorstores import FAISS
20
  from langchain_text_splitters import RecursiveCharacterTextSplitter
21
 
22
 
23
- # =========================
24
  # ๊ธฐ๋ณธ ์„ค์ •
25
- # =========================
 
26
  api_key = os.getenv("OPENAI_API_KEY")
27
  print("โœ… OPENAI_API_KEY ์ •์ƒ" if api_key else "โŒ OPENAI_API_KEY ์—†์Œ")
28
 
29
- # ์†๋„ ๊ด€๋ จ ์„ค์ •
30
- # ์ˆซ์ž๋ฅผ ์˜ฌ๋ฆฌ๋ฉด ๋นจ๋ผ์งˆ ์ˆ˜ ์žˆ์ง€๋งŒ OpenAI API rate limit์— ๊ฑธ๋ฆด ์ˆ˜ ์žˆ์Œ.
31
- MAX_WORKERS = int(os.getenv("SCREENING_MAX_WORKERS", "4"))
32
-
33
- # ์„ฑ๋ถ„๋ณ„ ๊ทœ์ œ๋ฌธ์„œ ๊ฒ€์ƒ‰ ๊ฐœ์ˆ˜. ๊ธฐ์กด 8๋ณด๋‹ค ๋‚ฎ์ถฐ ์†๋„ ๊ฐœ์„ .
34
- SEARCH_K = int(os.getenv("SCREENING_SEARCH_K", "4"))
35
-
36
- # FAISS ๋””์Šคํฌ ์บ์‹œ ํด๋”
37
- FAISS_CACHE_DIR = os.getenv("FAISS_CACHE_DIR", ".faiss_cache")
38
-
39
- # ๊ตญ๊ฐ€๋ณ„ ๊ทœ์ œ DB ๋ฉ”๋ชจ๋ฆฌ ์บ์‹œ
40
- # VECTOR_DB_CACHE[country_folder] = {
41
- # "signature_hash": ํด๋” ๋‚ด ํŒŒ์ผ ์ƒํƒœ hash,
42
- # "db": FAISS DB,
43
- # "file_count": ํŒŒ์ผ ๊ฐœ์ˆ˜,
44
- # }
45
  VECTOR_DB_CACHE = {}
46
-
47
- # ์„ฑ๋ถ„๋ณ„ ํ‰๊ฐ€ ๊ฒฐ๊ณผ ๋ฉ”๋ชจ๋ฆฌ ์บ์‹œ
48
  EVAL_CACHE = {}
 
49
 
50
- # thread-safe cache access
51
- DB_LOCK = threading.Lock()
52
- CACHE_LOCK = threading.Lock()
53
 
54
- # ๊ทœ์ œ DB๋กœ ์ฝ์„ ํŒŒ์ผ ํ™•์žฅ์ž
55
  SUPPORTED_REG_FILE_EXTENSIONS = {
56
  ".pdf",
57
  ".txt",
@@ -60,7 +49,6 @@ SUPPORTED_REG_FILE_EXTENSIONS = {
60
  ".xls",
61
  }
62
 
63
- # UI์— ์šฐ์„  ํ‘œ์‹œํ•  ๊ตญ๊ฐ€/์ฑ„๋„ ์ˆœ์„œ
64
  COUNTRY_ORDER = [
65
  "ASEAN",
66
  "CALIFORNIA",
@@ -126,7 +114,6 @@ COUNTRY_DISPLAY = {
126
  "ULTA": "ULTA",
127
  }
128
 
129
- # UI ์„ ํƒ๊ฐ’๊ณผ ์‹ค์ œ PDF/๊ทœ์ œ์ž๋ฃŒ ํด๋”๋ช…์ด ๋‹ค๋ฅผ ๋•Œ๋ฅผ ๋Œ€๋น„ํ•œ ๋ณ„์นญ
130
  COUNTRY_FOLDER_ALIASES = {
131
  "ํ•œ๊ตญ": "KOREA",
132
  "KOREA": "KOREA",
@@ -175,6 +162,11 @@ COUNTRY_FOLDER_ALIASES = {
175
  "ULTA": "ULTA",
176
  }
177
 
 
 
 
 
 
178
  custom_css = """
179
  #country_checks .wrap,
180
  #country_checks .checkbox-group {
@@ -196,10 +188,10 @@ custom_css = """
196
  """
197
 
198
 
199
- # =========================
200
  # ๋กœ์ปฌ ๊ณ ์ • ๊ทœ์น™
201
- # - GPT/๋ฒกํ„ฐ ๊ฒ€์ƒ‰์ด ๋†“์น˜๊ธฐ ์‰ฌ์šด ํ–ฅ๋ฃŒ ์•Œ๋ ˆ๋ฅด๊ฒ, ์ •์œ ๋ฅ˜, ๊ธฐ๋Šฅ์„ฑ/๊ณ ๋ถ„์ž ๊ฒ€ํ†  ํ•ญ๋ชฉ์„ ์šฐ์„  ํŒ์ •
202
- # =========================
203
  FRAGRANCE_ALLERGEN_RULES = {
204
  "limonene": {
205
  "label": "Limonene",
@@ -293,9 +285,10 @@ for canonical_name, rule in FRAGRANCE_ALLERGEN_RULES.items():
293
  FRAGRANCE_ALIAS_TO_CANONICAL[alias.lower()] = canonical_name
294
 
295
 
296
- # =========================
297
  # ๊ณตํ†ต ์œ ํ‹ธ
298
- # =========================
 
299
  def safe_str(x):
300
  if pd.isna(x):
301
  return ""
@@ -424,15 +417,51 @@ def canonical_inci_name(inci_name):
424
  return norm
425
 
426
 
427
- def resolve_country_folder(country):
428
- """
429
- UI ์„ ํƒ๊ฐ’์„ ์‹ค์ œ ๊ทœ์ œ ํŒŒ์ผ ํด๋”๋ช…์œผ๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค.
430
- ์˜ˆ:
431
- - ํ•œ๊ตญ โ†’ KOREA
432
- - ๋ฏธ๊ตญ/USA/US โ†’ FDA
433
- - EU_FUTURE โ†’ EU (FUTURE)
434
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
435
 
 
436
  if not country or country == "ํด๋” ์—†์Œ":
437
  return None
438
 
@@ -458,12 +487,10 @@ def resolve_country_folder(country):
458
  if item and item not in seen:
459
  seen.append(item)
460
 
461
- # ์ •ํ™•ํ•œ ํด๋”๋ช… ์šฐ์„ 
462
  for item in seen:
463
  if os.path.isdir(item):
464
  return item
465
 
466
- # ๋Œ€์†Œ๋ฌธ์ž ๋ฌด์‹œ ๋งค์นญ
467
  folder_map = {
468
  f.lower(): f
469
  for f in os.listdir(".")
@@ -479,12 +506,6 @@ def resolve_country_folder(country):
479
 
480
 
481
  def get_country_folders():
482
- """
483
- ํ˜„์žฌ ์ž‘์—… ํด๋”์— ์กด์žฌํ•˜๋Š” ๊ตญ๊ฐ€/์ฑ„๋„ ํด๋”๋ฅผ ์ž๋™์œผ๋กœ ์ฝ์–ด UI ๋ชฉ๋ก์— ๋ฐ˜์˜ํ•œ๋‹ค.
484
- COUNTRY_ORDER์— ์žˆ๋Š” ํด๋”๋Š” ์ง€์ • ์ˆœ์„œ๋Œ€๋กœ ํ‘œ์‹œํ•˜๊ณ ,
485
- ์ƒˆ๋กœ ์ถ”๊ฐ€๋œ ํด๋”๋Š” ๋’ค์ชฝ์— ์ž๋™ ์ถ”๊ฐ€ํ•œ๋‹ค.
486
- """
487
-
488
  exclude = [
489
  ".git",
490
  ".cache",
@@ -503,19 +524,37 @@ def get_country_folders():
503
 
504
  existing_set = set(existing_folders)
505
 
506
- # ์ง€์ • ์ˆœ์„œ ์šฐ์„ 
507
  ordered = [c for c in COUNTRY_ORDER if c in existing_set]
508
-
509
- # COUNTRY_ORDER์— ์—†๋Š” ์ƒˆ ๊ตญ๊ฐ€/์ฑ„๋„ ํด๋”๋Š” ์ž๋™ ์ถ”๊ฐ€
510
  extras = sorted([f for f in existing_folders if f not in COUNTRY_ORDER])
511
 
512
- # ์‹ค์ œ ํด๋”๊ฐ€ ์—†์œผ๋ฉด ๊ธฐ๋ณธ ๋ชฉ๋ก๋งŒ ํ‘œ์‹œ
513
  if not ordered and not extras:
514
  return COUNTRY_ORDER.copy()
515
 
516
  return ordered + extras
517
 
518
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
  def preview_excel(file):
520
  if not file:
521
  return None
@@ -526,29 +565,10 @@ def preview_excel(file):
526
  return pd.DataFrame({"์˜ค๋ฅ˜": [str(e)]})
527
 
528
 
529
- def signature_to_hash(signature):
530
- text = json.dumps(signature, ensure_ascii=False, sort_keys=True)
531
- return hashlib.sha256(text.encode("utf-8")).hexdigest()
532
-
533
-
534
- def safe_cache_folder_name(country_folder):
535
- abs_path = os.path.abspath(country_folder)
536
- digest = hashlib.sha256(abs_path.encode("utf-8")).hexdigest()[:16]
537
- base = re.sub(r"[^a-zA-Z0-9๊ฐ€-ํžฃ_-]+", "_", os.path.basename(country_folder)).strip("_")
538
- return f"{base}_{digest}"
539
-
540
-
541
- def get_faiss_cache_paths(country_folder):
542
- os.makedirs(FAISS_CACHE_DIR, exist_ok=True)
543
- cache_name = safe_cache_folder_name(country_folder)
544
- cache_path = os.path.join(FAISS_CACHE_DIR, cache_name)
545
- meta_path = os.path.join(cache_path, "metadata.json")
546
- return cache_path, meta_path
547
-
548
-
549
- # =========================
550
  # ์ปฌ๋Ÿผ ์ž๋™ ์ธ์‹
551
- # =========================
 
552
  def find_best_col(df, keywords, default_index=None, exclude_cols=None):
553
  exclude_cols = exclude_cols or []
554
  scores = []
@@ -655,12 +675,6 @@ def find_numeric_col(df, keywords, default_index=None, exclude_cols=None, prefer
655
 
656
 
657
  def find_main_columns(df):
658
- """
659
- ๊ธฐ๋Œ€ ์ž…๋ ฅ ํ˜•ํƒœ:
660
- NO / Trade name(๊ตญ๋ฌธ) / Trade name(์˜๋ฌธ) / ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช… / INCI Name /
661
- Contents(w/w %) / In formula(w/w %)
662
- """
663
-
664
  no_col = find_best_col(df, ["no", "๋ฒˆํ˜ธ", "์ˆœ๋ฒˆ"], default_index=0)
665
 
666
  trade_ko_col = find_best_col(
@@ -707,15 +721,16 @@ def find_main_columns(df):
707
  prefer_many_values=True
708
  )
709
 
710
- # Contents์™€ In formula๊ฐ€ ๊ฐ™์€ ์ปฌ๋Ÿผ์œผ๋กœ ์žกํžˆ๋ฉด ์ˆซ์ž ์ปฌ๋Ÿผ ๋’ค์ชฝ 2๊ฐœ๋ฅผ ๋ณด์กฐ ์‚ฌ์šฉ
711
  if contents_col == formula_col:
712
  numeric_cols = []
713
  for col in df.columns:
714
  if col in [no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col]:
715
  continue
 
716
  values = df[col].dropna()
717
  if values.empty:
718
  continue
 
719
  count = values.apply(is_numeric_like).sum()
720
  if count > 0:
721
  numeric_cols.append(col)
@@ -735,18 +750,11 @@ def find_main_columns(df):
735
  }
736
 
737
 
738
- # =========================
739
- # ์—‘์…€ ์›๋ณธ ์ •๋ฆฌ
740
- # =========================
741
- def clean_input_df(df, cols):
742
- """
743
- ์ด์ „ ๊ฒฐ๊ณผ ํŒŒ์ผ์ด๋‚˜ PDF์—์„œ ๋ถ™์€ ๊ผฌ๋ฆฌ๋ง์ด ๋“ค์–ด์˜จ ๊ฒฝ์šฐ๋ฅผ ์ œ๊ฑฐํ•œ๋‹ค.
744
- ํ•ต์‹ฌ ์ˆ˜์ •์ :
745
- - ํ•ฉ๊ณ„ ์•„๋ž˜์˜ Commitment, ์ฃผ์†Œ, Lab No. ๊ฐ™์€ footer ํ–‰ ์ „๋ถ€ ์ œ์™ธ
746
- - ์ค‘๋ณต ํ—ค๋” ํ–‰ ์ œ์™ธ
747
- - ๋นˆ ํ–‰ ์ œ์™ธ
748
- """
749
 
 
750
  no_col = cols["no_col"]
751
  trade_ko_col = cols["trade_ko_col"]
752
  trade_en_col = cols["trade_en_col"]
@@ -831,11 +839,6 @@ def compute_totals(cleaned_df, cols):
831
 
832
 
833
  def compute_ingredient_totals(cleaned_df, cols):
834
- """
835
- ํ–ฅ๋ฃŒ ์•Œ๋ ˆ๋ฅด๊ฒ ๋“ฑ์€ ๋™์ผ ์„ฑ๋ถ„์ด ์—ฌ๋Ÿฌ ์›๋ฃŒ์—์„œ ๋“ค์–ด์˜ค๋ฉด ์ด๋Ÿ‰์œผ๋กœ ํŒ๋‹จํ•œ๋‹ค.
836
- ์˜ˆ: d-LIMONENE + Limonene = ์ด Limonene
837
- """
838
-
839
  inci_col = cols["inci_col"]
840
  formula_col = cols["formula_col"]
841
 
@@ -862,15 +865,106 @@ def compute_ingredient_totals(cleaned_df, cols):
862
  return totals, amount_parts
863
 
864
 
865
- # =========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866
  # ๊ทœ์ œ ํŒŒ์ผ ์ž๋™ ์ธ์‹ / ์ž๋™ ์žฌ์ƒ‰์ธ
867
- # =========================
868
- def get_regulatory_file_list(country_folder):
869
- """
870
- ๊ตญ๊ฐ€ ํด๋” ์•ˆ์˜ ๊ทœ์ œ ํŒŒ์ผ ๋ชฉ๋ก์„ ์žฌ๊ท€์ ์œผ๋กœ ์ฝ๋Š”๋‹ค.
871
- ์ง€์› ํ™•์žฅ์ž: PDF, TXT, CSV, XLSX, XLS
872
- """
873
 
 
874
  files = []
875
 
876
  if not country_folder or not os.path.isdir(country_folder):
@@ -909,11 +1003,6 @@ def get_regulatory_file_list(country_folder):
909
 
910
 
911
  def get_regulatory_folder_signature(country_folder):
912
- """
913
- ํด๋” ์•ˆ ๊ทœ์ œ ํŒŒ์ผ์˜ ๋ณ€๊ฒฝ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•˜๊ธฐ ์œ„ํ•œ signature.
914
- ํŒŒ์ผ๋ช…, ํŒŒ์ผ ํฌ๊ธฐ, ์ˆ˜์ •์‹œ๊ฐ„์ด ๋ฐ”๋€Œ๋ฉด signature๊ฐ€ ๋ฐ”๋€๋‹ค.
915
- """
916
-
917
  file_list = get_regulatory_file_list(country_folder)
918
 
919
  signature = tuple(
@@ -942,11 +1031,6 @@ def read_text_file_with_fallback(file_path):
942
 
943
 
944
  def extract_text_from_regulatory_file(file_item):
945
- """
946
- ๊ทœ์ œ ํŒŒ์ผ 1๊ฐœ์—๏ฟฝ๏ฟฝ ํ…์ŠคํŠธ ์ถ”์ถœ.
947
- PDF / TXT / CSV / XLSX / XLS ์ง€์›.
948
- """
949
-
950
  file_path = file_item["path"]
951
  rel_path = file_item["relative_path"]
952
  ext = file_item["ext"]
@@ -988,7 +1072,16 @@ def extract_text_from_regulatory_file(file_item):
988
  return "\n\n".join(texts)
989
 
990
 
991
- def get_current_db_signature_hash(country):
 
 
 
 
 
 
 
 
 
992
  folder = resolve_country_folder(country)
993
  cached = VECTOR_DB_CACHE.get(folder)
994
 
@@ -998,43 +1091,6 @@ def get_current_db_signature_hash(country):
998
  return None
999
 
1000
 
1001
- def refresh_country_choices_keep_selection(current_values=None):
1002
- """
1003
- ๊ตญ๊ฐ€ ํด๋” ๋ชฉ๋ก์„ ๋‹ค์‹œ ์ฝ๊ณ ,
1004
- ์ด๋ฏธ ์„ ํƒํ•œ ๊ตญ๊ฐ€๋Š” ์ƒˆ ๋ชฉ๋ก์— ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ ์œ ์ง€ํ•œ๋‹ค.
1005
- """
1006
-
1007
- choices = get_country_folders()
1008
- current_values = current_values or []
1009
- kept_values = [v for v in current_values if v in choices]
1010
-
1011
- return gr.update(
1012
- choices=choices,
1013
- value=kept_values,
1014
- )
1015
-
1016
-
1017
- def refresh_country_choices_and_clear_cache(current_values=None):
1018
- """
1019
- ์‚ฌ์šฉ์ž๊ฐ€ ์ƒˆ๋กœ๊ณ ์นจ ๋ฒ„ํŠผ์„ ๋ˆŒ๋ €์„ ๋•Œ:
1020
- - ๊ตญ๊ฐ€ ๋ชฉ๋ก ๊ฐฑ์‹ 
1021
- - ๋ฒกํ„ฐ DB ๋ฉ”๋ชจ๋ฆฌ ์บ์‹œ ์ดˆ๊ธฐํ™”
1022
- - ํ‰๊ฐ€ ๊ฒฐ๊ณผ ์บ์‹œ ์ดˆ๊ธฐํ™”
1023
- - ๋””์Šคํฌ FAISS ์บ์‹œ๋Š” ์‚ญ์ œํ•˜์ง€ ์•Š์Œ
1024
- """
1025
-
1026
- with DB_LOCK:
1027
- VECTOR_DB_CACHE.clear()
1028
-
1029
- with CACHE_LOCK:
1030
- EVAL_CACHE.clear()
1031
-
1032
- return refresh_country_choices_keep_selection(current_values)
1033
-
1034
-
1035
- # =========================
1036
- # ๊ทœ์ œ DB ๊ตฌ์ถ•
1037
- # =========================
1038
  def build_database(country_folder):
1039
  country_folder = resolve_country_folder(country_folder)
1040
 
@@ -1044,232 +1100,128 @@ def build_database(country_folder):
1044
  if not os.path.isdir(country_folder):
1045
  return None
1046
 
1047
- with DB_LOCK:
1048
- current_signature, file_list = get_regulatory_folder_signature(country_folder)
1049
- current_signature_hash = signature_to_hash(current_signature)
1050
-
1051
- if not file_list:
1052
- VECTOR_DB_CACHE.pop(country_folder, None)
1053
- return None
1054
-
1055
- cached = VECTOR_DB_CACHE.get(country_folder)
1056
 
1057
- # ๋ฉ”๋ชจ๋ฆฌ ์บ์‹œ hit
1058
- if (
1059
- isinstance(cached, dict)
1060
- and cached.get("signature_hash") == current_signature_hash
1061
- and cached.get("db") is not None
1062
- ):
1063
- return cached["db"]
1064
-
1065
- embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
1066
- cache_path, meta_path = get_faiss_cache_paths(country_folder)
1067
-
1068
- # ๋””์Šคํฌ ์บ์‹œ hit
1069
- if os.path.isdir(cache_path) and os.path.isfile(meta_path):
1070
- try:
1071
- with open(meta_path, "r", encoding="utf-8") as f:
1072
- meta = json.load(f)
1073
-
1074
- if meta.get("signature_hash") == current_signature_hash:
1075
- db = FAISS.load_local(
1076
- cache_path,
1077
- embeddings,
1078
- allow_dangerous_deserialization=True,
1079
- )
1080
-
1081
- VECTOR_DB_CACHE[country_folder] = {
1082
- "signature_hash": current_signature_hash,
1083
- "db": db,
1084
- "file_count": len(file_list),
1085
- }
1086
-
1087
- print(f"โœ… FAISS ๋””์Šคํฌ ์บ์‹œ ์‚ฌ์šฉ: {country_folder} / ํŒŒ์ผ {len(file_list)}๊ฐœ")
1088
- return db
1089
-
1090
- except Exception as e:
1091
- print(f"FAISS ๋””์Šคํฌ ์บ์‹œ ๋กœ๋“œ ์‹คํŒจ, ์žฌ์ƒ‰์ธ ์ง„ํ–‰: {country_folder} / {e}")
1092
-
1093
- # ํŒŒ์ผ์ด ์ถ”๊ฐ€/์ˆ˜์ •/์‚ญ์ œ๋˜์—ˆ์œผ๋ฉด ์žฌ์ƒ‰์ธ
1094
- print(f"๐Ÿ”„ ๊ทœ์ œ DB ์žฌ์ƒ‰์ธ: {country_folder} / ํŒŒ์ผ {len(file_list)}๊ฐœ")
1095
-
1096
- # ๊ทœ์ œ ์›๋ฌธ์ด ๋ฐ”๋€Œ๋ฉด ๊ธฐ์กด ํ‰๊ฐ€ ๊ฒฐ๊ณผ ์บ์‹œ๋Š” stale ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ์œผ๋ฏ€๋กœ ์ดˆ๊ธฐํ™”
1097
- with CACHE_LOCK:
1098
- EVAL_CACHE.clear()
1099
-
1100
- texts = []
1101
-
1102
- splitter = RecursiveCharacterTextSplitter(
1103
- chunk_size=900,
1104
- chunk_overlap=120
1105
- )
1106
-
1107
- for file_item in file_list:
1108
- raw_text = extract_text_from_regulatory_file(file_item)
1109
-
1110
- if not raw_text:
1111
- continue
1112
 
1113
- source_text = (
1114
- f"[๊ตญ๊ฐ€/์ฑ„๋„: {country_folder}] "
1115
- f"[์ถœ์ฒ˜ํŒŒ์ผ: {file_item['relative_path']}]\n"
1116
- f"{raw_text}"
1117
- )
1118
 
1119
- chunks = splitter.split_text(source_text)
1120
- texts.extend(chunks)
1121
 
1122
- if not texts:
1123
- VECTOR_DB_CACHE.pop(country_folder, None)
1124
- return None
 
 
 
1125
 
1126
- db = FAISS.from_texts(
1127
- texts,
1128
- embeddings,
1129
- )
1130
 
1131
- # ๋””์Šคํฌ ์บ์‹œ ์ €์žฅ
1132
  try:
1133
- if os.path.isdir(cache_path):
1134
- shutil.rmtree(cache_path)
1135
-
1136
- os.makedirs(cache_path, exist_ok=True)
1137
- db.save_local(cache_path)
1138
-
1139
- meta = {
1140
- "country_folder": country_folder,
1141
- "absolute_path": os.path.abspath(country_folder),
1142
- "signature_hash": current_signature_hash,
1143
- "file_count": len(file_list),
1144
- "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
1145
- "files": [
1146
- {
1147
- "relative_path": item["relative_path"],
1148
- "size": item["size"],
1149
- "mtime_ns": item["mtime_ns"],
1150
- "ext": item["ext"],
1151
- }
1152
- for item in file_list
1153
- ],
1154
- }
1155
-
1156
- with open(meta_path, "w", encoding="utf-8") as f:
1157
- json.dump(meta, f, ensure_ascii=False, indent=2)
1158
-
1159
- except Exception as e:
1160
- print(f"FAISS ๋””์Šคํฌ ์บ์‹œ ์ €์žฅ ์‹คํŒจ: {country_folder} / {e}")
1161
-
1162
- VECTOR_DB_CACHE[country_folder] = {
1163
- "signature_hash": current_signature_hash,
1164
- "db": db,
1165
- "file_count": len(file_list),
1166
- }
1167
-
1168
- return db
1169
-
1170
-
1171
- # =========================
1172
- # ์›๋ฃŒ ๊ทธ๋ฃนํ™” + ๊ตฌ์„ฑ ์„ฑ๋ถ„ ํ–‰ ๋ณด์กด
1173
- # =========================
1174
- def make_grouped_materials(df):
1175
- cols = find_main_columns(df)
1176
- cleaned_df = clean_input_df(df, cols)
1177
-
1178
- no_col = cols["no_col"]
1179
- trade_ko_col = cols["trade_ko_col"]
1180
- trade_en_col = cols["trade_en_col"]
1181
- korean_ing_col = cols["korean_ing_col"]
1182
- inci_col = cols["inci_col"]
1183
- contents_col = cols["contents_col"]
1184
- formula_col = cols["formula_col"]
1185
 
1186
- work_df = cleaned_df.copy()
 
 
 
 
1187
 
1188
- for col in [no_col, trade_ko_col, trade_en_col]:
1189
- if col and col in work_df.columns:
1190
- work_df[col] = work_df[col].ffill()
1191
 
1192
- group_keys = [c for c in [no_col, trade_ko_col, trade_en_col] if c and c in work_df.columns]
 
1193
 
1194
- grouped_materials = []
 
1195
 
1196
- for key, group in work_df.groupby(group_keys, dropna=True, sort=False):
1197
- if not isinstance(key, tuple):
1198
- key = (key,)
1199
 
1200
- no_value = format_no(key[0]) if len(key) > 0 else ""
1201
- trade_ko = safe_str(key[1]) if len(key) > 1 else ""
1202
- trade_en = safe_str(key[2]) if len(key) > 2 else trade_ko
 
1203
 
1204
- # ์ˆซ์ž NO๊ฐ€ ์•„๋‹Œ footer์„ฑ ๊ทธ๋ฃน์€ ์ œ์™ธ
1205
- if no_value and not is_numeric_like(no_value):
1206
- continue
1207
 
1208
- if not trade_ko and not trade_en:
1209
  continue
1210
 
1211
- components = []
1212
- inci_list = []
1213
- final_amounts = []
1214
-
1215
- for _, row in group.iterrows():
1216
- korean_ing = safe_str(row.get(korean_ing_col, "")) if korean_ing_col in row else ""
1217
- inci_name = safe_str(row.get(inci_col, "")) if inci_col in row else ""
1218
-
1219
- if not inci_name and not korean_ing:
1220
- continue
1221
-
1222
- contents_value = format_amount(row.get(contents_col)) if contents_col and contents_col in row else ""
1223
- formula_value = format_amount(row.get(formula_col)) if formula_col and formula_col in row else ""
1224
-
1225
- comp = {
1226
- "ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…": korean_ing,
1227
- "INCI Name": inci_name,
1228
- "Contents(w/w %)": contents_value,
1229
- "In formula(w/w %)": formula_value,
1230
- "amount_float": to_number(row.get(formula_col)) if formula_col and formula_col in row else None,
1231
- }
1232
- components.append(comp)
1233
 
1234
- if inci_name:
1235
- inci_list.append(inci_name)
1236
 
1237
- if inci_name and formula_value:
1238
- final_amounts.append(f"{inci_name}: {formula_value}")
 
1239
 
1240
- if not components:
1241
- continue
 
 
1242
 
1243
- inci_list = list(dict.fromkeys(inci_list))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1244
 
1245
- grouped_materials.append({
1246
- "NO": no_value,
1247
- "Trade name(๊ตญ๋ฌธ)": trade_ko,
1248
- "Trade name(์˜๋ฌธ)": trade_en,
1249
- "INCI_list": inci_list,
1250
- "Components": components,
1251
- "Final_amounts": final_amounts,
1252
- "Group_records": group.to_dict(orient="records"),
1253
- })
1254
 
1255
- contents_total, formula_total = compute_totals(cleaned_df, cols)
1256
- ingredient_totals, ingredient_amount_parts = compute_ingredient_totals(cleaned_df, cols)
1257
 
1258
- meta = {
1259
- "cols": cols,
1260
- "cleaned_df": cleaned_df,
1261
- "contents_total": contents_total,
1262
- "formula_total": formula_total,
1263
- "ingredient_totals": ingredient_totals,
1264
- "ingredient_amount_parts": ingredient_amount_parts,
1265
  }
1266
 
1267
- return grouped_materials, meta
 
1268
 
 
 
 
1269
 
1270
- # =========================
1271
- # GPT ์‘๋‹ต ํŒŒ์‹ฑ
1272
- # =========================
1273
  def parse_country_response(text):
1274
  result = {
1275
  "๋Œ€ํ‘œ INCI": "-",
@@ -1292,9 +1244,61 @@ def parse_country_response(text):
1292
  return result
1293
 
1294
 
1295
- # =========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1296
  # ๋กœ์ปฌ ๊ทœ์น™ ํŒ์ •
1297
- # =========================
 
1298
  def evaluate_local_rules(country, component, ingredient_totals, ingredient_amount_parts):
1299
  ckey = country_key(country)
1300
  inci_name = safe_str(component.get("INCI Name", ""))
@@ -1311,9 +1315,6 @@ def evaluate_local_rules(country, component, ingredient_totals, ingredient_amoun
1311
  canonical = canonical_inci_name(inci_name)
1312
  norm = normalize_text(inci_name)
1313
 
1314
- # EU / EU FUTURE / UK / ํ•œ๊ตญ ํ–ฅ๋ฃŒ ์•Œ๋ ˆ๋ฅด๊ฒ ํ‘œ์‹œ๊ธฐ์ค€
1315
- # Leave-on 0.001%, Wash-off 0.01%
1316
- # ์ด ๊ทœ์น™์€ ํ†ต๊ณผ ์—ฌ๋ถ€์™€ ๊ด€๊ณ„์—†์ด ํ•ญ์ƒ ํ‘œ์‹œ๋˜๋„๋ก ํ•œ๋‹ค.
1317
  if ckey in ["EU", "EU_FUTURE", "UK", "KOREA"] and canonical in FRAGRANCE_ALLERGEN_RULES:
1318
  rule = FRAGRANCE_ALLERGEN_RULES[canonical]
1319
  total_amount = ingredient_totals.get(canonical, amount)
@@ -1338,7 +1339,6 @@ def evaluate_local_rules(country, component, ingredient_totals, ingredient_amoun
1338
  "๋น„๊ณ ": "-",
1339
  }
1340
 
1341
- # EU / EU FUTURE / UK ์‹œํŠธ๋Ÿฌ์Šค ์ •์œ /์ถ”์ถœ๋ฌผ: furocoumarines ๋“ฑ ๊ด‘๋…์„ฑ ๊ด€๋ จ ์›๋ฃŒ์ž๋ฃŒ ํ™•์ธ
1342
  if ckey in ["EU", "EU_FUTURE", "UK"] and "citrus" in norm and (
1343
  "peel oil" in norm
1344
  or "fruit extract" in norm
@@ -1357,7 +1357,6 @@ def evaluate_local_rules(country, component, ingredient_totals, ingredient_amoun
1357
  "๋น„๊ณ ": "COA ๋˜๋Š” ์›๋ฃŒ๊ทœ๊ฒฉ์„œ์—์„œ furocoumarines ํ™•์ธ ๊ถŒ์žฅ",
1358
  }
1359
 
1360
- # EU ์ •์œ ๋ฅ˜๋Š” ๊ตฌ์„ฑ ์•Œ๋ ˆ๋ฅด๊ฒ ์ž๋ฃŒ๋ฅผ ๋ณ„๋„๋กœ ํ™•์ธํ•˜๋„๋ก ํ‘œ์‹œ
1361
  if ckey == "EU" and ("essential oil" in norm or "leaf oil" in norm or "peel oil" in norm):
1362
  amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1363
  return {
@@ -1366,7 +1365,6 @@ def evaluate_local_rules(country, component, ingredient_totals, ingredient_amoun
1366
  "๋น„๊ณ ": "ํ•˜์œ„ ๊ตฌ์„ฑ์„ฑ๋ถ„์— Limonene, Linalool, Citral ๋“ฑ ์กด์žฌ ์‹œ ์ด๋Ÿ‰ ๊ธฐ์ค€์œผ๋กœ ํ‘œ์‹œ๊ธฐ์ค€ ๊ฒ€ํ† ",
1367
  }
1368
 
1369
- # EU ํ•ฉ์„ฑ๊ณ ๋ถ„์ž ๋ฏธ์„ธ์ž…์ž ํ•ด๋‹น์„ฑ ๊ฒ€ํ† 
1370
  if ckey == "EU" and any(x in norm for x in ["carbomer", "copolymer", "crosspolymer", "polymer"]):
1371
  amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1372
  return {
@@ -1375,7 +1373,6 @@ def evaluate_local_rules(country, component, ingredient_totals, ingredient_amoun
1375
  "๋น„๊ณ ": "๊ณ ์ฒด ์ž…์ž์„ฑ, ์šฉํ•ด์„ฑ, ์ƒ๋ถ„ํ•ด์„ฑ, ์ž…์ž ํฌ๊ธฐ ๋“ฑ ์›๋ฃŒ์ž๋ฃŒ ํ™•์ธ ํ•„์š”",
1376
  }
1377
 
1378
- # ํ•œ๊ตญ ๊ธฐ๋Šฅ์„ฑํ™”์žฅํ’ˆ ์ฃผ์„ฑ๋ถ„ ํ‘œ์‹œยท๊ด‘๊ณ  ๊ฒ€ํ† 
1379
  if ckey == "KOREA" and norm == "niacinamide":
1380
  amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1381
  return {
@@ -1392,7 +1389,6 @@ def evaluate_local_rules(country, component, ingredient_totals, ingredient_amoun
1392
  "๋น„๊ณ ": "๋‹จ์ˆœ ์ „์„ฑ๋ถ„ ๋ฐฐํ•ฉ ์ž์ฒด๊ฐ€ ์•„๋‹ˆ๋ผ ์ฃผ๋ฆ„๊ฐœ์„  ๊ธฐ๋Šฅ์„ฑ ํ‘œ์‹œยท๊ด‘๊ณ  ์—ฌ๋ถ€์— ๋”ฐ๋ผ ๊ฒ€ํ† ",
1393
  }
1394
 
1395
- # ํ•จ๋Ÿ‰๊ฐ’์ด ๋น„์–ด ์žˆ๋Š” ์„ฑ๋ถ„์€ ์ œํ•œ ์—†์Œ์œผ๋กœ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š๊ณ  ํ™•์ธ ํ•„์š”๋กœ ์ฒ˜๋ฆฌ
1396
  if amount is None:
1397
  return {
1398
  "๋Œ€ํ‘œ INCI": inci_name or "-",
@@ -1403,52 +1399,13 @@ def evaluate_local_rules(country, component, ingredient_totals, ingredient_amoun
1403
  return None
1404
 
1405
 
1406
- # =========================
1407
- # ๊ตญ๊ฐ€๋ณ„ ๊ทœ์ œ ํŒ๋‹จ - ๊ตฌ์„ฑ์„ฑ๋ถ„ ๋‹จ์œ„
1408
- # =========================
1409
- def evaluate_component_with_llm(country, material, component, llm):
1410
- db = build_database(country)
1411
-
1412
- inci_name = safe_str(component.get("INCI Name", ""))
1413
- korean_name = safe_str(component.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", ""))
1414
- amount = component.get("amount_float")
1415
- amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1416
-
1417
- if not inci_name and not korean_name:
1418
- return {
1419
- "๋Œ€ํ‘œ INCI": "-",
1420
- "๊ฒฐ๊ณผ": "",
1421
- "๋น„๊ณ ": "-",
1422
- }
1423
-
1424
- if not db:
1425
- return {
1426
- "๋Œ€ํ‘œ INCI": inci_name or "-",
1427
- "๊ฒฐ๊ณผ": "๊ทœ์ œ๋ฌธ์„œ ์—†์Œ",
1428
- "๋น„๊ณ ": "-",
1429
- }
1430
-
1431
- # ๊ทœ์ œ ํด๋” signature๋ฅผ cache key์— ํฌํ•จํ•œ๋‹ค.
1432
- # ํด๋” ๋‚ด ํŒŒ์ผ์ด ์ถ”๊ฐ€/์ˆ˜์ •/์‚ญ์ œ๋˜๋ฉด signature๊ฐ€ ๋ฐ”๋€Œ๋ฏ€๋กœ ์ด์ „ GPT ๊ฒฐ๊ณผ ์บ์‹œ๋ฅผ ์žฌ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค.
1433
- db_signature_hash = get_current_db_signature_hash(country)
1434
-
1435
- cache_key = (
1436
- str(country),
1437
- str(db_signature_hash),
1438
- inci_name.lower(),
1439
- korean_name.lower(),
1440
- amount_text,
1441
- )
1442
-
1443
- with CACHE_LOCK:
1444
- if cache_key in EVAL_CACHE:
1445
- return EVAL_CACHE[cache_key]
1446
-
1447
- trade_ko = material["Trade name(๊ตญ๋ฌธ)"]
1448
- trade_en = material["Trade name(์˜๋ฌธ)"]
1449
 
 
1450
  regulatory_hints = []
1451
- inci_text = inci_name.lower()
1452
 
1453
  if any(x in inci_text for x in ["retinol", "retinyl", "retinal", "retinoate", "vitamin a"]):
1454
  regulatory_hints.append("retinol retinyl palmitate retinal retinoid vitamin A retinol equivalent RE")
@@ -1500,6 +1457,39 @@ def evaluate_component_with_llm(country, material, component, llm):
1500
  ]):
1501
  regulatory_hints.append("AHA BHA PHA acid maximum concentration pH restriction")
1502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1503
  search_text = f"""
1504
  ๊ตญ๊ฐ€: {country}
1505
  ์›๋ฃŒ๋ช… ๊ตญ๋ฌธ: {trade_ko}
@@ -1511,7 +1501,7 @@ def evaluate_component_with_llm(country, material, component, llm):
1511
  ๊ทœ์ œ๊ตฐ ํžŒํŠธ: {' / '.join(regulatory_hints)}
1512
  """
1513
 
1514
- docs = db.similarity_search(search_text, k=SEARCH_K)
1515
  context = "\n".join([d.page_content for d in docs])
1516
 
1517
  prompt = f"""
@@ -1549,52 +1539,15 @@ Leave-on ๊ธฐ์ค€๊ณผ Wash-off ๊ธฐ์ค€์„ ๋ชจ๋‘ ํ™•์ธํ•ด.
1549
  - ๊ด€๋ จ ๊ทœ์ œ๊ฐ€ ์—†์œผ๋ฉด ๊ฒฐ๊ณผ๋Š” ์ •ํ™•ํžˆ "์ œํ•œ ์—†์Œ (ํ†ต๊ณผ)" ๋กœ ์ž‘์„ฑํ•ด.
1550
  - ๊ทœ์ œ๊ฐ€ ์žˆ์œผ๋ฉด ์ œํ•œ ์—†์Œ์ด๋ผ๊ณ  ์“ฐ์ง€ ๋ง๊ณ  ๋ฐ˜๋“œ์‹œ ๊ทœ์ œ๊ตฐ๋ช…, ํ˜„์žฌ ํ•จ๋Ÿ‰, Leave-on ๊ธฐ์ค€, Wash-off ๊ธฐ์ค€์„ ๋ชจ๋‘ ์ ์–ด.
1551
  - Leave-on๊ณผ Wash-off ๊ธฐ์ค€์ด ๋™์ผํ•˜๋ฉด "Leave-on/Wash-off ๊ธฐ์ค€ ๋™์ผ"์ด๋ผ๊ณ  ์ ์–ด.
1552
- - ํ•œ๋„ ์ด๋‚ด๋ผ๋„ ๊ทœ์ œ๊ฐ€ ์กด์žฌํ•˜๋ฉด ์ œํ•œ ์—†์Œ์ด ์•„๋‹ˆ๋ผ ์•„๋ž˜ ์˜ˆ์‹œ์ฒ˜๋Ÿผ ์ž‘์„ฑํ•ด.
1553
-
1554
- ์ข‹์€ ์˜ˆ์‹œ 1:
1555
- ๋Œ€ํ‘œ INCI: Limonene
1556
- ๊ฒฐ๊ณผ: ํ–ฅ๋ฃŒ ์•Œ๋ ˆ๋ฅด๊ฒ / Limonene 0.033385%, Leave-on ํ‘œ์‹œ๊ธฐ์ค€ 0.001% ์ดˆ๊ณผ(ํ‘œ์‹œ ํ•„์š”), Wash-off ํ‘œ์‹œ๊ธฐ์ค€ 0.01% ์ดˆ๊ณผ(ํ‘œ์‹œ ํ•„์š”)
1557
- ๋น„๊ณ : -
1558
-
1559
- ์ข‹์€ ์˜ˆ์‹œ 2:
1560
- ๋Œ€ํ‘œ INCI: Phenoxyethanol
1561
- ๊ฒฐ๊ณผ: ๋ณด์กด์ œ ๊ทœ์ œ / Phenoxyethanol 0.8%, Leave-on/Wash-off ํ•œ๋„ 1.0% ์ด๋‚ด(ํ†ต๊ณผ)
1562
- ๋น„๊ณ : -
1563
-
1564
- ์ข‹์€ ์˜ˆ์‹œ 3:
1565
- ๋Œ€ํ‘œ INCI: Aqua
1566
- ๊ฒฐ๊ณผ: ์ œํ•œ ์—†์Œ (ํ†ต๊ณผ)
1567
- ๋น„๊ณ : -
1568
-
1569
- ๋‚˜์œ ์˜ˆ์‹œ:
1570
- ๋Œ€ํ‘œ INCI: Citral
1571
- ๊ฒฐ๊ณผ: ๊ทœ์ œ๋ช… / ์ด๋Ÿ‰ ๊ณ„์‚ฐ, ํ•œ๋„ ์ด๋‚ด(ํ†ต๊ณผ)
1572
- ๋น„๊ณ : -
1573
  """
1574
 
1575
  try:
1576
  response = llm.invoke(prompt).content
1577
  parsed = parse_country_response(response)
 
1578
 
1579
- bad_tokens = [
1580
- "๊ทœ์ œ๋ช…",
1581
- "์ด๋Ÿ‰ ๊ณ„์‚ฐ",
1582
- "๊ทœ์ œ / ์ด๋Ÿ‰",
1583
- "{๊ทœ์ œ๊ตฐ๋ช…}",
1584
- "{์„ฑ๋ถ„๋ช…",
1585
- "{ํ•จ๋Ÿ‰}",
1586
- "{๊ธฐ์ค€์น˜}",
1587
- "placeholder",
1588
- ]
1589
-
1590
- if any(token in parsed["๊ฒฐ๊ณผ"] for token in bad_tokens):
1591
- parsed["๊ฒฐ๊ณผ"] = "ํ™•์ธ ํ•„์š” / ๊ทœ์ œ ์„ธ๋ถ€ ๊ณ„์‚ฐ ์žฌํ™•์ธ ํ•„์š”"
1592
- if parsed["๋น„๊ณ "] == "-":
1593
- parsed["๋น„๊ณ "] = "๊ตฌ์ฒด ํ•œ๋„ ๋˜๋Š” ์ด๋Ÿ‰ ๊ณ„์‚ฐ๊ฐ’ ํ™•์ธ ํ•„์š”"
1594
-
1595
- with CACHE_LOCK:
1596
- EVAL_CACHE[cache_key] = parsed
1597
-
1598
  return parsed
1599
 
1600
  except Exception as e:
@@ -1605,17 +1558,186 @@ Leave-on ๊ธฐ์ค€๊ณผ Wash-off ๊ธฐ์ค€์„ ๋ชจ๋‘ ํ™•์ธํ•ด.
1605
  }
1606
 
1607
 
1608
- def evaluate_one_component_country(country, material, component, llm, ingredient_totals, ingredient_amount_parts):
1609
- local_result = evaluate_local_rules(country, component, ingredient_totals, ingredient_amount_parts)
1610
- if local_result is not None:
1611
- return local_result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1612
 
1613
- return evaluate_component_with_llm(country, material, component, llm)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1614
 
 
1615
 
1616
- # =========================
 
1617
  # ์—‘์…€ ์Šคํƒ€์ผ ๋ฐ ๋ณ‘ํ•ฉ
1618
- # =========================
 
1619
  def style_excel(path, selected_countries, merge_ranges):
1620
  wb = load_workbook(path)
1621
  ws = wb.active
@@ -1636,17 +1758,11 @@ def style_excel(path, selected_countries, merge_ranges):
1636
 
1637
  headers = [c.value for c in ws[1]]
1638
 
1639
- # ๊ตญ๊ฐ€ ๊ฒฐ๊ณผ ์ปฌ๋Ÿผ์€ ๊ตฌ์„ฑ์„ฑ๋ถ„๋ณ„ ๊ฒฐ๊ณผ๊ฐ€ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ๋ณ‘ํ•ฉํ•˜์ง€ ์•Š๋Š”๋‹ค.
1640
- # ๊ฐ™์€ ์›๋ฃŒ(NO) ์•ˆ์—์„œ ๊ณตํ†ต์œผ๋กœ ์ ์šฉ๋˜๋Š” ๊ฐ’๋งŒ ๋ณ‘ํ•ฉํ•œ๋‹ค.
1641
- # - NO / Trade name: ์›๋ฃŒ ๋‹จ์œ„ ๊ณตํ†ต๊ฐ’
1642
- # - Contents(w/w %): ์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰์ด๋ฏ€๋กœ ๊ฐ™์€ NO ๊ทธ๋ฃน ์ „์ฒด์— ๊ณตํ†ต ์ ์šฉ
1643
- # - In formula(w/w %): ๊ตฌ์„ฑ์„ฑ๋ถ„๋ณ„ ์ตœ์ข… ํ•จ๋Ÿ‰์ด๋ฏ€๋กœ ๋ณ‘ํ•ฉํ•˜์ง€ ์•Š์Œ
1644
  merge_cols = []
1645
  for name in ["NO", "Trade name(๊ตญ๋ฌธ)", "Trade name(์˜๋ฌธ)", "Contents\n(w/w %)"]:
1646
  if name in headers:
1647
  merge_cols.append(headers.index(name) + 1)
1648
 
1649
- # ํ˜น์‹œ ํ—ค๋” ์ค„๋ฐ”๊ฟˆ/๊ณต๋ฐฑ ํ˜•ํƒœ๊ฐ€ ๋‹ฌ๋ผ๋„ Contents ์ปฌ๋Ÿผ์€ ๋ณ‘ํ•ฉ๋˜๋„๋ก ๋ณด์ •
1650
  for idx, header in enumerate(headers, start=1):
1651
  header_text = str(header or "").replace("\n", " ").strip().lower()
1652
  if "contents" in header_text and "w/w" in header_text and idx not in merge_cols:
@@ -1660,7 +1776,6 @@ def style_excel(path, selected_countries, merge_ranges):
1660
 
1661
  note_col = headers.index("๋น„๊ณ ") + 1 if "๋น„๊ณ " in headers else None
1662
 
1663
- # ๊ธฐ๋ณธ ์Šคํƒ€์ผ
1664
  for row in range(1, ws.max_row + 1):
1665
  for col in range(1, ws.max_column + 1):
1666
  cell = ws.cell(row=row, column=col)
@@ -1671,8 +1786,6 @@ def style_excel(path, selected_countries, merge_ranges):
1671
  cell.fill = header_fill
1672
  cell.font = black_bold_font
1673
 
1674
- # ๊ตญ๊ฐ€ ์ปฌ๋Ÿผ ์Šคํƒ€์ผ
1675
- # ์š”์ฒญ์‚ฌํ•ญ: ์ œํ•œ ์—†์Œ์ด ์•„๋‹Œ ๋ชจ๋“  ๊ฒฐ๊ณผ๋Š” ๋นจ๊ฐ„์ƒ‰ + ๋ณผ๋“œ + ๋…ธ๋ž€์ƒ‰ ์ฑ„์šฐ๊ธฐ
1676
  for row in range(2, ws.max_row + 1):
1677
  no_value = str(ws.cell(row=row, column=1).value or "").strip()
1678
  is_total_row = no_value == "ํ•ฉ๊ณ„"
@@ -1702,7 +1815,6 @@ def style_excel(path, selected_countries, merge_ranges):
1702
  note_cell.fill = yellow_fill
1703
  note_cell.font = red_font
1704
 
1705
- # ๊ทธ๋ฃน ๋ณ‘ํ•ฉ
1706
  for start_row, end_row in merge_ranges:
1707
  if end_row <= start_row:
1708
  continue
@@ -1720,7 +1832,6 @@ def style_excel(path, selected_countries, merge_ranges):
1720
  except Exception:
1721
  pass
1722
 
1723
- # ์—ด ๋„ˆ๋น„
1724
  for col_cells in ws.columns:
1725
  col_letter = col_cells[0].column_letter
1726
  col_idx = col_cells[0].column
@@ -1743,9 +1854,10 @@ def style_excel(path, selected_countries, merge_ranges):
1743
  wb.save(path)
1744
 
1745
 
1746
- # =========================
1747
  # ๋ฉ”์ธ ์ฒ˜๋ฆฌ
1748
- # =========================
 
1749
  def process(countries, file):
1750
  try:
1751
  if not file:
@@ -1768,17 +1880,16 @@ def process(countries, file):
1768
  temperature=0,
1769
  )
1770
 
1771
- output_rows = []
1772
  row_items = []
1773
  merge_ranges = []
1774
 
1775
- # 1) ํ–‰ ๊ตฌ์กฐ ๋จผ์ € ์ƒ์„ฑ
1776
  for material in grouped_materials:
1777
  components = material["Components"]
1778
- start_excel_row = len(output_rows) + 2
1779
 
1780
  for idx, comp in enumerate(components):
1781
  is_first = idx == 0
 
1782
 
1783
  row_data = {
1784
  "NO": material["NO"] if is_first else "",
@@ -1788,76 +1899,77 @@ def process(countries, file):
1788
  "INCI Name": comp["INCI Name"],
1789
  "Contents\n(w/w %)": comp["Contents(w/w %)"] if is_first else "",
1790
  "In formula\n(w/w %)": comp["In formula(w/w %)"],
1791
- "๋น„๊ณ ": "-",
1792
  }
1793
 
1794
- output_rows.append(row_data)
1795
- row_items.append((material, comp))
 
 
 
 
 
1796
 
1797
- end_excel_row = len(output_rows) + 1
1798
  merge_ranges.append((start_excel_row, end_excel_row))
1799
 
1800
- # 2) ๊ตญ๊ฐ€๋ณ„ ํ‰๊ฐ€ ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ
1801
- note_map = defaultdict(list)
1802
- tasks = []
 
 
 
 
 
 
 
 
1803
 
1804
- for row_idx, (material, comp) in enumerate(row_items):
1805
- for country in countries:
1806
- tasks.append((row_idx, country, material, comp))
1807
 
1808
- def run_eval(task):
1809
- row_idx, country, material, comp = task
1810
- col_name = display_country(country)
 
 
 
 
 
 
 
1811
 
1812
- result = evaluate_one_component_country(
1813
  country=country,
1814
- material=material,
1815
- component=comp,
1816
  llm=llm,
1817
- ingredient_totals=ingredient_totals,
1818
- ingredient_amount_parts=ingredient_amount_parts,
1819
  )
1820
 
1821
- return row_idx, col_name, result
 
 
1822
 
1823
- if MAX_WORKERS <= 1:
1824
- for task in tasks:
1825
- row_idx, col_name, result = run_eval(task)
1826
- output_rows[row_idx][col_name] = result.get("๊ฒฐ๊ณผ", "")
1827
 
1828
- note = safe_str(result.get("๋น„๊ณ ", "-"))
1829
- if note and note != "-":
1830
- note_map[row_idx].append(f"{col_name}: {note}")
1831
-
1832
- else:
1833
- with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
1834
- future_map = {
1835
- executor.submit(run_eval, task): task
1836
- for task in tasks
1837
- }
1838
 
1839
- for future in as_completed(future_map):
1840
- try:
1841
- row_idx, col_name, result = future.result()
1842
- except Exception as e:
1843
- row_idx, country, _, _ = future_map[future]
1844
- col_name = display_country(country)
1845
- result = {
1846
- "๊ฒฐ๊ณผ": "ํ™•์ธ ํ•„์š”",
1847
- "๋น„๊ณ ": str(e),
1848
- }
1849
 
1850
- output_rows[row_idx][col_name] = result.get("๊ฒฐ๊ณผ", "")
 
 
1851
 
1852
- note = safe_str(result.get("๋น„๊ณ ", "-"))
1853
- if note and note != "-":
1854
- note_map[row_idx].append(f"{col_name}: {note}")
1855
 
1856
- # 3) ๋น„๊ณ  ๋ฐ˜์˜
1857
- for row_idx, notes in note_map.items():
1858
- output_rows[row_idx]["๋น„๊ณ "] = " / ".join(notes) if notes else "-"
 
1859
 
1860
- # 4) ํ•ฉ๊ณ„ ํ–‰: ์›๋ณธ footer๋Š” ์ œ๊ฑฐํ•˜๊ณ , ์‹ค์ œ ์ˆ˜์น˜ ํ•ฉ๊ณ„๋งŒ ์ƒˆ๋กœ ์ƒ์„ฑ
1861
  country_cols = [display_country(c) for c in countries]
1862
 
1863
  total_row = {
@@ -1909,10 +2021,8 @@ def process(countries, file):
1909
  "- In formula(w/w %)๋Š” ๊ตฌ์„ฑ์„ฑ๋ถ„๋ณ„ ์ตœ์ข… ํ•จ๋Ÿ‰์ด๋ฏ€๋กœ ๋ณ‘ํ•ฉํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.\n"
1910
  "- ๊ตญ๊ฐ€ ๊ฒฐ๊ณผ ์นธ์€ '์ œํ•œ ์—†์Œ (ํ†ต๊ณผ)'๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ๋นจ๊ฐ„์ƒ‰ ๋ณผ๋“œ + ๋…ธ๋ž€์ƒ‰์œผ๋กœ ํ‘œ์‹œํ–ˆ์Šต๋‹ˆ๋‹ค.\n"
1911
  "- ํ–ฅ๋ฃŒ ์•Œ๋ ˆ๋ฅด๊ฒ์€ ์ด๋Ÿ‰ ๊ธฐ์ค€์œผ๋กœ Leave-on 0.001%, Wash-off 0.01% ๊ธฐ์ค€์„ ํ•จ๊ป˜ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค.\n"
1912
- "- ๊ตญ๊ฐ€/์ฑ„๋„ ํด๋” ๋ฐ ๊ทœ์ œ ํŒŒ์ผ์€ ๋‹ค์Œ ๋ถ„์„ ์‹œ ์ž๋™์œผ๋กœ ๋ณ€๊ฒฝ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜๊ณ  ์žฌ์ƒ‰์ธํ•ฉ๋‹ˆ๋‹ค.\n"
1913
- "- FAISS ๊ทœ์ œ DB๋Š” ๋””์Šคํฌ ์บ์‹œ๋กœ ์ €์žฅ๋˜์–ด ๊ฐ™์€ ํŒŒ์ผ ์ƒํƒœ์—์„œ๋Š” ๋‹ค์Œ ์‹คํ–‰๋ถ€ํ„ฐ ๋” ๋น ๋ฅด๊ฒŒ ๋ถˆ๋Ÿฌ์˜ต๋‹ˆ๋‹ค.\n"
1914
- f"- ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ worker ์ˆ˜: {MAX_WORKERS}\n"
1915
- f"- ๊ทœ์ œ ๊ฒ€์ƒ‰ ๋ฌธ์„œ ์ˆ˜ SEARCH_K: {SEARCH_K}\n"
1916
  f"- ์ง€์› ๊ทœ์ œ ํŒŒ์ผ ํ™•์žฅ์ž: {', '.join(sorted(SUPPORTED_REG_FILE_EXTENSIONS))}"
1917
  )
1918
 
@@ -1924,9 +2034,10 @@ def process(countries, file):
1924
  return None, None, f"โŒ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}\n\n{tb[-3000:]}"
1925
 
1926
 
1927
- # =========================
1928
  # GRADIO UI
1929
- # =========================
 
1930
  with gr.Blocks(css=custom_css) as demo:
1931
  gr.Markdown("# ๐ŸŒ reBom Regulatory Screening AI")
1932
  gr.Markdown("### ๊ธ€๋กœ๋ฒŒ ํ™”์žฅํ’ˆ ๊ทœ์ œ ๊ธฐ๋ฐ˜ ์ „์„ฑ๋ถ„ ์Šคํฌ๋ฆฌ๋‹")
@@ -1961,18 +2072,12 @@ with gr.Blocks(css=custom_css) as demo:
1961
  lines=12,
1962
  )
1963
 
1964
- # ์ˆ˜๋™ ์ƒˆ๋กœ๊ณ ์นจ:
1965
- # - ์ƒˆ ๊ตญ๊ฐ€ ํด๋” ๋ฐ˜์˜
1966
- # - ๊ทœ์ œ DB ๋ฉ”๋ชจ๋ฆฌ ์บ์‹œ ์ดˆ๊ธฐํ™”
1967
- # - ํ‰๊ฐ€ ์บ์‹œ ์ดˆ๊ธฐํ™”
1968
- # - ๋””์Šคํฌ FAISS ์บ์‹œ๋Š” ์œ ์ง€
1969
  refresh.click(
1970
  fn=refresh_country_choices_and_clear_cache,
1971
  inputs=country,
1972
  outputs=country,
1973
  )
1974
 
1975
- # Gradio ๋ฒ„์ „์ด Timer๋ฅผ ์ง€์›ํ•˜๋ฉด 15์ดˆ๋งˆ๋‹ค ๊ตญ๊ฐ€ ํด๋” ๋ชฉ๋ก ์ž๋™ ๊ฐฑ์‹ 
1976
  try:
1977
  auto_refresh_timer = gr.Timer(15)
1978
 
@@ -1997,30 +2102,35 @@ with gr.Blocks(css=custom_css) as demo:
1997
  )
1998
 
1999
 
2000
- # ๐Ÿ” ํŒ€์›๋“ค์˜ ์•„์ด๋””์™€ ๋น„๋ฐ€๋ฒˆํ˜ธ ๋ชฉ๋ก ์„ค์ •
2001
- # ๊ด„ํ˜ธ ์•ˆ์— ("์•„์ด๋””", "๋น„๋ฐ€๋ฒˆํ˜ธ") ํ˜•ํƒœ๋กœ ๊ณ„์† ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
 
 
2002
  allowed_users = [
2003
  ("jin21i@rebom.kr", "qwer0515!"),
2004
  ("jkh@rebom.kr", "rebom123!"),
2005
- ("member1", "0000"),
2006
  ("member2", "1111"),
2007
  ]
2008
 
2009
 
2010
- # =========================
2011
  # ์•ฑ ์‹คํ–‰
2012
- # =========================
2013
- # Gradio ๋ฒ„์ „์— ๋”ฐ๋ผ ssr_mode ๋ฏธ์ง€์›์ผ ์ˆ˜ ์žˆ์–ด fallback ์ฒ˜๋ฆฌ
 
 
2014
  try:
2015
  demo.launch(
2016
  server_name="0.0.0.0",
2017
  server_port=7860,
2018
  ssr_mode=False,
2019
  auth=allowed_users,
 
2020
  )
2021
  except TypeError:
2022
  demo.launch(
2023
  server_name="0.0.0.0",
2024
  server_port=7860,
2025
  auth=allowed_users,
 
2026
  )
 
1
+ # ============================================================
2
+ # reBom Regulatory Screening AI
3
+ # - ๊ตญ๊ฐ€/์ฑ„๋„ ํด๋” ์ž๋™ ์ธ์‹
4
+ # - ๊ทœ์ œ ํŒŒ์ผ ์ž๋™ ๋ณ€๊ฒฝ ๊ฐ์ง€
5
+ # - FAISS ๋ฒกํ„ฐ DB ๋””์Šคํฌ ์บ์‹œ
6
+ # - ํ–ฅ๋ฃŒ ์•Œ๋ ˆ๋ฅด๊ฒ/๊ธฐ๋Šฅ์„ฑ/์ •์œ ๋ฅ˜/๊ณ ๋ถ„์ž ๋กœ์ปฌ ๊ทœ์น™ ์šฐ์„  ํŒ์ •
7
+ # - ๊ตญ๊ฐ€๋ณ„ batch GPT ํŒ์ •์œผ๋กœ ์†๋„ ๊ฐœ์„ 
8
+ # - ๊ฒฐ๊ณผ ์—‘์…€ ๋ณ‘ํ•ฉ/์Šคํƒ€์ผ ์ ์šฉ
9
+ # - Gradio ๋กœ๊ทธ์ธ ์ธ์ฆ ์ ์šฉ
10
+ # - Gradio public share link ์ ์šฉ
11
+ # ============================================================
12
+
13
  import os
14
  import re
15
  import json
 
 
16
  import hashlib
17
  import traceback
 
18
  from collections import defaultdict
 
19
 
20
  import pandas as pd
21
  import pdfplumber
 
28
  from langchain_text_splitters import RecursiveCharacterTextSplitter
29
 
30
 
31
+ # ============================================================
32
  # ๊ธฐ๋ณธ ์„ค์ •
33
+ # ============================================================
34
+
35
  api_key = os.getenv("OPENAI_API_KEY")
36
  print("โœ… OPENAI_API_KEY ์ •์ƒ" if api_key else "โŒ OPENAI_API_KEY ์—†์Œ")
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  VECTOR_DB_CACHE = {}
 
 
39
  EVAL_CACHE = {}
40
+ EMBEDDINGS_CACHE = None
41
 
42
+ FAISS_CACHE_DIR = ".faiss_cache"
 
 
43
 
 
44
  SUPPORTED_REG_FILE_EXTENSIONS = {
45
  ".pdf",
46
  ".txt",
 
49
  ".xls",
50
  }
51
 
 
52
  COUNTRY_ORDER = [
53
  "ASEAN",
54
  "CALIFORNIA",
 
114
  "ULTA": "ULTA",
115
  }
116
 
 
117
  COUNTRY_FOLDER_ALIASES = {
118
  "ํ•œ๊ตญ": "KOREA",
119
  "KOREA": "KOREA",
 
162
  "ULTA": "ULTA",
163
  }
164
 
165
+ # GPT batch ์ฒ˜๋ฆฌ ์„ค์ •
166
+ BATCH_SIZE = 25
167
+ RAG_TOP_K_BATCH = 10
168
+ RAG_TOP_K_SINGLE = 5
169
+
170
  custom_css = """
171
  #country_checks .wrap,
172
  #country_checks .checkbox-group {
 
188
  """
189
 
190
 
191
+ # ============================================================
192
  # ๋กœ์ปฌ ๊ณ ์ • ๊ทœ์น™
193
+ # ============================================================
194
+
195
  FRAGRANCE_ALLERGEN_RULES = {
196
  "limonene": {
197
  "label": "Limonene",
 
285
  FRAGRANCE_ALIAS_TO_CANONICAL[alias.lower()] = canonical_name
286
 
287
 
288
+ # ============================================================
289
  # ๊ณตํ†ต ์œ ํ‹ธ
290
+ # ============================================================
291
+
292
  def safe_str(x):
293
  if pd.isna(x):
294
  return ""
 
417
  return norm
418
 
419
 
420
+ def stable_hash(obj):
421
+ text = json.dumps(obj, ensure_ascii=False, sort_keys=True, default=str)
422
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
423
+
424
+
425
+ def safe_filename(text):
426
+ text = safe_str(text)
427
+ text = re.sub(r"[^a-zA-Z0-9๊ฐ€-ํžฃ._() -]", "_", text)
428
+ text = text.strip().replace(" ", "_")
429
+ return text or "unknown"
430
+
431
+
432
+ def chunk_list(items, size):
433
+ for i in range(0, len(items), size):
434
+ yield items[i:i + size]
435
+
436
+
437
+ def get_embeddings():
438
+ global EMBEDDINGS_CACHE
439
+
440
+ if EMBEDDINGS_CACHE is None:
441
+ EMBEDDINGS_CACHE = OpenAIEmbeddings(model="text-embedding-3-small")
442
+
443
+ return EMBEDDINGS_CACHE
444
+
445
+
446
+ def make_eval_cache_key(country, component):
447
+ amount = component.get("amount_float")
448
+ amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
449
+ db_signature = get_current_db_signature(country)
450
+
451
+ return (
452
+ str(country),
453
+ str(db_signature),
454
+ safe_str(component.get("INCI Name", "")).lower(),
455
+ safe_str(component.get("ํ•œ๊ธ€ ์„ฑ๏ฟฝ๏ฟฝ๋ช…", "")).lower(),
456
+ amount_text,
457
+ )
458
+
459
+
460
+ # ============================================================
461
+ # ๊ตญ๊ฐ€/์ฑ„๋„ ํด๋” ์ž๋™ ์ธ์‹
462
+ # ============================================================
463
 
464
+ def resolve_country_folder(country):
465
  if not country or country == "ํด๋” ์—†์Œ":
466
  return None
467
 
 
487
  if item and item not in seen:
488
  seen.append(item)
489
 
 
490
  for item in seen:
491
  if os.path.isdir(item):
492
  return item
493
 
 
494
  folder_map = {
495
  f.lower(): f
496
  for f in os.listdir(".")
 
506
 
507
 
508
  def get_country_folders():
 
 
 
 
 
 
509
  exclude = [
510
  ".git",
511
  ".cache",
 
524
 
525
  existing_set = set(existing_folders)
526
 
 
527
  ordered = [c for c in COUNTRY_ORDER if c in existing_set]
 
 
528
  extras = sorted([f for f in existing_folders if f not in COUNTRY_ORDER])
529
 
 
530
  if not ordered and not extras:
531
  return COUNTRY_ORDER.copy()
532
 
533
  return ordered + extras
534
 
535
 
536
+ def refresh_country_choices_keep_selection(current_values=None):
537
+ choices = get_country_folders()
538
+ current_values = current_values or []
539
+ kept_values = [v for v in current_values if v in choices]
540
+
541
+ return gr.update(
542
+ choices=choices,
543
+ value=kept_values,
544
+ )
545
+
546
+
547
+ def refresh_country_choices_and_clear_cache(current_values=None):
548
+ VECTOR_DB_CACHE.clear()
549
+ EVAL_CACHE.clear()
550
+
551
+ return refresh_country_choices_keep_selection(current_values)
552
+
553
+
554
+ # ============================================================
555
+ # ์—‘์…€ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
556
+ # ============================================================
557
+
558
  def preview_excel(file):
559
  if not file:
560
  return None
 
565
  return pd.DataFrame({"์˜ค๋ฅ˜": [str(e)]})
566
 
567
 
568
+ # ============================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
569
  # ์ปฌ๋Ÿผ ์ž๋™ ์ธ์‹
570
+ # ============================================================
571
+
572
  def find_best_col(df, keywords, default_index=None, exclude_cols=None):
573
  exclude_cols = exclude_cols or []
574
  scores = []
 
675
 
676
 
677
  def find_main_columns(df):
 
 
 
 
 
 
678
  no_col = find_best_col(df, ["no", "๋ฒˆํ˜ธ", "์ˆœ๋ฒˆ"], default_index=0)
679
 
680
  trade_ko_col = find_best_col(
 
721
  prefer_many_values=True
722
  )
723
 
 
724
  if contents_col == formula_col:
725
  numeric_cols = []
726
  for col in df.columns:
727
  if col in [no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col]:
728
  continue
729
+
730
  values = df[col].dropna()
731
  if values.empty:
732
  continue
733
+
734
  count = values.apply(is_numeric_like).sum()
735
  if count > 0:
736
  numeric_cols.append(col)
 
750
  }
751
 
752
 
753
+ # ============================================================
754
+ # ์—‘์…€ ์›๋ณธ ์ •๏ฟฝ๏ฟฝ๏ฟฝ / ๊ทธ๋ฃนํ™” / ํ•ฉ๊ณ„
755
+ # ============================================================
 
 
 
 
 
 
 
 
756
 
757
+ def clean_input_df(df, cols):
758
  no_col = cols["no_col"]
759
  trade_ko_col = cols["trade_ko_col"]
760
  trade_en_col = cols["trade_en_col"]
 
839
 
840
 
841
  def compute_ingredient_totals(cleaned_df, cols):
 
 
 
 
 
842
  inci_col = cols["inci_col"]
843
  formula_col = cols["formula_col"]
844
 
 
865
  return totals, amount_parts
866
 
867
 
868
+ def make_grouped_materials(df):
869
+ cols = find_main_columns(df)
870
+ cleaned_df = clean_input_df(df, cols)
871
+
872
+ no_col = cols["no_col"]
873
+ trade_ko_col = cols["trade_ko_col"]
874
+ trade_en_col = cols["trade_en_col"]
875
+ korean_ing_col = cols["korean_ing_col"]
876
+ inci_col = cols["inci_col"]
877
+ contents_col = cols["contents_col"]
878
+ formula_col = cols["formula_col"]
879
+
880
+ work_df = cleaned_df.copy()
881
+
882
+ for col in [no_col, trade_ko_col, trade_en_col]:
883
+ if col and col in work_df.columns:
884
+ work_df[col] = work_df[col].ffill()
885
+
886
+ group_keys = [c for c in [no_col, trade_ko_col, trade_en_col] if c and c in work_df.columns]
887
+
888
+ grouped_materials = []
889
+
890
+ for key, group in work_df.groupby(group_keys, dropna=True, sort=False):
891
+ if not isinstance(key, tuple):
892
+ key = (key,)
893
+
894
+ no_value = format_no(key[0]) if len(key) > 0 else ""
895
+ trade_ko = safe_str(key[1]) if len(key) > 1 else ""
896
+ trade_en = safe_str(key[2]) if len(key) > 2 else trade_ko
897
+
898
+ if no_value and not is_numeric_like(no_value):
899
+ continue
900
+
901
+ if not trade_ko and not trade_en:
902
+ continue
903
+
904
+ components = []
905
+ inci_list = []
906
+ final_amounts = []
907
+
908
+ for _, row in group.iterrows():
909
+ korean_ing = safe_str(row.get(korean_ing_col, "")) if korean_ing_col in row else ""
910
+ inci_name = safe_str(row.get(inci_col, "")) if inci_col in row else ""
911
+
912
+ if not inci_name and not korean_ing:
913
+ continue
914
+
915
+ contents_value = format_amount(row.get(contents_col)) if contents_col and contents_col in row else ""
916
+ formula_value = format_amount(row.get(formula_col)) if formula_col and formula_col in row else ""
917
+
918
+ comp = {
919
+ "ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…": korean_ing,
920
+ "INCI Name": inci_name,
921
+ "Contents(w/w %)": contents_value,
922
+ "In formula(w/w %)": formula_value,
923
+ "amount_float": to_number(row.get(formula_col)) if formula_col and formula_col in row else None,
924
+ }
925
+ components.append(comp)
926
+
927
+ if inci_name:
928
+ inci_list.append(inci_name)
929
+
930
+ if inci_name and formula_value:
931
+ final_amounts.append(f"{inci_name}: {formula_value}")
932
+
933
+ if not components:
934
+ continue
935
+
936
+ inci_list = list(dict.fromkeys(inci_list))
937
+
938
+ grouped_materials.append({
939
+ "NO": no_value,
940
+ "Trade name(๊ตญ๋ฌธ)": trade_ko,
941
+ "Trade name(์˜๋ฌธ)": trade_en,
942
+ "INCI_list": inci_list,
943
+ "Components": components,
944
+ "Final_amounts": final_amounts,
945
+ "Group_records": group.to_dict(orient="records"),
946
+ })
947
+
948
+ contents_total, formula_total = compute_totals(cleaned_df, cols)
949
+ ingredient_totals, ingredient_amount_parts = compute_ingredient_totals(cleaned_df, cols)
950
+
951
+ meta = {
952
+ "cols": cols,
953
+ "cleaned_df": cleaned_df,
954
+ "contents_total": contents_total,
955
+ "formula_total": formula_total,
956
+ "ingredient_totals": ingredient_totals,
957
+ "ingredient_amount_parts": ingredient_amount_parts,
958
+ }
959
+
960
+ return grouped_materials, meta
961
+
962
+
963
+ # ============================================================
964
  # ๊ทœ์ œ ํŒŒ์ผ ์ž๋™ ์ธ์‹ / ์ž๋™ ์žฌ์ƒ‰์ธ
965
+ # ============================================================
 
 
 
 
 
966
 
967
+ def get_regulatory_file_list(country_folder):
968
  files = []
969
 
970
  if not country_folder or not os.path.isdir(country_folder):
 
1003
 
1004
 
1005
  def get_regulatory_folder_signature(country_folder):
 
 
 
 
 
1006
  file_list = get_regulatory_file_list(country_folder)
1007
 
1008
  signature = tuple(
 
1031
 
1032
 
1033
  def extract_text_from_regulatory_file(file_item):
 
 
 
 
 
1034
  file_path = file_item["path"]
1035
  rel_path = file_item["relative_path"]
1036
  ext = file_item["ext"]
 
1072
  return "\n\n".join(texts)
1073
 
1074
 
1075
+ def get_faiss_cache_path(country_folder, signature_hash):
1076
+ os.makedirs(FAISS_CACHE_DIR, exist_ok=True)
1077
+
1078
+ folder_key = safe_filename(country_folder)
1079
+ cache_folder = f"{folder_key}_{signature_hash[:16]}"
1080
+
1081
+ return os.path.join(FAISS_CACHE_DIR, cache_folder)
1082
+
1083
+
1084
+ def get_current_db_signature(country):
1085
  folder = resolve_country_folder(country)
1086
  cached = VECTOR_DB_CACHE.get(folder)
1087
 
 
1091
  return None
1092
 
1093
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1094
  def build_database(country_folder):
1095
  country_folder = resolve_country_folder(country_folder)
1096
 
 
1100
  if not os.path.isdir(country_folder):
1101
  return None
1102
 
1103
+ current_signature, file_list = get_regulatory_folder_signature(country_folder)
 
 
 
 
 
 
 
 
1104
 
1105
+ if not file_list:
1106
+ VECTOR_DB_CACHE.pop(country_folder, None)
1107
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1108
 
1109
+ signature_hash = stable_hash(current_signature)
 
 
 
 
1110
 
1111
+ cached = VECTOR_DB_CACHE.get(country_folder)
 
1112
 
1113
+ if (
1114
+ isinstance(cached, dict)
1115
+ and cached.get("signature_hash") == signature_hash
1116
+ and cached.get("db") is not None
1117
+ ):
1118
+ return cached["db"]
1119
 
1120
+ embeddings = get_embeddings()
1121
+ cache_path = get_faiss_cache_path(country_folder, signature_hash)
1122
+ metadata_path = os.path.join(cache_path, "metadata.json")
 
1123
 
1124
+ if os.path.isdir(cache_path) and os.path.exists(metadata_path):
1125
  try:
1126
+ with open(metadata_path, "r", encoding="utf-8") as f:
1127
+ metadata = json.load(f)
1128
+
1129
+ if metadata.get("signature_hash") == signature_hash:
1130
+ print(f"โœ… FAISS ๋””์Šคํฌ ์บ์‹œ ๋กœ๋“œ: {country_folder}")
1131
+ db = FAISS.load_local(
1132
+ cache_path,
1133
+ embeddings,
1134
+ allow_dangerous_deserialization=True,
1135
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1136
 
1137
+ VECTOR_DB_CACHE[country_folder] = {
1138
+ "signature_hash": signature_hash,
1139
+ "db": db,
1140
+ "file_count": len(file_list),
1141
+ }
1142
 
1143
+ return db
 
 
1144
 
1145
+ except Exception as e:
1146
+ print(f"FAISS ๋””์Šคํฌ ์บ์‹œ ๋กœ๋“œ ์‹คํŒจ: {country_folder} / {e}")
1147
 
1148
+ print(f"๐Ÿ”„ ๊ทœ์ œ DB ์žฌ์ƒ‰์ธ: {country_folder} / ํŒŒ์ผ {len(file_list)}๊ฐœ")
1149
+ EVAL_CACHE.clear()
1150
 
1151
+ texts = []
 
 
1152
 
1153
+ splitter = RecursiveCharacterTextSplitter(
1154
+ chunk_size=900,
1155
+ chunk_overlap=120
1156
+ )
1157
 
1158
+ for file_item in file_list:
1159
+ raw_text = extract_text_from_regulatory_file(file_item)
 
1160
 
1161
+ if not raw_text:
1162
  continue
1163
 
1164
+ source_text = (
1165
+ f"[๊ตญ๊ฐ€/์ฑ„๋„: {country_folder}] "
1166
+ f"[์ถœ์ฒ˜ํŒŒ์ผ: {file_item['relative_path']}]\n"
1167
+ f"{raw_text}"
1168
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1169
 
1170
+ chunks = splitter.split_text(source_text)
1171
+ texts.extend(chunks)
1172
 
1173
+ if not texts:
1174
+ VECTOR_DB_CACHE.pop(country_folder, None)
1175
+ return None
1176
 
1177
+ db = FAISS.from_texts(
1178
+ texts,
1179
+ embeddings,
1180
+ )
1181
 
1182
+ try:
1183
+ os.makedirs(cache_path, exist_ok=True)
1184
+ db.save_local(cache_path)
1185
+
1186
+ with open(metadata_path, "w", encoding="utf-8") as f:
1187
+ json.dump(
1188
+ {
1189
+ "country_folder": country_folder,
1190
+ "signature_hash": signature_hash,
1191
+ "file_count": len(file_list),
1192
+ "files": [
1193
+ {
1194
+ "relative_path": item["relative_path"],
1195
+ "size": item["size"],
1196
+ "mtime_ns": item["mtime_ns"],
1197
+ "ext": item["ext"],
1198
+ }
1199
+ for item in file_list
1200
+ ],
1201
+ },
1202
+ f,
1203
+ ensure_ascii=False,
1204
+ indent=2,
1205
+ )
1206
 
1207
+ print(f"โœ… FAISS ๋””์Šคํฌ ์บ์‹œ ์ €์žฅ: {cache_path}")
 
 
 
 
 
 
 
 
1208
 
1209
+ except Exception as e:
1210
+ print(f"FAISS ๋””์Šคํฌ ์บ์‹œ ์ €์žฅ ์‹คํŒจ: {country_folder} / {e}")
1211
 
1212
+ VECTOR_DB_CACHE[country_folder] = {
1213
+ "signature_hash": signature_hash,
1214
+ "db": db,
1215
+ "file_count": len(file_list),
 
 
 
1216
  }
1217
 
1218
+ return db
1219
+
1220
 
1221
+ # ============================================================
1222
+ # GPT ์‘๋‹ต ํŒŒ์‹ฑ / ๋ณด์ •
1223
+ # ============================================================
1224
 
 
 
 
1225
  def parse_country_response(text):
1226
  result = {
1227
  "๋Œ€ํ‘œ INCI": "-",
 
1244
  return result
1245
 
1246
 
1247
+ def clean_json_text(text):
1248
+ text = safe_str(text)
1249
+
1250
+ text = re.sub(r"^```json\s*", "", text.strip(), flags=re.IGNORECASE)
1251
+ text = re.sub(r"^```\s*", "", text.strip())
1252
+ text = re.sub(r"\s*```$", "", text.strip())
1253
+
1254
+ match = re.search(r"\[.*\]", text, flags=re.DOTALL)
1255
+ if match:
1256
+ return match.group(0)
1257
+
1258
+ match = re.search(r"\{.*\}", text, flags=re.DOTALL)
1259
+ if match:
1260
+ return match.group(0)
1261
+
1262
+ return text
1263
+
1264
+
1265
+ def sanitize_country_result(parsed, fallback_inci="-"):
1266
+ if not isinstance(parsed, dict):
1267
+ parsed = {}
1268
+
1269
+ representative = safe_str(parsed.get("๋Œ€ํ‘œ INCI", "")) or fallback_inci or "-"
1270
+ result_text = safe_str(parsed.get("๊ฒฐ๊ณผ", "")) or "์ œํ•œ ์—†์Œ (ํ†ต๊ณผ)"
1271
+ note = safe_str(parsed.get("๋น„๊ณ ", "")) or "-"
1272
+
1273
+ bad_tokens = [
1274
+ "๊ทœ์ œ๋ช…",
1275
+ "์ด๋Ÿ‰ ๊ณ„์‚ฐ",
1276
+ "๊ทœ์ œ / ์ด๋Ÿ‰",
1277
+ "{๊ทœ์ œ๊ตฐ๋ช…}",
1278
+ "{์„ฑ๋ถ„๋ช…",
1279
+ "{ํ•จ๋Ÿ‰}",
1280
+ "{๊ธฐ์ค€์น˜}",
1281
+ "placeholder",
1282
+ "N/A",
1283
+ "n/a",
1284
+ ]
1285
+
1286
+ if any(token in result_text for token in bad_tokens):
1287
+ result_text = "ํ™•์ธ ํ•„์š” / ๊ทœ์ œ ์„ธ๋ถ€ ๊ณ„์‚ฐ ์žฌํ™•์ธ ํ•„์š”"
1288
+ if note == "-":
1289
+ note = "๊ตฌ์ฒด ํ•œ๋„ ๋˜๋Š” ์ด๋Ÿ‰ ๊ณ„์‚ฐ๊ฐ’ ํ™•์ธ ํ•„์š”"
1290
+
1291
+ return {
1292
+ "๋Œ€ํ‘œ INCI": representative,
1293
+ "๊ฒฐ๊ณผ": result_text,
1294
+ "๋น„๊ณ ": note,
1295
+ }
1296
+
1297
+
1298
+ # ============================================================
1299
  # ๋กœ์ปฌ ๊ทœ์น™ ํŒ์ •
1300
+ # ============================================================
1301
+
1302
  def evaluate_local_rules(country, component, ingredient_totals, ingredient_amount_parts):
1303
  ckey = country_key(country)
1304
  inci_name = safe_str(component.get("INCI Name", ""))
 
1315
  canonical = canonical_inci_name(inci_name)
1316
  norm = normalize_text(inci_name)
1317
 
 
 
 
1318
  if ckey in ["EU", "EU_FUTURE", "UK", "KOREA"] and canonical in FRAGRANCE_ALLERGEN_RULES:
1319
  rule = FRAGRANCE_ALLERGEN_RULES[canonical]
1320
  total_amount = ingredient_totals.get(canonical, amount)
 
1339
  "๋น„๊ณ ": "-",
1340
  }
1341
 
 
1342
  if ckey in ["EU", "EU_FUTURE", "UK"] and "citrus" in norm and (
1343
  "peel oil" in norm
1344
  or "fruit extract" in norm
 
1357
  "๋น„๊ณ ": "COA ๋˜๋Š” ์›๋ฃŒ๊ทœ๊ฒฉ์„œ์—์„œ furocoumarines ํ™•์ธ ๊ถŒ์žฅ",
1358
  }
1359
 
 
1360
  if ckey == "EU" and ("essential oil" in norm or "leaf oil" in norm or "peel oil" in norm):
1361
  amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1362
  return {
 
1365
  "๋น„๊ณ ": "ํ•˜์œ„ ๊ตฌ์„ฑ์„ฑ๋ถ„์— Limonene, Linalool, Citral ๋“ฑ ์กด์žฌ ์‹œ ์ด๋Ÿ‰ ๊ธฐ์ค€์œผ๋กœ ํ‘œ์‹œ๊ธฐ์ค€ ๊ฒ€ํ† ",
1366
  }
1367
 
 
1368
  if ckey == "EU" and any(x in norm for x in ["carbomer", "copolymer", "crosspolymer", "polymer"]):
1369
  amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1370
  return {
 
1373
  "๋น„๊ณ ": "๊ณ ์ฒด ์ž…์ž์„ฑ, ์šฉํ•ด์„ฑ, ์ƒ๋ถ„ํ•ด์„ฑ, ์ž…์ž ํฌ๊ธฐ ๋“ฑ ์›๋ฃŒ์ž๋ฃŒ ํ™•์ธ ํ•„์š”",
1374
  }
1375
 
 
1376
  if ckey == "KOREA" and norm == "niacinamide":
1377
  amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1378
  return {
 
1389
  "๋น„๊ณ ": "๋‹จ์ˆœ ์ „์„ฑ๋ถ„ ๋ฐฐํ•ฉ ์ž์ฒด๊ฐ€ ์•„๋‹ˆ๋ผ ์ฃผ๋ฆ„๊ฐœ์„  ๊ธฐ๋Šฅ์„ฑ ํ‘œ์‹œยท๊ด‘๊ณ  ์—ฌ๋ถ€์— ๋”ฐ๋ผ ๊ฒ€ํ† ",
1390
  }
1391
 
 
1392
  if amount is None:
1393
  return {
1394
  "๋Œ€ํ‘œ INCI": inci_name or "-",
 
1399
  return None
1400
 
1401
 
1402
+ # ============================================================
1403
+ # GPT ํŒ์ •
1404
+ # ============================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1405
 
1406
+ def build_regulatory_hints(inci_name):
1407
  regulatory_hints = []
1408
+ inci_text = safe_str(inci_name).lower()
1409
 
1410
  if any(x in inci_text for x in ["retinol", "retinyl", "retinal", "retinoate", "vitamin a"]):
1411
  regulatory_hints.append("retinol retinyl palmitate retinal retinoid vitamin A retinol equivalent RE")
 
1457
  ]):
1458
  regulatory_hints.append("AHA BHA PHA acid maximum concentration pH restriction")
1459
 
1460
+ return regulatory_hints
1461
+
1462
+
1463
+ def evaluate_component_with_llm(country, material, component, llm):
1464
+ db = build_database(country)
1465
+
1466
+ inci_name = safe_str(component.get("INCI Name", ""))
1467
+ korean_name = safe_str(component.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", ""))
1468
+ amount = component.get("amount_float")
1469
+ amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1470
+
1471
+ if not inci_name and not korean_name:
1472
+ return {
1473
+ "๋Œ€ํ‘œ INCI": "-",
1474
+ "๊ฒฐ๊ณผ": "",
1475
+ "๋น„๊ณ ": "-",
1476
+ }
1477
+
1478
+ if not db:
1479
+ return {
1480
+ "๋Œ€ํ‘œ INCI": inci_name or "-",
1481
+ "๊ฒฐ๊ณผ": "๊ทœ์ œ๋ฌธ์„œ ์—†์Œ",
1482
+ "๋น„๊ณ ": "-",
1483
+ }
1484
+
1485
+ cache_key = make_eval_cache_key(country, component)
1486
+ if cache_key in EVAL_CACHE:
1487
+ return EVAL_CACHE[cache_key]
1488
+
1489
+ trade_ko = material["Trade name(๊ตญ๋ฌธ)"]
1490
+ trade_en = material["Trade name(์˜๋ฌธ)"]
1491
+ regulatory_hints = build_regulatory_hints(inci_name)
1492
+
1493
  search_text = f"""
1494
  ๊ตญ๊ฐ€: {country}
1495
  ์›๋ฃŒ๋ช… ๊ตญ๋ฌธ: {trade_ko}
 
1501
  ๊ทœ์ œ๊ตฐ ํžŒํŠธ: {' / '.join(regulatory_hints)}
1502
  """
1503
 
1504
+ docs = db.similarity_search(search_text, k=RAG_TOP_K_SINGLE)
1505
  context = "\n".join([d.page_content for d in docs])
1506
 
1507
  prompt = f"""
 
1539
  - ๊ด€๋ จ ๊ทœ์ œ๊ฐ€ ์—†์œผ๋ฉด ๊ฒฐ๊ณผ๋Š” ์ •ํ™•ํžˆ "์ œํ•œ ์—†์Œ (ํ†ต๊ณผ)" ๋กœ ์ž‘์„ฑํ•ด.
1540
  - ๊ทœ์ œ๊ฐ€ ์žˆ์œผ๋ฉด ์ œํ•œ ์—†์Œ์ด๋ผ๊ณ  ์“ฐ์ง€ ๋ง๊ณ  ๋ฐ˜๋“œ์‹œ ๊ทœ์ œ๊ตฐ๋ช…, ํ˜„์žฌ ํ•จ๋Ÿ‰, Leave-on ๊ธฐ์ค€, Wash-off ๊ธฐ์ค€์„ ๋ชจ๋‘ ์ ์–ด.
1541
  - Leave-on๊ณผ Wash-off ๊ธฐ์ค€์ด ๋™์ผํ•˜๋ฉด "Leave-on/Wash-off ๊ธฐ์ค€ ๋™์ผ"์ด๋ผ๊ณ  ์ ์–ด.
1542
+ - ํ•œ๋„ ์ด๋‚ด๋ผ๋„ ๊ทœ์ œ๊ฐ€ ์กด์žฌํ•˜๋ฉด ์ œํ•œ ์—†์Œ์ด ์•„๋‹ˆ๋ผ ๊ทœ์ œ๊ตฐ๋ช…๊ณผ ๊ธฐ์ค€์„ ํ‘œ์‹œํ•ด.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1543
  """
1544
 
1545
  try:
1546
  response = llm.invoke(prompt).content
1547
  parsed = parse_country_response(response)
1548
+ parsed = sanitize_country_result(parsed, fallback_inci=inci_name or "-")
1549
 
1550
+ EVAL_CACHE[cache_key] = parsed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1551
  return parsed
1552
 
1553
  except Exception as e:
 
1558
  }
1559
 
1560
 
1561
+ def evaluate_components_with_llm_batch(country, targets, llm):
1562
+ results = {}
1563
+
1564
+ if not targets:
1565
+ return results
1566
+
1567
+ db = build_database(country)
1568
+
1569
+ if not db:
1570
+ for item in targets:
1571
+ comp = item["component"]
1572
+ inci_name = safe_str(comp.get("INCI Name", ""))
1573
+ results[item["target_id"]] = {
1574
+ "๋Œ€ํ‘œ INCI": inci_name or "-",
1575
+ "๊ฒฐ๊ณผ": "๊ทœ์ œ๋ฌธ์„œ ์—†์Œ",
1576
+ "๋น„๊ณ ": "-",
1577
+ }
1578
+ return results
1579
+
1580
+ uncached_targets = []
1581
+
1582
+ for item in targets:
1583
+ comp = item["component"]
1584
+ cache_key = make_eval_cache_key(country, comp)
1585
+
1586
+ if cache_key in EVAL_CACHE:
1587
+ results[item["target_id"]] = EVAL_CACHE[cache_key]
1588
+ else:
1589
+ uncached_targets.append(item)
1590
+
1591
+ if not uncached_targets:
1592
+ return results
1593
+
1594
+ for batch in chunk_list(uncached_targets, BATCH_SIZE):
1595
+ target_payload = []
1596
+ search_blocks = []
1597
+
1598
+ for item in batch:
1599
+ material = item["material"]
1600
+ comp = item["component"]
1601
+
1602
+ inci_name = safe_str(comp.get("INCI Name", ""))
1603
+ korean_name = safe_str(comp.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", ""))
1604
+ amount = comp.get("amount_float")
1605
+ amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1606
+ hints = build_regulatory_hints(inci_name)
1607
+
1608
+ target_payload.append({
1609
+ "target_id": item["target_id"],
1610
+ "์›๋ฃŒ๋ช… ๊ตญ๋ฌธ": material["Trade name(๊ตญ๋ฌธ)"],
1611
+ "์›๋ฃŒ๋ช… ์˜๋ฌธ": material["Trade name(์˜๋ฌธ)"],
1612
+ "์„ฑ๋ถ„ ๊ตญ๋ฌธ๋ช…": korean_name,
1613
+ "INCI": inci_name,
1614
+ "์ตœ์ข… ์ œํ’ˆ ๋‚ด ํ•จ๋Ÿ‰(%)": amount_text,
1615
+ "๊ทœ์ œ๊ตฐ ํžŒํŠธ": hints,
1616
+ })
1617
+
1618
+ search_blocks.append(
1619
+ f"{inci_name} {korean_name} {amount_text}% {' '.join(hints)}"
1620
+ )
1621
+
1622
+ search_text = f"""
1623
+ ๊ตญ๊ฐ€: {country}
1624
+ ์ œํ’ˆ์œ ํ˜•: Leave-on ๋ฐ Wash-off ๊ธฐ์ค€ ๋ชจ๋‘ ํ™•์ธ
1625
+ ๊ฒ€ํ†  ๋Œ€์ƒ ์„ฑ๋ถ„:
1626
+ {chr(10).join(search_blocks)}
1627
+ """
1628
+
1629
+ try:
1630
+ docs = db.similarity_search(search_text, k=RAG_TOP_K_BATCH)
1631
+ context = "\n".join([d.page_content for d in docs])
1632
+
1633
+ prompt = f"""
1634
+ ๋„ˆ๋Š” ํ™”์žฅํ’ˆ ์ „์„ฑ๋ถ„ ๊ทœ์ œ ์Šคํฌ๋ฆฌ๋‹ ์ „๋ฌธ๊ฐ€์•ผ.
1635
+ ์•„๋ž˜ ์—ฌ๋Ÿฌ ๊ตฌ์„ฑ์„ฑ๋ถ„์„ "{country}" ๊ทœ์ œ ๊ธฐ์ค€์œผ๋กœ ํ•œ ๋ฒˆ์— ๊ฒ€ํ† ํ•ด.
1636
+
1637
+ [๊ฒ€ํ†  ๋Œ€์ƒ JSON]
1638
+ {json.dumps(target_payload, ensure_ascii=False, indent=2)}
1639
+
1640
+ [์ œํ’ˆ ์œ ํ˜•]
1641
+ Leave-on ๊ธฐ์ค€๊ณผ Wash-off ๊ธฐ์ค€์„ ๋ชจ๋‘ ํ™•์ธํ•ด.
1642
+
1643
+ [๊ฒ€์ƒ‰๋œ {country} ๊ทœ์ œ ์›๋ฌธ]
1644
+ {context}
1645
+
1646
+ ๋ฐ˜๋“œ์‹œ JSON ๋ฐฐ์—ด๋งŒ ์ถœ๋ ฅํ•ด.
1647
+ ๋งˆํฌ๋‹ค์šด, ์„ค๋ช…๋ฌธ, ์ฝ”๋“œ๋ธ”๋ก ์—†์ด ์ˆœ์ˆ˜ JSON๋งŒ ์ถœ๋ ฅํ•ด.
1648
+
1649
+ ์ถœ๋ ฅ ํ˜•์‹:
1650
+ [
1651
+ {{
1652
+ "target_id": "์ž…๋ ฅ target_id ๊ทธ๋Œ€๋กœ",
1653
+ "๋Œ€ํ‘œ INCI": "๋Œ€ํ‘œ INCI ๋˜๋Š” -",
1654
+ "๊ฒฐ๊ณผ": "์ œํ•œ ์—†์Œ (ํ†ต๊ณผ) ๋˜๋Š” ๊ทœ์ œ ๋‚ด์šฉ",
1655
+ "๋น„๊ณ ": "-"
1656
+ }}
1657
+ ]
1658
+
1659
+ ์ž‘์„ฑ ์›์น™:
1660
+ - ๊ฒ€์ƒ‰๋œ ๊ทœ์ œ ์›๋ฌธ์— ๊ทผ๊ฑฐ๊ฐ€ ์žˆ๋Š” ๋‚ด์šฉ๋งŒ ์ž‘์„ฑํ•ด.
1661
+ - ์›๋ฌธ์— ๊ทผ๊ฑฐ๊ฐ€ ์—†๋Š”๋ฐ ํŠน์ • ํ•œ๋„๋‚˜ ๊ธˆ์ง€ ์—ฌ๋ถ€๋ฅผ ๋งŒ๋“ค์ง€ ๋งˆ.
1662
+ - ๊ด€๋ จ ๊ทœ์ œ๊ฐ€ ์—†์œผ๋ฉด ๊ฒฐ๊ณผ๋Š” ์ •ํ™•ํžˆ "์ œํ•œ ์—†์Œ (ํ†ต๊ณผ)" ๋กœ ์ž‘์„ฑํ•ด.
1663
+ - ๊ทœ์ œ๊ฐ€ ์žˆ์œผ๋ฉด ์ œํ•œ ์—†์Œ์ด๋ผ๊ณ  ์“ฐ์ง€ ๋ง๊ณ  ๋ฐ˜๋“œ์‹œ ๊ทœ์ œ๊ตฐ๋ช…, ํ˜„์žฌ ํ•จ๋Ÿ‰, Leave-on ๊ธฐ์ค€, Wash-off ๊ธฐ์ค€์„ ๋ชจ๋‘ ์ ์–ด.
1664
+ - Leave-on๊ณผ Wash-off ๊ธฐ์ค€์ด ๋™์ผํ•˜๋ฉด "Leave-on/Wash-off ๊ธฐ์ค€ ๋™์ผ"์ด๋ผ๊ณ  ์ ์–ด.
1665
+ - ํ•œ๋„ ์ด๋‚ด๋ผ๋„ ๊ทœ์ œ๊ฐ€ ์กด์žฌํ•˜๋ฉด ์ œํ•œ ์—†์Œ์ด ์•„๋‹ˆ๋ผ ๊ทœ์ œ๊ตฐ๋ช…๊ณผ ๊ธฐ์ค€์„ ํ‘œ์‹œํ•ด.
1666
+ - ์ž…๋ ฅ๋œ ๋ชจ๋“  target_id๋ฅผ ๋น ์ง์—†์ด ๋ฐ˜ํ™˜ํ•ด.
1667
+ - ์•Œ ์ˆ˜ ์—†๊ฑฐ๋‚˜ ์›๋ฌธ ๊ทผ๊ฑฐ๊ฐ€ ๋ถ€์กฑํ•˜๋ฉด "ํ™•์ธ ํ•„์š” / ๊ทœ์ œ ์„ธ๋ถ€ ๊ณ„์‚ฐ ์žฌํ™•์ธ ํ•„์š”"๋กœ ์ž‘์„ฑํ•ด.
1668
+ """
1669
+
1670
+ response = llm.invoke(prompt).content
1671
+ json_text = clean_json_text(response)
1672
+ parsed = json.loads(json_text)
1673
+
1674
+ if isinstance(parsed, dict):
1675
+ parsed = [parsed]
1676
+
1677
+ parsed_by_id = {}
1678
+
1679
+ for obj in parsed:
1680
+ if not isinstance(obj, dict):
1681
+ continue
1682
+
1683
+ target_id = safe_str(obj.get("target_id", ""))
1684
+ if not target_id:
1685
+ continue
1686
+
1687
+ parsed_by_id[target_id] = sanitize_country_result(
1688
+ obj,
1689
+ fallback_inci=safe_str(obj.get("๋Œ€ํ‘œ INCI", "-"))
1690
+ )
1691
+
1692
+ for item in batch:
1693
+ target_id = item["target_id"]
1694
+ comp = item["component"]
1695
+
1696
+ if target_id in parsed_by_id:
1697
+ result = parsed_by_id[target_id]
1698
+ results[target_id] = result
1699
+ EVAL_CACHE[make_eval_cache_key(country, comp)] = result
1700
+
1701
+ for item in batch:
1702
+ target_id = item["target_id"]
1703
+
1704
+ if target_id in results:
1705
+ continue
1706
+
1707
+ result = evaluate_component_with_llm(
1708
+ country=country,
1709
+ material=item["material"],
1710
+ component=item["component"],
1711
+ llm=llm,
1712
+ )
1713
+
1714
+ results[target_id] = result
1715
 
1716
+ except Exception as e:
1717
+ print(f"batch GPT ํŒ์ • ์‹คํŒจ: {country} / {e}")
1718
+
1719
+ for item in batch:
1720
+ target_id = item["target_id"]
1721
+
1722
+ if target_id in results:
1723
+ continue
1724
+
1725
+ result = evaluate_component_with_llm(
1726
+ country=country,
1727
+ material=item["material"],
1728
+ component=item["component"],
1729
+ llm=llm,
1730
+ )
1731
+
1732
+ results[target_id] = result
1733
 
1734
+ return results
1735
 
1736
+
1737
+ # ============================================================
1738
  # ์—‘์…€ ์Šคํƒ€์ผ ๋ฐ ๋ณ‘ํ•ฉ
1739
+ # ============================================================
1740
+
1741
  def style_excel(path, selected_countries, merge_ranges):
1742
  wb = load_workbook(path)
1743
  ws = wb.active
 
1758
 
1759
  headers = [c.value for c in ws[1]]
1760
 
 
 
 
 
 
1761
  merge_cols = []
1762
  for name in ["NO", "Trade name(๊ตญ๋ฌธ)", "Trade name(์˜๋ฌธ)", "Contents\n(w/w %)"]:
1763
  if name in headers:
1764
  merge_cols.append(headers.index(name) + 1)
1765
 
 
1766
  for idx, header in enumerate(headers, start=1):
1767
  header_text = str(header or "").replace("\n", " ").strip().lower()
1768
  if "contents" in header_text and "w/w" in header_text and idx not in merge_cols:
 
1776
 
1777
  note_col = headers.index("๋น„๊ณ ") + 1 if "๋น„๊ณ " in headers else None
1778
 
 
1779
  for row in range(1, ws.max_row + 1):
1780
  for col in range(1, ws.max_column + 1):
1781
  cell = ws.cell(row=row, column=col)
 
1786
  cell.fill = header_fill
1787
  cell.font = black_bold_font
1788
 
 
 
1789
  for row in range(2, ws.max_row + 1):
1790
  no_value = str(ws.cell(row=row, column=1).value or "").strip()
1791
  is_total_row = no_value == "ํ•ฉ๊ณ„"
 
1815
  note_cell.fill = yellow_fill
1816
  note_cell.font = red_font
1817
 
 
1818
  for start_row, end_row in merge_ranges:
1819
  if end_row <= start_row:
1820
  continue
 
1832
  except Exception:
1833
  pass
1834
 
 
1835
  for col_cells in ws.columns:
1836
  col_letter = col_cells[0].column_letter
1837
  col_idx = col_cells[0].column
 
1854
  wb.save(path)
1855
 
1856
 
1857
+ # ============================================================
1858
  # ๋ฉ”์ธ ์ฒ˜๋ฆฌ
1859
+ # ============================================================
1860
+
1861
  def process(countries, file):
1862
  try:
1863
  if not file:
 
1880
  temperature=0,
1881
  )
1882
 
 
1883
  row_items = []
1884
  merge_ranges = []
1885
 
 
1886
  for material in grouped_materials:
1887
  components = material["Components"]
1888
+ start_excel_row = len(row_items) + 2
1889
 
1890
  for idx, comp in enumerate(components):
1891
  is_first = idx == 0
1892
+ target_id = f"row_{len(row_items)}"
1893
 
1894
  row_data = {
1895
  "NO": material["NO"] if is_first else "",
 
1899
  "INCI Name": comp["INCI Name"],
1900
  "Contents\n(w/w %)": comp["Contents(w/w %)"] if is_first else "",
1901
  "In formula\n(w/w %)": comp["In formula(w/w %)"],
 
1902
  }
1903
 
1904
+ row_items.append({
1905
+ "target_id": target_id,
1906
+ "material": material,
1907
+ "component": comp,
1908
+ "row_data": row_data,
1909
+ "notes": [],
1910
+ })
1911
 
1912
+ end_excel_row = len(row_items) + 1
1913
  merge_ranges.append((start_excel_row, end_excel_row))
1914
 
1915
+ for country in countries:
1916
+ col_name = display_country(country)
1917
+ gpt_targets = []
1918
+
1919
+ for item in row_items:
1920
+ local_result = evaluate_local_rules(
1921
+ country=country,
1922
+ component=item["component"],
1923
+ ingredient_totals=ingredient_totals,
1924
+ ingredient_amount_parts=ingredient_amount_parts,
1925
+ )
1926
 
1927
+ if local_result is not None:
1928
+ item["row_data"][col_name] = local_result.get("๊ฒฐ๊ณผ", "")
 
1929
 
1930
+ note = safe_str(local_result.get("๋น„๊ณ ", "-"))
1931
+ if note and note != "-":
1932
+ item["notes"].append(f"{col_name}: {note}")
1933
+
1934
+ else:
1935
+ gpt_targets.append({
1936
+ "target_id": item["target_id"],
1937
+ "material": item["material"],
1938
+ "component": item["component"],
1939
+ })
1940
 
1941
+ batch_results = evaluate_components_with_llm_batch(
1942
  country=country,
1943
+ targets=gpt_targets,
 
1944
  llm=llm,
 
 
1945
  )
1946
 
1947
+ for item in row_items:
1948
+ if col_name in item["row_data"]:
1949
+ continue
1950
 
1951
+ result = batch_results.get(item["target_id"])
 
 
 
1952
 
1953
+ if result is None:
1954
+ result = {
1955
+ "๋Œ€ํ‘œ INCI": safe_str(item["component"].get("INCI Name", "")) or "-",
1956
+ "๊ฒฐ๊ณผ": "ํ™•์ธ ํ•„์š”",
1957
+ "๋น„๊ณ ": "batch ๊ฒฐ๊ณผ ๋ˆ„๋ฝ",
1958
+ }
 
 
 
 
1959
 
1960
+ item["row_data"][col_name] = result.get("๊ฒฐ๊ณผ", "")
 
 
 
 
 
 
 
 
 
1961
 
1962
+ note = safe_str(result.get("๋น„๊ณ ", "-"))
1963
+ if note and note != "-":
1964
+ item["notes"].append(f"{col_name}: {note}")
1965
 
1966
+ output_rows = []
 
 
1967
 
1968
+ for item in row_items:
1969
+ row_data = item["row_data"]
1970
+ row_data["๋น„๊ณ "] = " / ".join(item["notes"]) if item["notes"] else "-"
1971
+ output_rows.append(row_data)
1972
 
 
1973
  country_cols = [display_country(c) for c in countries]
1974
 
1975
  total_row = {
 
2021
  "- In formula(w/w %)๋Š” ๊ตฌ์„ฑ์„ฑ๋ถ„๋ณ„ ์ตœ์ข… ํ•จ๋Ÿ‰์ด๋ฏ€๋กœ ๋ณ‘ํ•ฉํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.\n"
2022
  "- ๊ตญ๊ฐ€ ๊ฒฐ๊ณผ ์นธ์€ '์ œํ•œ ์—†์Œ (ํ†ต๊ณผ)'๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ๋นจ๊ฐ„์ƒ‰ ๋ณผ๋“œ + ๋…ธ๋ž€์ƒ‰์œผ๋กœ ํ‘œ์‹œํ–ˆ์Šต๋‹ˆ๋‹ค.\n"
2023
  "- ํ–ฅ๋ฃŒ ์•Œ๋ ˆ๋ฅด๊ฒ์€ ์ด๋Ÿ‰ ๊ธฐ์ค€์œผ๋กœ Leave-on 0.001%, Wash-off 0.01% ๊ธฐ์ค€์„ ํ•จ๊ป˜ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค.\n"
2024
+ "- ๊ทœ์ œ ํŒŒ์ผ์€ ๋ณ€๊ฒฝ ์‹œ ์ž๋™ ์žฌ์ƒ‰์ธํ•˜๋ฉฐ, ๋™์ผ ํŒŒ์ผ ๊ตฌ์„ฑ์€ FAISS ๋””์Šคํฌ ์บ์‹œ๋ฅผ ์žฌ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.\n"
2025
+ "- GPT ํŒ์ •์€ ๊ตญ๊ฐ€๋ณ„ batch ๋ฐฉ์‹์œผ๋กœ ์ฒ˜๋ฆฌํ•˜์—ฌ ๊ธฐ์กด ์„ฑ๋ถ„ร—๊ตญ๊ฐ€ ๊ฐœ๋ณ„ ํ˜ธ์ถœ๋ณด๋‹ค ๋น ๋ฅด๊ฒŒ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.\n"
 
 
2026
  f"- ์ง€์› ๊ทœ์ œ ํŒŒ์ผ ํ™•์žฅ์ž: {', '.join(sorted(SUPPORTED_REG_FILE_EXTENSIONS))}"
2027
  )
2028
 
 
2034
  return None, None, f"โŒ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}\n\n{tb[-3000:]}"
2035
 
2036
 
2037
+ # ============================================================
2038
  # GRADIO UI
2039
+ # ============================================================
2040
+
2041
  with gr.Blocks(css=custom_css) as demo:
2042
  gr.Markdown("# ๐ŸŒ reBom Regulatory Screening AI")
2043
  gr.Markdown("### ๊ธ€๋กœ๋ฒŒ ํ™”์žฅํ’ˆ ๊ทœ์ œ ๊ธฐ๋ฐ˜ ์ „์„ฑ๋ถ„ ์Šคํฌ๋ฆฌ๋‹")
 
2072
  lines=12,
2073
  )
2074
 
 
 
 
 
 
2075
  refresh.click(
2076
  fn=refresh_country_choices_and_clear_cache,
2077
  inputs=country,
2078
  outputs=country,
2079
  )
2080
 
 
2081
  try:
2082
  auto_refresh_timer = gr.Timer(15)
2083
 
 
2102
  )
2103
 
2104
 
2105
+ # ============================================================
2106
+ # ๋กœ๊ทธ์ธ ์ธ์ฆ ์„ค์ •
2107
+ # ============================================================
2108
+
2109
  allowed_users = [
2110
  ("jin21i@rebom.kr", "qwer0515!"),
2111
  ("jkh@rebom.kr", "rebom123!"),
 
2112
  ("member2", "1111"),
2113
  ]
2114
 
2115
 
2116
+ # ============================================================
2117
  # ์•ฑ ์‹คํ–‰
2118
+ # ============================================================
2119
+
2120
+ # share=True ์ ์šฉ:
2121
+ # ์‹คํ–‰ ํ›„ ํ„ฐ๋ฏธ๋„์— ๋œจ๋Š” https://xxxxx.gradio.live ๋งํฌ๋ฅผ ํŒ€์›์—๊ฒŒ ๊ณต์œ ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.
2122
  try:
2123
  demo.launch(
2124
  server_name="0.0.0.0",
2125
  server_port=7860,
2126
  ssr_mode=False,
2127
  auth=allowed_users,
2128
+ share=True,
2129
  )
2130
  except TypeError:
2131
  demo.launch(
2132
  server_name="0.0.0.0",
2133
  server_port=7860,
2134
  auth=allowed_users,
2135
+ share=True,
2136
  )