jin2li commited on
Commit
b4eeca4
Β·
verified Β·
1 Parent(s): 66f5064

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1273 -4
app.py CHANGED
@@ -663,10 +663,1279 @@ def download_mfds_template():
663
  def resolve_country_folder(country):
664
  if not country or country == "폴더 μ—†μŒ":
665
  return None
 
666
  raw = safe_str(country)
667
  alias = COUNTRY_FOLDER_ALIASES.get(raw, COUNTRY_FOLDER_ALIASES.get(raw.upper(), raw))
 
668
  candidates = [
669
- raw, alias, raw.upper(), alias.upper(),
670
- raw.replace("_", " "), raw.replace("-", " "),
671
- raw.replace("EU FUTURE", "EU (FUTURE)"), raw.replace("EU_FUTURE", "EU (FUTURE)"),
672
- alias.replace
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
663
  def resolve_country_folder(country):
664
  if not country or country == "폴더 μ—†μŒ":
665
  return None
666
+
667
  raw = safe_str(country)
668
  alias = COUNTRY_FOLDER_ALIASES.get(raw, COUNTRY_FOLDER_ALIASES.get(raw.upper(), raw))
669
+
670
  candidates = [
671
+ raw,
672
+ alias,
673
+ raw.upper(),
674
+ alias.upper(),
675
+ raw.replace("_", " "),
676
+ raw.replace("-", " "),
677
+ raw.replace("EU FUTURE", "EU (FUTURE)"),
678
+ raw.replace("EU_FUTURE", "EU (FUTURE)"),
679
+ alias.replace("_", " "),
680
+ alias.replace("-", " "),
681
+ ]
682
+
683
+ seen = []
684
+ for item in candidates:
685
+ item = safe_str(item)
686
+ if item and item not in seen:
687
+ seen.append(item)
688
+
689
+ for item in seen:
690
+ if os.path.isdir(item):
691
+ return item
692
+
693
+ folder_map = {
694
+ f.lower(): f
695
+ for f in os.listdir(".")
696
+ if os.path.isdir(f)
697
+ }
698
+
699
+ for item in seen:
700
+ matched = folder_map.get(item.lower())
701
+ if matched:
702
+ return matched
703
+
704
+ return alias
705
+
706
+
707
+ # ============================================================
708
+ # 4-1. κ΅­κ°€ 폴더 λͺ©λ‘ κ°±μ‹ 
709
+ # ============================================================
710
+
711
+ def get_country_folders():
712
+ exclude = [".git", ".cache", "__pycache__", ".ipynb_checkpoints", ".venv", "venv", "node_modules", FAISS_CACHE_DIR, "outputs"]
713
+ existing_folders = [f for f in os.listdir(".") if os.path.isdir(f) and f not in exclude]
714
+ existing_set = set(existing_folders)
715
+ ordered = [c for c in COUNTRY_ORDER if c in existing_set]
716
+ extras = sorted([f for f in existing_folders if f not in COUNTRY_ORDER])
717
+ if not ordered and not extras:
718
+ return COUNTRY_ORDER.copy()
719
+ return ordered + extras
720
+
721
+
722
+ def refresh_country_choices_keep_selection(current_values=None):
723
+ choices = get_country_folders()
724
+ current_values = current_values or []
725
+ kept_values = [v for v in current_values if v in choices]
726
+ return gr.update(choices=choices, value=kept_values)
727
+
728
+
729
+ def refresh_country_choices_and_clear_cache(current_values=None):
730
+ VECTOR_DB_CACHE.clear()
731
+ EVAL_CACHE.clear()
732
+ return refresh_country_choices_keep_selection(current_values)
733
+
734
+
735
+ # ============================================================
736
+ # 5. μž…λ ₯ μ—‘μ…€ 미리보기 / 컬럼 인식
737
+ # ============================================================
738
+
739
+ def preview_excel(file):
740
+ if not file:
741
+ return None
742
+ try:
743
+ return pd.read_excel(file.name)
744
+ except Exception as e:
745
+ return pd.DataFrame({"였λ₯˜": [str(e)]})
746
+
747
+
748
+ def find_best_col(df, keywords, default_index=None, exclude_cols=None):
749
+ exclude_cols = exclude_cols or []
750
+ scores = []
751
+ for idx, col in enumerate(df.columns):
752
+ if col in exclude_cols:
753
+ continue
754
+ header = str(col).lower()
755
+ values = df[col].dropna().astype(str).str.strip()
756
+ sample = " ".join(values.head(80).tolist()).lower()
757
+ score = 0
758
+ for kw in keywords:
759
+ if kw.lower() in header:
760
+ score += 30
761
+ markers = [
762
+ "aqua", "water", "glycerin", "octocrylene", "homosalate", "octisalate", "avobenzone",
763
+ "niacinamide", "phenoxyethanol", "limonene", "linalool", "citral", "extract", "acid", "ceramide", "glycol", "retinol",
764
+ ]
765
+ if any(x in sample for x in markers):
766
+ if any(k.lower() in ["inci", "ingredient", "μ„±λΆ„", "μ „μ„±λΆ„", "ꡬ성", "inci name"] for k in keywords):
767
+ score += 10
768
+ scores.append((score, idx, col))
769
+ scores = sorted(scores, reverse=True, key=lambda x: (x[0], -x[1]))
770
+ if scores and scores[0][0] > 0:
771
+ return scores[0][2]
772
+ if default_index is not None and len(df.columns) > default_index:
773
+ return df.columns[default_index]
774
+ return df.columns[0]
775
+
776
+
777
+ def find_numeric_col(df, keywords, default_index=None, exclude_cols=None, prefer_many_values=True):
778
+ exclude_cols = exclude_cols or []
779
+ candidates = []
780
+ for idx, col in enumerate(df.columns):
781
+ if col in exclude_cols:
782
+ continue
783
+ header = str(col).lower()
784
+ values = df[col].dropna()
785
+ if values.empty:
786
+ continue
787
+ count = values.apply(is_numeric_like).sum()
788
+ if count <= 0:
789
+ continue
790
+ score = 0
791
+ for kw in keywords:
792
+ if kw.lower() in header:
793
+ score += 30
794
+ candidates.append({"col": col, "idx": idx, "score": score, "count": count, "non_null": len(values)})
795
+ if not candidates:
796
+ if default_index is not None and len(df.columns) > default_index:
797
+ return df.columns[default_index]
798
+ return None
799
+ if prefer_many_values:
800
+ candidates = sorted(candidates, key=lambda x: (x["score"], x["non_null"], x["idx"]), reverse=True)
801
+ else:
802
+ candidates = sorted(candidates, key=lambda x: (x["score"], -x["non_null"], -x["idx"]), reverse=True)
803
+ return candidates[0]["col"]
804
+
805
+
806
+ def find_main_columns(df):
807
+ no_col = find_best_col(df, ["no", "번호", "순번"], default_index=0)
808
+ trade_ko_col = find_best_col(df, ["trade name(κ΅­λ¬Έ)", "trade name κ΅­λ¬Έ", "κ΅­λ¬Έ", "μ›λ£Œλͺ…", "μƒν’ˆλͺ…"], default_index=1, exclude_cols=[no_col])
809
+ trade_en_col = find_best_col(df, ["trade name(영문)", "trade name 영문", "영문", "trade name", "trade", "raw material", "material"], default_index=2 if len(df.columns) > 2 else 1, exclude_cols=[no_col, trade_ko_col])
810
+ korean_ing_col = find_best_col(df, ["ν•œκΈ€ μ„±λΆ„λͺ…", "κ΅­λ¬Έ μ„±λΆ„λͺ…", "ν•œκΈ€μ„±λΆ„λͺ…", "korean", "κ΅­λ¬Έinci", "μ„±λΆ„λͺ…"], default_index=3 if len(df.columns) > 3 else None, exclude_cols=[no_col, trade_ko_col, trade_en_col])
811
+ inci_col = find_best_col(df, ["inci name", "inci", "ingredient", "μ„±λΆ„", "μ „μ„±λΆ„", "ꡬ성", "cas"], default_index=4 if len(df.columns) > 4 else 2, exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col])
812
+ contents_col = find_numeric_col(df, ["contents", "content", "contenta", "μ›λ£Œ λ‚΄", "μ›λ£Œλ‚΄", "ν•¨μœ λŸ‰", "μ‘°μ„±λΉ„"], default_index=5 if len(df.columns) > 5 else None, exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col], prefer_many_values=True)
813
+ formula_col = find_numeric_col(df, ["in formula", "formula", "처방", "μ΅œμ’…", "μ œν’ˆ λ‚΄", "μ œν’ˆλ‚΄", "λ°°ν•©λŸ‰", "ν•¨λŸ‰"], default_index=6 if len(df.columns) > 6 else None, exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col], prefer_many_values=True)
814
+
815
+ if contents_col == formula_col:
816
+ numeric_cols = []
817
+ for col in df.columns:
818
+ if col in [no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col]:
819
+ continue
820
+ values = df[col].dropna()
821
+ if not values.empty and values.apply(is_numeric_like).sum() > 0:
822
+ numeric_cols.append(col)
823
+ if len(numeric_cols) >= 2:
824
+ contents_col = numeric_cols[-2]
825
+ formula_col = numeric_cols[-1]
826
+
827
+ return {
828
+ "no_col": no_col,
829
+ "trade_ko_col": trade_ko_col,
830
+ "trade_en_col": trade_en_col,
831
+ "korean_ing_col": korean_ing_col,
832
+ "inci_col": inci_col,
833
+ "contents_col": contents_col,
834
+ "formula_col": formula_col,
835
+ }
836
+
837
+
838
+ # ============================================================
839
+ # 6. μž…λ ₯ μ—‘μ…€ 정리 / κ·Έλ£Ήν™”
840
+ # ============================================================
841
+
842
+ def clean_input_df(df, cols):
843
+ no_col = cols["no_col"]
844
+ trade_ko_col = cols["trade_ko_col"]
845
+ trade_en_col = cols["trade_en_col"]
846
+ korean_ing_col = cols["korean_ing_col"]
847
+ inci_col = cols["inci_col"]
848
+
849
+ footer_markers = [
850
+ "commitment of the manufacturer", "the manufacturer here", "it is illegal", "rebom co",
851
+ "myeonghaksandanseo", "sejong special", "tel :", "fax :", "lab no.", "permission",
852
+ ]
853
+
854
+ keep_indices = []
855
+ footer_started = False
856
+
857
+ for idx, row in df.iterrows():
858
+ row_values = [safe_str(v) for v in row.values]
859
+ row_text = " ".join([v for v in row_values if v]).strip()
860
+ row_text_lower = row_text.lower()
861
+ if not row_text:
862
+ continue
863
+
864
+ no_text = safe_str(row.get(no_col, "")).lower() if no_col in df.columns else ""
865
+ trade_ko_text = safe_str(row.get(trade_ko_col, "")).lower() if trade_ko_col in df.columns else ""
866
+ trade_en_text = safe_str(row.get(trade_en_col, "")).lower() if trade_en_col in df.columns else ""
867
+ korean_ing_text = safe_str(row.get(korean_ing_col, "")).lower() if korean_ing_col in df.columns else ""
868
+ inci_text = safe_str(row.get(inci_col, "")).lower() if inci_col in df.columns else ""
869
+
870
+ if no_text in ["no", "번호", "순번"] or inci_text in ["inci", "inci name"] or korean_ing_text in ["ν•œκΈ€ μ„±λΆ„λͺ…", "ν•œκΈ€μ„±λΆ„λͺ…", "κ΅­λ¬Έ μ„±λΆ„λͺ…"]:
871
+ continue
872
+ if no_text.startswith("합계") or trade_ko_text.startswith("합계") or trade_en_text.startswith("합계"):
873
+ footer_started = True
874
+ continue
875
+ if any(marker in row_text_lower for marker in footer_markers):
876
+ footer_started = True
877
+ continue
878
+ if footer_started:
879
+ continue
880
+ keep_indices.append(idx)
881
+
882
+ return df.loc[keep_indices].reset_index(drop=True)
883
+
884
+
885
+ def compute_ingredient_totals(cleaned_df, cols):
886
+ formula_col = cols["formula_col"]
887
+ totals = defaultdict(float)
888
+ amount_parts = defaultdict(list)
889
+ if not formula_col:
890
+ return totals, amount_parts
891
+ for _, row in cleaned_df.iterrows():
892
+ identity = normalize_text(" ".join([safe_str(v) for v in row.values]))
893
+ amount = to_number(row.get(formula_col, ""))
894
+ if amount is None:
895
+ continue
896
+ for canonical, rule in FRAGRANCE_ALLERGEN_RULES.items():
897
+ for alias in rule.get("aliases", []):
898
+ alias_norm = normalize_text(alias)
899
+ if alias_norm and alias_norm in identity:
900
+ totals[canonical] += amount
901
+ amount_parts[canonical].append(amount)
902
+ return totals, amount_parts
903
+
904
+
905
+ def make_grouped_materials(df):
906
+ cols = find_main_columns(df)
907
+ cleaned_df = clean_input_df(df, cols)
908
+
909
+ no_col = cols["no_col"]
910
+ trade_ko_col = cols["trade_ko_col"]
911
+ trade_en_col = cols["trade_en_col"]
912
+ korean_ing_col = cols["korean_ing_col"]
913
+ inci_col = cols["inci_col"]
914
+ contents_col = cols["contents_col"]
915
+ formula_col = cols["formula_col"]
916
+
917
+ work_df = cleaned_df.copy()
918
+ for col in [no_col, trade_ko_col, trade_en_col]:
919
+ if col and col in work_df.columns:
920
+ work_df[col] = work_df[col].ffill()
921
+
922
+ group_keys = [c for c in [no_col, trade_ko_col, trade_en_col] if c and c in work_df.columns]
923
+ grouped_materials = []
924
+
925
+ for key, group in work_df.groupby(group_keys, dropna=True, sort=False):
926
+ if not isinstance(key, tuple):
927
+ key = (key,)
928
+ no_value = format_no(key[0]) if len(key) > 0 else ""
929
+ trade_ko = safe_str(key[1]) if len(key) > 1 else ""
930
+ trade_en = safe_str(key[2]) if len(key) > 2 else trade_ko
931
+
932
+ if no_value and not is_numeric_like(no_value):
933
+ continue
934
+ if not trade_ko and not trade_en:
935
+ continue
936
+
937
+ components = []
938
+ for _, row in group.iterrows():
939
+ korean_ing = safe_str(row.get(korean_ing_col, "")) if korean_ing_col in row else ""
940
+ inci_name = safe_str(row.get(inci_col, "")) if inci_col in row else ""
941
+ if not inci_name and not korean_ing:
942
+ continue
943
+ contents_value = format_amount(row.get(contents_col)) if contents_col and contents_col in row else ""
944
+ formula_value = format_amount(row.get(formula_col)) if formula_col and formula_col in row else ""
945
+ components.append({
946
+ "ν•œκΈ€ μ„±λΆ„λͺ…": korean_ing,
947
+ "INCI Name": inci_name,
948
+ "Contents(w/w %)": contents_value,
949
+ "In formula(w/w %)": formula_value,
950
+ "amount_float": to_number(row.get(formula_col)) if formula_col and formula_col in row else None,
951
+ })
952
+
953
+ if components:
954
+ grouped_materials.append({
955
+ "NO": no_value,
956
+ "Trade name(κ΅­λ¬Έ)": trade_ko,
957
+ "Trade name(영문)": trade_en,
958
+ "Components": components,
959
+ "Group_records": group.to_dict(orient="records"),
960
+ })
961
+
962
+ ingredient_totals, ingredient_amount_parts = compute_ingredient_totals(cleaned_df, cols)
963
+ meta = {"cols": cols, "cleaned_df": cleaned_df, "ingredient_totals": ingredient_totals, "ingredient_amount_parts": ingredient_amount_parts}
964
+ return grouped_materials, meta
965
+
966
+
967
+ # ============================================================
968
+ # 7. 규제 λ¬Έμ„œ FAISS DB
969
+ # ============================================================
970
+
971
+ def get_regulatory_file_list(country_folder):
972
+ files = []
973
+ if not country_folder or not os.path.isdir(country_folder):
974
+ return files
975
+ for root, dirs, filenames in os.walk(country_folder):
976
+ dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ["__pycache__", ".ipynb_checkpoints"]]
977
+ for filename in filenames:
978
+ ext = os.path.splitext(filename)[1].lower()
979
+ if ext not in SUPPORTED_REG_FILE_EXTENSIONS:
980
+ continue
981
+ file_path = os.path.join(root, filename)
982
+ try:
983
+ stat = os.stat(file_path)
984
+ except FileNotFoundError:
985
+ continue
986
+ files.append({"path": file_path, "relative_path": os.path.relpath(file_path, country_folder), "size": stat.st_size, "mtime_ns": stat.st_mtime_ns, "ext": ext})
987
+ return sorted(files, key=lambda x: x["relative_path"].lower())
988
+
989
+
990
+ def get_regulatory_folder_signature(country_folder):
991
+ file_list = get_regulatory_file_list(country_folder)
992
+ signature = tuple((item["relative_path"], item["size"], item["mtime_ns"]) for item in file_list)
993
+ return signature, file_list
994
+
995
+
996
+ def read_text_file_with_fallback(file_path):
997
+ for enc in ["utf-8", "utf-8-sig", "cp949", "euc-kr", "latin-1"]:
998
+ try:
999
+ with open(file_path, "r", encoding=enc) as f:
1000
+ return f.read()
1001
+ except Exception:
1002
+ continue
1003
+ return ""
1004
+
1005
+
1006
+ def extract_text_from_regulatory_file(file_item):
1007
+ file_path = file_item["path"]
1008
+ rel_path = file_item["relative_path"]
1009
+ ext = file_item["ext"]
1010
+ texts = []
1011
+ try:
1012
+ if ext == ".pdf":
1013
+ with pdfplumber.open(file_path) as pdf:
1014
+ for page_no, page in enumerate(pdf.pages, start=1):
1015
+ text = page.extract_text()
1016
+ if text:
1017
+ texts.append(f"[파일: {rel_path}] [νŽ˜μ΄μ§€: {page_no}]\n{text}")
1018
+ elif ext == ".txt":
1019
+ text = read_text_file_with_fallback(file_path)
1020
+ if text:
1021
+ texts.append(f"[파일: {rel_path}]\n{text}")
1022
+ elif ext == ".csv":
1023
+ try:
1024
+ df = pd.read_csv(file_path, dtype=str)
1025
+ except UnicodeDecodeError:
1026
+ df = pd.read_csv(file_path, dtype=str, encoding="cp949")
1027
+ texts.append(f"[파일: {rel_path}]\n{df.fillna('').to_string(index=False)}")
1028
+ elif ext in [".xlsx", ".xls"]:
1029
+ sheets = pd.read_excel(file_path, sheet_name=None, dtype=str)
1030
+ for sheet_name, sheet_df in sheets.items():
1031
+ texts.append(f"[파일: {rel_path}] [μ‹œνŠΈ: {sheet_name}]\n{sheet_df.fillna('').to_string(index=False)}")
1032
+ except Exception as e:
1033
+ print(f"규제 파일 읽기 였λ₯˜: {file_path} / {e}")
1034
+ return "\n\n".join(texts)
1035
+
1036
+
1037
+ def get_faiss_cache_path(country_folder, signature_hash):
1038
+ os.makedirs(FAISS_CACHE_DIR, exist_ok=True)
1039
+ folder_key = safe_filename(country_folder)
1040
+ cache_folder = f"{folder_key}_{signature_hash[:16]}"
1041
+ return os.path.join(FAISS_CACHE_DIR, cache_folder)
1042
+
1043
+
1044
+ def get_current_db_signature(country):
1045
+ folder = resolve_country_folder(country)
1046
+ cached = VECTOR_DB_CACHE.get(folder)
1047
+ if isinstance(cached, dict):
1048
+ return cached.get("signature_hash")
1049
+ return None
1050
+
1051
+
1052
+ def build_database(country_folder):
1053
+ country_folder = resolve_country_folder(country_folder)
1054
+ if not country_folder or country_folder == "폴더 μ—†μŒ" or not os.path.isdir(country_folder):
1055
+ return None
1056
+
1057
+ current_signature, file_list = get_regulatory_folder_signature(country_folder)
1058
+ if not file_list:
1059
+ VECTOR_DB_CACHE.pop(country_folder, None)
1060
+ return None
1061
+
1062
+ signature_hash = stable_hash(current_signature)
1063
+ cached = VECTOR_DB_CACHE.get(country_folder)
1064
+ if isinstance(cached, dict) and cached.get("signature_hash") == signature_hash and cached.get("db") is not None:
1065
+ return cached["db"]
1066
+
1067
+ embeddings = get_embeddings()
1068
+ cache_path = get_faiss_cache_path(country_folder, signature_hash)
1069
+ metadata_path = os.path.join(cache_path, "metadata.json")
1070
+
1071
+ if os.path.isdir(cache_path) and os.path.exists(metadata_path):
1072
+ try:
1073
+ with open(metadata_path, "r", encoding="utf-8") as f:
1074
+ metadata = json.load(f)
1075
+ if metadata.get("signature_hash") == signature_hash:
1076
+ print(f"βœ… FAISS λ””μŠ€ν¬ μΊμ‹œ λ‘œλ“œ: {country_folder}")
1077
+ db = FAISS.load_local(cache_path, embeddings, allow_dangerous_deserialization=True)
1078
+ VECTOR_DB_CACHE[country_folder] = {"signature_hash": signature_hash, "db": db, "file_count": len(file_list)}
1079
+ return db
1080
+ except Exception as e:
1081
+ print(f"FAISS λ””μŠ€ν¬ μΊμ‹œ λ‘œλ“œ μ‹€νŒ¨: {country_folder} / {e}")
1082
+
1083
+ print(f"πŸ”„ 규제 DB μž¬μƒ‰μΈ: {country_folder} / 파일 {len(file_list)}개")
1084
+ EVAL_CACHE.clear()
1085
+
1086
+ texts = []
1087
+ splitter = RecursiveCharacterTextSplitter(chunk_size=900, chunk_overlap=120)
1088
+ for file_item in file_list:
1089
+ raw_text = extract_text_from_regulatory_file(file_item)
1090
+ if not raw_text:
1091
+ continue
1092
+ source_text = f"[κ΅­κ°€/채널: {country_folder}] [좜처파일: {file_item['relative_path']}]\n{raw_text}"
1093
+ texts.extend(splitter.split_text(source_text))
1094
+
1095
+ if not texts:
1096
+ VECTOR_DB_CACHE.pop(country_folder, None)
1097
+ return None
1098
+
1099
+ db = FAISS.from_texts(texts, embeddings)
1100
+
1101
+ try:
1102
+ os.makedirs(cache_path, exist_ok=True)
1103
+ db.save_local(cache_path)
1104
+ with open(metadata_path, "w", encoding="utf-8") as f:
1105
+ json.dump({
1106
+ "country_folder": country_folder,
1107
+ "signature_hash": signature_hash,
1108
+ "file_count": len(file_list),
1109
+ "files": [{"relative_path": item["relative_path"], "size": item["size"], "mtime_ns": item["mtime_ns"], "ext": item["ext"]} for item in file_list],
1110
+ }, f, ensure_ascii=False, indent=2)
1111
+ print(f"βœ… FAISS λ””μŠ€ν¬ μΊμ‹œ μ €μž₯: {cache_path}")
1112
+ except Exception as e:
1113
+ print(f"FAISS λ””μŠ€ν¬ μΊμ‹œ μ €μž₯ μ‹€νŒ¨: {country_folder} / {e}")
1114
+
1115
+ VECTOR_DB_CACHE[country_folder] = {"signature_hash": signature_hash, "db": db, "file_count": len(file_list)}
1116
+ return db
1117
+
1118
+
1119
+ # ============================================================
1120
+ # 8. 둜컬 κ·œμΉ™ νŒμ •
1121
+ # ============================================================
1122
+
1123
+ def evaluate_limit_rule(country, material, component, rule_group, rule_type_name):
1124
+ ckey = country_key(country)
1125
+ key = match_rule_key(material, component, rule_group)
1126
+ if not key:
1127
+ return None
1128
+ rule = rule_group[key]
1129
+ country_rule = rule.get(ckey)
1130
+ if not country_rule:
1131
+ return None
1132
+
1133
+ label = rule.get("label", key)
1134
+ amount = component.get("amount_float")
1135
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1136
+ status = country_rule.get("status", "allowed")
1137
+
1138
+ if status == "prohibited":
1139
+ return {"λŒ€ν‘œ INCI": label, "κ²°κ³Ό": f"{label} λ°°ν•©κΈˆμ§€ / ν˜„μž¬ ν•¨λŸ‰ {amount_text}% / μž¬κ²€ν†  ν•„μš”", "λΉ„κ³ ": "-"}
1140
+
1141
+ limit = country_rule.get("limit")
1142
+ if limit is not None:
1143
+ if amount is None:
1144
+ return {"λŒ€ν‘œ INCI": label, "κ²°κ³Ό": f"{rule_type_name} / {label}, ν•œλ„ {format_percent(limit)}%, ν˜„μž¬ ν•¨λŸ‰ 확인 ν•„μš”", "λΉ„κ³ ": "ν•¨λŸ‰ 확인 ν•„μš”"}
1145
+ if amount > limit:
1146
+ return {"λŒ€ν‘œ INCI": label, "κ²°κ³Ό": f"{rule_type_name} / {label} ν˜„μž¬ ν•¨λŸ‰ {amount_text}%, ν•œλ„ {format_percent(limit)}% 초과(μž¬κ²€ν†  ν•„μš”)", "λΉ„κ³ ": "-"}
1147
+ return {"λŒ€ν‘œ INCI": label, "κ²°κ³Ό": f"{rule_type_name} / {label} ν˜„μž¬ ν•¨λŸ‰ {amount_text}%, ν•œλ„ {format_percent(limit)}% 이내(톡과)", "λΉ„κ³ ": "-"}
1148
+
1149
+ return {"λŒ€ν‘œ INCI": label, "κ²°κ³Ό": NO_EVIDENCE_TEXT, "λΉ„κ³ ": "-"}
1150
+
1151
+
1152
+ def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts):
1153
+ ckey = country_key(country)
1154
+ amount = component.get("amount_float")
1155
+
1156
+ uv_result = evaluate_limit_rule(country, material, component, UV_FILTER_RULES, "UV ν•„ν„°")
1157
+ if uv_result is not None:
1158
+ return uv_result
1159
+
1160
+ preservative_result = evaluate_limit_rule(country, material, component, PRESERVATIVE_RULES, "보쑴제/μ œν•œμ„±λΆ„")
1161
+ if preservative_result is not None:
1162
+ return preservative_result
1163
+
1164
+ functional_key = match_rule_key(material, component, FUNCTIONAL_KOREA_RULES)
1165
+ if ckey == "KOREA" and functional_key:
1166
+ rule = FUNCTIONAL_KOREA_RULES[functional_key]
1167
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1168
+ return {"λŒ€ν‘œ INCI": rule["label"], "κ²°κ³Ό": rule["result"].format(amount=amount_text), "λΉ„κ³ ": rule.get("note", "-")}
1169
+
1170
+ fragrance_key = canonical_fragrance_name(material, component)
1171
+ if ckey in ["EU", "EU_FUTURE", "UK", "KOREA"] and fragrance_key:
1172
+ rule = FRAGRANCE_ALLERGEN_RULES[fragrance_key]
1173
+ total_amount = ingredient_totals.get(fragrance_key, amount)
1174
+ parts = ingredient_amount_parts.get(fragrance_key, [])
1175
+ calc_text = build_calc_text(parts)
1176
+ leave_status = amount_status(total_amount, rule["leave_on"], "ν‘œμ‹œ ν•„μš”")
1177
+ wash_status = amount_status(total_amount, rule["wash_off"], "ν‘œμ‹œ ν•„μš”")
1178
+ extra = rule.get("extra", "-")
1179
+ extra_text = "" if not extra or extra == "-" else f", {extra}"
1180
+ result_text = f"ν–₯료 μ•Œλ ˆλ₯΄κ² / {rule['label']} 총 {format_percent(total_amount)}%{calc_text}, Leave-on ν‘œμ‹œκΈ°μ€€ {leave_status}, Wash-off ν‘œμ‹œκΈ°μ€€ {wash_status}{extra_text}"
1181
+ return {"λŒ€ν‘œ INCI": rule["label"], "κ²°κ³Ό": result_text, "λΉ„κ³ ": "-"}
1182
+
1183
+ identity = get_identity_text(material, component)
1184
+
1185
+ if ckey in ["EU", "EU_FUTURE", "UK"] and "citrus" in identity and any(x in identity for x in ["peel oil", "fruit extract", "tangerine", "junos", "reticulata"]):
1186
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1187
+ return {
1188
+ "λŒ€ν‘œ INCI": safe_str(component.get("INCI Name", "")) or "-",
1189
+ "κ²°κ³Ό": f"μ‹œνŠΈλŸ¬μŠ€ μ›λ£Œ / ν˜„μž¬ ν•¨λŸ‰ {amount_text}%, furocoumarines μ›λ£Œμžλ£Œ 확인 ν•„μš”. μžμ™Έμ„ μ°¨λ‹¨Β·νƒœλ‹ λ“± ν–‡λΉ› λ…ΈμΆœ μ œν’ˆ ν•΄λ‹Ή μ‹œ 총 furocoumarines 1 mg/kg μ΄ν•˜ 관리 ν•„μš”",
1190
+ "λΉ„κ³ ": "COA λ˜λŠ” μ›λ£Œκ·œκ²©μ„œμ—μ„œ furocoumarines 확인 ꢌμž₯",
1191
+ }
1192
+
1193
+ if ckey in ["EU", "EU_FUTURE", "UK"] and any(x in identity for x in ["essential oil", "leaf oil", "peel oil"]):
1194
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1195
+ return {
1196
+ "λŒ€ν‘œ INCI": safe_str(component.get("INCI Name", "")) or "-",
1197
+ "κ²°κ³Ό": f"μ •μœ λ₯˜ / ν˜„μž¬ ν•¨λŸ‰ {amount_text}%, ꡬ성 ν–₯료 μ•Œλ ˆλ₯΄κ² 및 μ‚°ν™”λ¬Ό 자료 확인 ν•„μš”",
1198
+ "λΉ„κ³ ": "ν•˜μœ„ ꡬ성성뢄에 Limonene, Linalool, Citral λ“± 쑴재 μ‹œ μ΄λŸ‰ κΈ°μ€€μœΌλ‘œ ν‘œμ‹œκΈ°μ€€ κ²€ν† ",
1199
+ }
1200
+
1201
+ if ckey in ["EU", "EU_FUTURE"] and any(x in identity for x in ["carbomer", "copolymer", "crosspolymer", "polymer"]):
1202
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1203
+ return {
1204
+ "λŒ€ν‘œ INCI": safe_str(component.get("INCI Name", "")) or "-",
1205
+ "κ²°κ³Ό": f"ν•©μ„±κ³ λΆ„μž / ν˜„μž¬ ν•¨λŸ‰ {amount_text}%, EU synthetic polymer microparticles ν•΄λ‹Ήμ„± κ²€ν†  ν•„μš”",
1206
+ "λΉ„κ³ ": "고체 μž…μžμ„±, μš©ν•΄μ„±, 생뢄해성, μž…μž 크기 λ“± μ›λ£Œμžλ£Œ 확인 ν•„μš”",
1207
+ }
1208
+
1209
+ if amount is None:
1210
+ return {"λŒ€ν‘œ INCI": safe_str(component.get("INCI Name", "")) or "-", "κ²°κ³Ό": "ν•¨λŸ‰ 정보 μ—†μŒ / In formula(w/w %) 확인 ν•„μš”", "λΉ„κ³ ": "-"}
1211
+
1212
+ return None
1213
+
1214
+
1215
+ # ============================================================
1216
+ # 9. GPT 보쑰 νŒμ •
1217
+ # ============================================================
1218
+
1219
+ def parse_country_response(text):
1220
+ result = {"λŒ€ν‘œ INCI": "-", "κ²°κ³Ό": NO_EVIDENCE_TEXT, "λΉ„κ³ ": "-"}
1221
+ for line in text.splitlines():
1222
+ line = line.strip()
1223
+ if line.startswith("λŒ€ν‘œ INCI:"):
1224
+ result["λŒ€ν‘œ INCI"] = line.split(":", 1)[1].strip() or "-"
1225
+ elif line.startswith("κ²°κ³Ό:"):
1226
+ result["κ²°κ³Ό"] = line.split(":", 1)[1].strip() or NO_EVIDENCE_TEXT
1227
+ elif line.startswith("λΉ„κ³ :"):
1228
+ result["λΉ„κ³ "] = line.split(":", 1)[1].strip() or "-"
1229
+ return result
1230
+
1231
+
1232
+ def clean_json_text(text):
1233
+ text = safe_str(text)
1234
+ text = re.sub(r"^```json\s*", "", text.strip(), flags=re.IGNORECASE)
1235
+ text = re.sub(r"^```\s*", "", text.strip())
1236
+ text = re.sub(r"\s*```$", "", text.strip())
1237
+ match = re.search(r"\[.*\]", text, flags=re.DOTALL)
1238
+ if match:
1239
+ return match.group(0)
1240
+ match = re.search(r"\{.*\}", text, flags=re.DOTALL)
1241
+ if match:
1242
+ return match.group(0)
1243
+ return text
1244
+
1245
+
1246
+ def sanitize_country_result(parsed, fallback_inci="-"):
1247
+ if not isinstance(parsed, dict):
1248
+ parsed = {}
1249
+ representative = safe_str(parsed.get("λŒ€ν‘œ INCI", "")) or fallback_inci or "-"
1250
+ result_text = safe_str(parsed.get("κ²°κ³Ό", "")) or NO_EVIDENCE_TEXT
1251
+ note = safe_str(parsed.get("λΉ„κ³ ", "")) or "-"
1252
+ bad_tokens = ["규제λͺ…", "μ΄λŸ‰ 계산", "규제 / μ΄λŸ‰", "{규제ꡰλͺ…}", "{μ„±λΆ„λͺ…", "{ν•¨λŸ‰}", "{κΈ°μ€€μΉ˜}", "placeholder", "N/A", "n/a"]
1253
+ if any(token in result_text for token in bad_tokens):
1254
+ result_text = "확인 ν•„μš” / 규제 μ„ΈλΆ€ 계산 μž¬ν™•μΈ ν•„μš”"
1255
+ if note == "-":
1256
+ note = "ꡬ체 ν•œλ„ λ˜λŠ” μ΄λŸ‰ 계산값 확인 ν•„μš”"
1257
+ return {"λŒ€ν‘œ INCI": representative, "κ²°κ³Ό": result_text, "λΉ„κ³ ": note}
1258
+
1259
+
1260
+ def make_eval_cache_key(country, component):
1261
+ amount = component.get("amount_float")
1262
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1263
+ db_signature = get_current_db_signature(country)
1264
+ return (str(country), str(db_signature), safe_str(component.get("INCI Name", "")).lower(), safe_str(component.get("ν•œκΈ€ μ„±λΆ„λͺ…", "")).lower(), amount_text)
1265
+
1266
+
1267
+ def has_meaningful_search_hit(db, search_text, ingredient_names, k=MEANINGFUL_HIT_K):
1268
+ if not db:
1269
+ return False, ""
1270
+ try:
1271
+ docs = db.similarity_search(search_text, k=k)
1272
+ context = "\n".join([d.page_content for d in docs])
1273
+ except Exception:
1274
+ return False, ""
1275
+ context_norm = normalize_compact(context)
1276
+ for name in ingredient_names:
1277
+ name_norm = normalize_compact(name)
1278
+ if name_norm and len(name_norm) >= 3 and name_norm in context_norm:
1279
+ return True, context
1280
+ return False, context
1281
+
1282
+
1283
+ def evaluate_component_with_llm(country, material, component, llm, target_id=""):
1284
+ db = build_database(country)
1285
+ inci_name = safe_str(component.get("INCI Name", ""))
1286
+ korean_name = safe_str(component.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""))
1287
+ amount = component.get("amount_float")
1288
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1289
+
1290
+ if not inci_name and not korean_name:
1291
+ return {"λŒ€ν‘œ INCI": "-", "κ²°κ³Ό": "", "λΉ„κ³ ": "-"}
1292
+
1293
+ if not db:
1294
+ result = {"λŒ€ν‘œ INCI": inci_name or "-", "κ²°κ³Ό": NO_EVIDENCE_TEXT, "λΉ„κ³ ": "-"}
1295
+ log_search_context(target_id, country, component, result["κ²°κ³Ό"], "NO_DB", "ν•΄λ‹Ή κ΅­κ°€/채널 규제 DB μ—†μŒ")
1296
+ return result
1297
+
1298
+ cache_key = make_eval_cache_key(country, component)
1299
+ if cache_key in EVAL_CACHE:
1300
+ return EVAL_CACHE[cache_key]
1301
+
1302
+ trade_ko = material["Trade name(κ΅­λ¬Έ)"]
1303
+ trade_en = material["Trade name(영문)"]
1304
+ search_text = f"""
1305
+ κ΅­κ°€/채널: {country}
1306
+ μ›λ£Œλͺ… κ΅­λ¬Έ: {trade_ko}
1307
+ μ›λ£Œλͺ… 영문: {trade_en}
1308
+ κ²€ν†  μ„±λΆ„ κ΅­λ¬Έ: {korean_name}
1309
+ κ²€ν†  μ„±λΆ„ INCI/CAS: {inci_name}
1310
+ μ΅œμ’… μ œν’ˆ λ‚΄ ν•¨λŸ‰: {amount_text}%
1311
+ μ œν’ˆμœ ν˜•: Leave-on 및 Wash-off κΈ°μ€€ λͺ¨λ‘ 확인
1312
+ """
1313
+
1314
+ has_hit, pre_context = has_meaningful_search_hit(db, search_text, [inci_name, korean_name], k=MEANINGFUL_HIT_K)
1315
+ if not has_hit:
1316
+ result = {"λŒ€ν‘œ INCI": inci_name or "-", "κ²°κ³Ό": NO_EVIDENCE_TEXT, "λΉ„κ³ ": "-"}
1317
+ EVAL_CACHE[cache_key] = result
1318
+ log_search_context(target_id, country, component, result["κ²°κ³Ό"], "NO_MEANINGFUL_HIT", pre_context)
1319
+ return result
1320
+
1321
+ docs = db.similarity_search(search_text, k=RAG_TOP_K_SINGLE)
1322
+ context = "\n".join([d.page_content for d in docs])
1323
+
1324
+ prompt = f"""
1325
+ λ„ˆλŠ” ν™”μž₯ν’ˆ μ „μ„±λΆ„ 규제 μŠ€ν¬λ¦¬λ‹ μ „λ¬Έκ°€μ•Ό.
1326
+ μ•„λž˜ 단일 ꡬ성성뢄을 λ°˜λ“œμ‹œ "{country}" κΈ°μ€€μœΌλ‘œλ§Œ κ²€ν† ν•΄.
1327
+
1328
+ [μ ˆλŒ€ κ·œμΉ™]
1329
+ - ν˜„μž¬ κ²€ν†  κ΅­κ°€λŠ” "{country}"이닀.
1330
+ - μ•„λž˜ 검색 원문은 "{country}" 폴더 λ˜λŠ” μ±„λ„μ—μ„œλ§Œ κ²€μƒ‰λœ κ·Όκ±°λ‹€.
1331
+ - μ™ΈλΆ€ 지식, ν•™μŠ΅ 지식, 일반 규제 지식을 μ‚¬μš©ν•˜μ§€ 마.
1332
+ - λ‹€λ₯Έ κ΅­κ°€ κ·œμ •, EU Annex, ASEAN 채택 κ·œμ •μ„ ν˜„μž¬ ꡭ가에 μž„μ˜ μ μš©ν•˜μ§€ 마.
1333
+ - 특히 EU κ·œμ •μ„ ν•œκ΅­/일본/λ―Έκ΅­/FDA/쀑ꡭ에 볡사 μ μš©ν•˜μ§€ 마.
1334
+ - κ²€μƒ‰λœ "{country}" 원문에 λͺ…μ‹œλ˜μ§€ μ•Šμ€ μ œν•œ, λ°°ν•©κΈˆμ§€, λ°°ν•©ν•œλ„λŠ” λ§Œλ“€μ§€ 마.
1335
+ - 검색 원문에 λͺ…μ‹œλœ μ œν•œ/κΈˆμ§€/ν•œλ„ κ·Όκ±°κ°€ μ—†μœΌλ©΄ κ²°κ³ΌλŠ” μ •ν™•νžˆ "{NO_EVIDENCE_TEXT}"으둜 μž‘μ„±ν•΄.
1336
+
1337
+ [μ›λ£Œλͺ… κ΅­λ¬Έ]
1338
+ {trade_ko}
1339
+
1340
+ [μ›λ£Œλͺ… 영문]
1341
+ {trade_en}
1342
+
1343
+ [κ²€ν†  μ„±λΆ„]
1344
+ κ΅­λ¬Έλͺ…: {korean_name}
1345
+ INCI/CAS: {inci_name}
1346
+ μ΅œμ’… μ œν’ˆ λ‚΄ ν•¨λŸ‰: {amount_text}%
1347
+
1348
+ [κ²€μƒ‰λœ {country} 규제 원문]
1349
+ {context}
1350
+
1351
+ λ°˜λ“œμ‹œ μ•„λž˜ ν˜•μ‹μœΌλ‘œλ§Œ λ‹΅λ³€ν•΄.
1352
+ λŒ€ν‘œ INCI:
1353
+ κ²°κ³Ό:
1354
+ λΉ„κ³ :
1355
+
1356
+ μž‘μ„± 원칙:
1357
+ - κ²€μƒ‰λœ 규제 원문에 κ·Όκ±°κ°€ μžˆλŠ” λ‚΄μš©λ§Œ μž‘μ„±ν•΄.
1358
+ - 원문에 κ·Όκ±°κ°€ μ—†λŠ”λ° νŠΉμ • ν•œλ„λ‚˜ κΈˆμ§€ μ—¬λΆ€λ₯Ό λ§Œλ“€μ§€ 마.
1359
+ - ν˜„μž¬ ν•¨λŸ‰μ΄ ν•œλ„ 이내라면 λ°˜λ“œμ‹œ "이내(톡과)"라고 μž‘μ„±ν•΄.
1360
+ - ν˜„μž¬ ν•¨λŸ‰μ΄ ν•œλ„λ₯Ό μ΄ˆκ³Όν•  λ•Œλ§Œ "초과" λ˜λŠ” "μž¬κ²€ν†  ν•„μš”"라고 μž‘μ„±ν•΄.
1361
+ - λ°°ν•©κΈˆμ§€, ν‘œμ‹œ ν•„μš”, 자료 확인 ν•„μš”λŠ” μž¬κ²€ν†  λŒ€μƒμ΄λ‹€.
1362
+ """
1363
+
1364
+ try:
1365
+ response = llm.invoke(prompt).content
1366
+ parsed = sanitize_country_result(parse_country_response(response), fallback_inci=inci_name or "-")
1367
+ EVAL_CACHE[cache_key] = parsed
1368
+ log_search_context(target_id, country, component, parsed["κ²°κ³Ό"], "GPT_SINGLE", context)
1369
+ return parsed
1370
+ except Exception as e:
1371
+ result = {"λŒ€ν‘œ INCI": inci_name or "-", "κ²°κ³Ό": "확인 ν•„μš”", "λΉ„κ³ ": str(e)}
1372
+ log_search_context(target_id, country, component, result["κ²°κ³Ό"], "GPT_SINGLE_ERROR", str(e))
1373
+ return result
1374
+
1375
+
1376
+ def evaluate_components_with_llm_batch(country, targets, llm):
1377
+ results = {}
1378
+ if not targets:
1379
+ return results
1380
+
1381
+ db = build_database(country)
1382
+ if not db:
1383
+ for item in targets:
1384
+ comp = item["component"]
1385
+ inci_name = safe_str(comp.get("INCI Name", ""))
1386
+ results[item["target_id"]] = {"λŒ€ν‘œ INCI": inci_name or "-", "κ²°κ³Ό": NO_EVIDENCE_TEXT, "λΉ„κ³ ": "-"}
1387
+ log_search_context(item["target_id"], country, comp, NO_EVIDENCE_TEXT, "NO_DB", "ν•΄λ‹Ή κ΅­κ°€/채널 규제 DB μ—†μŒ")
1388
+ return results
1389
+
1390
+ uncached_targets = []
1391
+ for item in targets:
1392
+ comp = item["component"]
1393
+ cache_key = make_eval_cache_key(country, comp)
1394
+ if cache_key in EVAL_CACHE:
1395
+ results[item["target_id"]] = EVAL_CACHE[cache_key]
1396
+ else:
1397
+ uncached_targets.append(item)
1398
+
1399
+ if not uncached_targets:
1400
+ return results
1401
+
1402
+ filtered_targets = []
1403
+ for item in uncached_targets:
1404
+ material = item["material"]
1405
+ comp = item["component"]
1406
+ inci_name = safe_str(comp.get("INCI Name", ""))
1407
+ korean_name = safe_str(comp.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""))
1408
+ amount = comp.get("amount_float")
1409
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1410
+ search_text = f"""
1411
+ κ΅­κ°€/채널: {country}
1412
+ μ›λ£Œλͺ… κ΅­λ¬Έ: {material.get('Trade name(κ΅­λ¬Έ)', '')}
1413
+ μ›λ£Œλͺ… 영문: {material.get('Trade name(영문)', '')}
1414
+ κ²€ν†  μ„±λΆ„ κ΅­λ¬Έ: {korean_name}
1415
+ κ²€ν†  μ„±λΆ„ INCI/CAS: {inci_name}
1416
+ μ΅œμ’… μ œν’ˆ λ‚΄ ν•¨λŸ‰: {amount_text}%
1417
+ """
1418
+ has_hit, context = has_meaningful_search_hit(db, search_text, [inci_name, korean_name], k=MEANINGFUL_HIT_K)
1419
+ if has_hit:
1420
+ filtered_targets.append(item)
1421
+ else:
1422
+ result = {"λŒ€ν‘œ INCI": inci_name or "-", "κ²°κ³Ό": NO_EVIDENCE_TEXT, "λΉ„κ³ ": "-"}
1423
+ results[item["target_id"]] = result
1424
+ EVAL_CACHE[make_eval_cache_key(country, comp)] = result
1425
+ log_search_context(item["target_id"], country, comp, result["κ²°κ³Ό"], "NO_MEANINGFUL_HIT", context)
1426
+
1427
+ uncached_targets = filtered_targets
1428
+ if not uncached_targets:
1429
+ return results
1430
+
1431
+ for batch in chunk_list(uncached_targets, BATCH_SIZE):
1432
+ target_payload = []
1433
+ search_blocks = []
1434
+ for item in batch:
1435
+ material = item["material"]
1436
+ comp = item["component"]
1437
+ inci_name = safe_str(comp.get("INCI Name", ""))
1438
+ korean_name = safe_str(comp.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""))
1439
+ amount = comp.get("amount_float")
1440
+ amount_text = format_percent(amount) if amount is not None else "ν•¨λŸ‰ 확인 ν•„μš”"
1441
+ target_payload.append({
1442
+ "target_id": item["target_id"],
1443
+ "μ›λ£Œλͺ… κ΅­λ¬Έ": material["Trade name(κ΅­λ¬Έ)"],
1444
+ "μ›λ£Œλͺ… 영문": material["Trade name(영문)"],
1445
+ "μ„±λΆ„ κ΅­λ¬Έλͺ…": korean_name,
1446
+ "INCI/CAS": inci_name,
1447
+ "μ΅œμ’… μ œν’ˆ λ‚΄ ν•¨λŸ‰(%)": amount_text,
1448
+ })
1449
+ search_blocks.append(f"{material['Trade name(영문)']} {inci_name} {korean_name} {amount_text}%")
1450
+
1451
+ search_text = f"""
1452
+ κ΅­κ°€/채널: {country}
1453
+ μ œν’ˆμœ ν˜•: Leave-on 및 Wash-off κΈ°μ€€ λͺ¨λ‘ 확인
1454
+ κ²€ν†  λŒ€μƒ μ„±λΆ„:
1455
+ {chr(10).join(search_blocks)}
1456
+ """
1457
+
1458
+ try:
1459
+ docs = db.similarity_search(search_text, k=RAG_TOP_K_BATCH)
1460
+ context = "\n".join([d.page_content for d in docs])
1461
+ prompt = f"""
1462
+ λ„ˆλŠ” ν™”μž₯ν’ˆ μ „μ„±λΆ„ 규제 μŠ€ν¬λ¦¬λ‹ μ „λ¬Έκ°€μ•Ό.
1463
+ μ•„λž˜ μ—¬λŸ¬ ꡬ성성뢄을 λ°˜λ“œμ‹œ "{country}" κΈ°μ€€μœΌλ‘œλ§Œ ν•œ λ²ˆμ— κ²€ν† ν•΄.
1464
+
1465
+ [μ ˆλŒ€ κ·œμΉ™]
1466
+ - ν˜„μž¬ κ²€ν†  κ΅­κ°€λŠ” "{country}"이닀.
1467
+ - μ•„λž˜ 검색 원문은 "{country}" 폴더 λ˜λŠ” μ±„λ„μ—μ„œλ§Œ κ²€μƒ‰λœ κ·Όκ±°λ‹€.
1468
+ - μ™ΈλΆ€ 지식, ν•™μŠ΅ 지식, 일반 규제 지식을 μ‚¬μš©ν•˜μ§€ 마.
1469
+ - λ‹€λ₯Έ κ΅­κ°€ κ·œμ •, EU Annex, ASEAN 채택 κ·œμ •μ„ ν˜„μž¬ ꡭ가에 μž„μ˜ μ μš©ν•˜μ§€ 마.
1470
+ - 특히 EU κ·œμ •μ„ ν•œκ΅­/일본/λ―Έκ΅­/FDA/쀑ꡭ에 볡사 μ μš©ν•˜μ§€ 마.
1471
+ - κ²€μƒ‰λœ "{country}" 원문에 λͺ…μ‹œλ˜μ§€ μ•Šμ€ μ œν•œ, λ°°ν•©κΈˆμ§€, λ°°ν•©ν•œλ„λŠ” λ§Œλ“€μ§€ 마.
1472
+ - 검색 원문에 λͺ…μ‹œλœ μ œν•œ/κΈˆμ§€/ν•œλ„ κ·Όκ±°κ°€ μ—†μœΌλ©΄ κ²°κ³ΌλŠ” μ •ν™•νžˆ "{NO_EVIDENCE_TEXT}"으둜 μž‘μ„±ν•΄.
1473
+
1474
+ [κ²€ν†  λŒ€μƒ JSON]
1475
+ {json.dumps(target_payload, ensure_ascii=False, indent=2)}
1476
+
1477
+ [κ²€μƒ‰λœ {country} 규제 원문]
1478
+ {context}
1479
+
1480
+ λ°˜λ“œμ‹œ JSON λ°°μ—΄λ§Œ 좜λ ₯ν•΄.
1481
+ λ§ˆν¬λ‹€μš΄, μ„€λͺ…λ¬Έ, μ½”λ“œλΈ”λ‘ 없이 순수 JSON만 좜λ ₯ν•΄.
1482
+
1483
+ 좜λ ₯ ν˜•μ‹:
1484
+ [
1485
+ {{
1486
+ "target_id": "μž…λ ₯ target_id κ·ΈλŒ€λ‘œ",
1487
+ "λŒ€ν‘œ INCI": "λŒ€ν‘œ INCI λ˜λŠ” -",
1488
+ "κ²°κ³Ό": "{NO_EVIDENCE_TEXT} λ˜λŠ” 규제 λ‚΄μš©",
1489
+ "λΉ„κ³ ": "-"
1490
+ }}
1491
+ ]
1492
+
1493
+ μž‘μ„± 원칙:
1494
+ - κ²€μƒ‰λœ 규제 원문에 κ·Όκ±°κ°€ μžˆλŠ” λ‚΄μš©λ§Œ μž‘μ„±ν•΄.
1495
+ - 원문에 κ·Όκ±°κ°€ μ—†λŠ”λ° νŠΉμ • ν•œλ„λ‚˜ κΈˆμ§€ μ—¬λΆ€λ₯Ό λ§Œλ“€μ§€ 마.
1496
+ - ν˜„μž¬ ν•¨λŸ‰μ΄ ν•œλ„ 이내라면 λ°˜λ“œμ‹œ "이내(톡과)"라고 μž‘μ„±ν•΄.
1497
+ - ν˜„μž¬ ν•¨λŸ‰μ΄ ν•œλ„λ₯Ό μ΄ˆκ³Όν•  λ•Œλ§Œ "초과" λ˜λŠ” "μž¬κ²€ν†  ν•„μš”"라고 μž‘μ„±ν•΄.
1498
+ - λ°°ν•©κΈˆμ§€, ν‘œμ‹œ ν•„μš”, 자료 확인 ν•„μš”λŠ” μž¬κ²€ν†  λŒ€μƒμ΄λ‹€.
1499
+ - μž…λ ₯된 λͺ¨λ“  target_idλ₯Ό 빠짐없이 λ°˜ν™˜ν•΄.
1500
+ """
1501
+ response = llm.invoke(prompt).content
1502
+ parsed = json.loads(clean_json_text(response))
1503
+ if isinstance(parsed, dict):
1504
+ parsed = [parsed]
1505
+
1506
+ parsed_by_id = {}
1507
+ for obj in parsed:
1508
+ if not isinstance(obj, dict):
1509
+ continue
1510
+ target_id = safe_str(obj.get("target_id", ""))
1511
+ if target_id:
1512
+ parsed_by_id[target_id] = sanitize_country_result(obj, fallback_inci=safe_str(obj.get("λŒ€ν‘œ INCI", "-")))
1513
+
1514
+ for item in batch:
1515
+ target_id = item["target_id"]
1516
+ comp = item["component"]
1517
+ if target_id in parsed_by_id:
1518
+ result = parsed_by_id[target_id]
1519
+ results[target_id] = result
1520
+ EVAL_CACHE[make_eval_cache_key(country, comp)] = result
1521
+ log_search_context(target_id, country, comp, result["κ²°κ³Ό"], "GPT_BATCH", context)
1522
+
1523
+ for item in batch:
1524
+ target_id = item["target_id"]
1525
+ if target_id in results:
1526
+ continue
1527
+ results[target_id] = evaluate_component_with_llm(country, item["material"], item["component"], llm, target_id)
1528
+
1529
+ except Exception as e:
1530
+ print(f"batch GPT νŒμ • μ‹€νŒ¨: {country} / {e}")
1531
+ for item in batch:
1532
+ target_id = item["target_id"]
1533
+ if target_id not in results:
1534
+ results[target_id] = evaluate_component_with_llm(country, item["material"], item["component"], llm, target_id)
1535
+
1536
+ return results
1537
+
1538
+
1539
+ # ============================================================
1540
+ # 10. 좜λ ₯ 데이터 ꡬ성
1541
+ # ============================================================
1542
+
1543
+ def make_formula_statement_rows(row_items):
1544
+ rows = []
1545
+ for item in row_items:
1546
+ material = item["material"]
1547
+ comp = item["component"]
1548
+ rows.append({
1549
+ "NO.": material.get("NO", ""),
1550
+ "ν•œκΈ€ ν‘œμ€€ν™” λͺ…μΉ­": comp.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""),
1551
+ "INGREDIENT NAME (INCI)": comp.get("INCI Name", ""),
1552
+ "FUNCTION": "",
1553
+ "CAS.No": "",
1554
+ "SOURCE": material.get("Trade name(영문)", "") or material.get("Trade name(ꡭ문)", ""),
1555
+ "%(w/w)": comp.get("In formula(w/w %)", ""),
1556
+ })
1557
+ return pd.DataFrame(rows)
1558
+
1559
+
1560
+ def make_regulatory_summary_rows(row_items, country_cols):
1561
+ rows = []
1562
+ for item in row_items:
1563
+ row_data = item["row_data"]
1564
+ if not is_country_result_issue(row_data.get("Result", "")):
1565
+ continue
1566
+ row = {
1567
+ "ν•œκΈ€ μ„±λΆ„λͺ…": row_data.get("ν•œκΈ€ μ„±λΆ„λͺ…", ""),
1568
+ "INCI Name": row_data.get("INCI Name", ""),
1569
+ "In formula(w/w %)": row_data.get("In formula\n(w/w %)", ""),
1570
+ "Result": row_data.get("Result", ""),
1571
+ }
1572
+ for country_col in country_cols:
1573
+ value = safe_str(row_data.get(country_col, ""))
1574
+ row[country_col] = value if is_country_result_issue(value) else "-"
1575
+ row["λΉ„κ³ "] = row_data.get("λΉ„κ³ ", "-")
1576
+ rows.append(row)
1577
+
1578
+ columns = ["ν•œκΈ€ μ„±λΆ„λͺ…", "INCI Name", "In formula(w/w %)", "Result"] + country_cols + ["λΉ„κ³ "]
1579
+ if not rows:
1580
+ return pd.DataFrame(columns=columns)
1581
+ return pd.DataFrame(rows)[columns]
1582
+
1583
+
1584
+ # ============================================================
1585
+ # 11. μ—‘μ…€ μ €μž₯ / μŠ€νƒ€μΌ
1586
+ # ============================================================
1587
+
1588
+ def write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw_df):
1589
+ with pd.ExcelWriter(out_path, engine="openpyxl") as writer:
1590
+ formula_df.to_excel(writer, index=False, sheet_name="Formula Ingredients Statement", startrow=3)
1591
+ regulatory_df.to_excel(writer, index=False, sheet_name="Regulatory Screening Summary")
1592
+ raw_df.to_excel(writer, index=False, sheet_name="Raw Search Log")
1593
+
1594
+ wb = load_workbook(out_path)
1595
+ ws = wb["Formula Ingredients Statement"]
1596
+ ws["A1"] = f"PRODUCT NAME : {safe_str(product_name)}"
1597
+ ws["A1"].font = Font(bold=True, size=13)
1598
+ ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=max(1, ws.max_column))
1599
+ wb.save(out_path)
1600
+
1601
+ style_output_workbook(out_path)
1602
+
1603
+
1604
+ def style_output_workbook(path):
1605
+ """
1606
+ MergedCell 였λ₯˜ μˆ˜μ • 버전.
1607
+ κΈ°μ‘΄ ws.columns + col_cells[0].column_letter 방식은 λ³‘ν•©μ…€μ—μ„œ 였λ₯˜κ°€ λ‚˜λ―€λ‘œ,
1608
+ get_column_letter(col_idx)둜 컬럼 문자λ₯Ό μ•ˆμ „ν•˜κ²Œ μƒμ„±ν•œλ‹€.
1609
+ """
1610
+ wb = load_workbook(path)
1611
+
1612
+ thin_border = Border(
1613
+ left=Side(style="thin", color="D9D9D9"),
1614
+ right=Side(style="thin", color="D9D9D9"),
1615
+ top=Side(style="thin", color="D9D9D9"),
1616
+ bottom=Side(style="thin", color="D9D9D9"),
1617
+ )
1618
+
1619
+ header_fill = PatternFill(start_color="D9D9D9", end_color="D9D9D9", fill_type="solid")
1620
+ issue_fill = PatternFill(start_color="FFF2CC", end_color="FFF2CC", fill_type="solid")
1621
+ pass_fill = PatternFill(start_color="C6E0B4", end_color="C6E0B4", fill_type="solid")
1622
+
1623
+ red_font = Font(color="FF0000", bold=True)
1624
+ black_bold_font = Font(color="000000", bold=True)
1625
+ green_font = Font(color="006100", bold=True)
1626
+
1627
+ for ws in wb.worksheets:
1628
+ header_row = 4 if ws.title == "Formula Ingredients Statement" else 1
1629
+
1630
+ for row in range(1, ws.max_row + 1):
1631
+ for col in range(1, ws.max_column + 1):
1632
+ cell = ws.cell(row=row, column=col)
1633
+ cell.border = thin_border
1634
+ cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
1635
+
1636
+ if row == header_row:
1637
+ cell.fill = header_fill
1638
+ cell.font = black_bold_font
1639
+
1640
+ value = safe_str(cell.value)
1641
+ if row > header_row:
1642
+ if is_country_result_issue(value):
1643
+ cell.fill = issue_fill
1644
+ cell.font = red_font
1645
+ if value == "PASS":
1646
+ cell.fill = pass_fill
1647
+ cell.font = green_font
1648
+
1649
+ for col_idx in range(1, ws.max_column + 1):
1650
+ col_letter = get_column_letter(col_idx)
1651
+ header = safe_str(ws.cell(row=header_row, column=col_idx).value)
1652
+
1653
+ if header in ["NO.", "NO"]:
1654
+ ws.column_dimensions[col_letter].width = 8
1655
+ elif header in ["ν•œκΈ€ ν‘œμ€€ν™” λͺ…μΉ­", "ν•œκΈ€ μ„±λΆ„λͺ…"]:
1656
+ ws.column_dimensions[col_letter].width = 30
1657
+ elif header in ["INGREDIENT NAME (INCI)", "INCI Name"]:
1658
+ ws.column_dimensions[col_letter].width = 36
1659
+ elif header == "FUNCTION":
1660
+ ws.column_dimensions[col_letter].width = 18
1661
+ elif header == "CAS.No":
1662
+ ws.column_dimensions[col_letter].width = 18
1663
+ elif header == "SOURCE":
1664
+ ws.column_dimensions[col_letter].width = 28
1665
+ elif "%(w/w)" in header or "formula" in header.lower():
1666
+ ws.column_dimensions[col_letter].width = 15
1667
+ elif header == "Result":
1668
+ ws.column_dimensions[col_letter].width = 45
1669
+ elif header in ["λΉ„κ³ ", "검색 원문"]:
1670
+ ws.column_dimensions[col_letter].width = 60
1671
+ else:
1672
+ ws.column_dimensions[col_letter].width = 38
1673
+
1674
+ ws.freeze_panes = "A5" if ws.title == "Formula Ingredients Statement" else "A2"
1675
+
1676
+ wb.save(path)
1677
+
1678
+
1679
+ # ============================================================
1680
+ # 12. 메인 처리
1681
+ # ============================================================
1682
+
1683
+ def process(countries, file, product_name="", use_mfds_db=True):
1684
+ global RAW_SEARCH_LOGS
1685
+ RAW_SEARCH_LOGS = []
1686
+
1687
+ try:
1688
+ if not file:
1689
+ return None, None, "❌ μ—‘μ…€ νŒŒμΌμ„ μ—…λ‘œλ“œν•΄μ£Όμ„Έμš”."
1690
+ if not countries:
1691
+ return None, None, "❌ μŠ€ν¬λ¦¬λ‹ κ΅­κ°€λ₯Ό μ„ νƒν•΄μ£Όμ„Έμš”."
1692
+
1693
+ df = pd.read_excel(file.name)
1694
+ grouped_materials, meta = make_grouped_materials(df)
1695
+ if not grouped_materials:
1696
+ return None, None, "❌ μ—‘μ…€μ—μ„œ μ›λ£Œ 정보λ₯Ό 읽지 λͺ»ν–ˆμŠ΅λ‹ˆλ‹€. 컬럼λͺ… λ˜λŠ” 합계/footer μœ„μΉ˜λ₯Ό ν™•μΈν•΄μ£Όμ„Έμš”."
1697
+
1698
+ ingredient_totals = meta["ingredient_totals"]
1699
+ ingredient_amount_parts = meta["ingredient_amount_parts"]
1700
+ mfds_df = load_mfds_detail_db() if use_mfds_db else pd.DataFrame()
1701
+
1702
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
1703
+
1704
+ row_items = []
1705
+ for material in grouped_materials:
1706
+ components = material["Components"]
1707
+ for idx, comp in enumerate(components):
1708
+ is_first = idx == 0
1709
+ target_id = f"row_{len(row_items)}"
1710
+ row_data = {
1711
+ "NO": material["NO"] if is_first else "",
1712
+ "Trade name(κ΅­λ¬Έ)": material["Trade name(κ΅­λ¬Έ)"] if is_first else "",
1713
+ "Trade name(영문)": material["Trade name(영문)"] if is_first else "",
1714
+ "ν•œκΈ€ μ„±λΆ„λͺ…": comp["ν•œκΈ€ μ„±λΆ„λͺ…"],
1715
+ "INCI Name": comp["INCI Name"],
1716
+ "Contents\n(w/w %)": comp["Contents(w/w %)"] if is_first else "",
1717
+ "In formula\n(w/w %)": comp["In formula(w/w %)"],
1718
+ "Result": "",
1719
+ }
1720
+ row_items.append({"target_id": target_id, "material": material, "component": comp, "row_data": row_data, "notes": []})
1721
+
1722
+ for country in countries:
1723
+ col_name = display_country(country)
1724
+ gpt_targets = []
1725
+
1726
+ for item in row_items:
1727
+ local_result = evaluate_local_rules(country, item["material"], item["component"], ingredient_totals, ingredient_amount_parts)
1728
+ if local_result is not None:
1729
+ item["row_data"][col_name] = local_result.get("κ²°κ³Ό", "")
1730
+ note = safe_str(local_result.get("λΉ„κ³ ", "-"))
1731
+ if note and note != "-":
1732
+ item["notes"].append(f"{col_name}: {note}")
1733
+ log_search_context(item["target_id"], country, item["component"], local_result.get("κ²°κ³Ό", ""), "LOCAL_RULE", note if note and note != "-" else "둜컬 κ³ μ • κ·œμΉ™ μš°μ„  νŒμ •")
1734
+ continue
1735
+
1736
+ mfds_result = None
1737
+ if use_mfds_db and mfds_df is not None and not mfds_df.empty:
1738
+ mfds_result = evaluate_mfds_detail_rule(country, item["material"], item["component"], mfds_df)
1739
+
1740
+ if mfds_result is not None:
1741
+ item["row_data"][col_name] = mfds_result.get("κ²°κ³Ό", "")
1742
+ note = safe_str(mfds_result.get("λΉ„κ³ ", "-"))
1743
+ if note and note != "-":
1744
+ item["notes"].append(f"{col_name}: {note}")
1745
+ log_search_context(item["target_id"], country, item["component"], mfds_result.get("κ²°κ³Ό", ""), "MFDS_DETAIL_DB", note)
1746
+ continue
1747
+
1748
+ gpt_targets.append({"target_id": item["target_id"], "material": item["material"], "component": item["component"]})
1749
+
1750
+ batch_results = evaluate_components_with_llm_batch(country, gpt_targets, llm)
1751
+
1752
+ for item in row_items:
1753
+ if col_name in item["row_data"]:
1754
+ continue
1755
+ result = batch_results.get(item["target_id"])
1756
+ if result is None:
1757
+ result = {"λŒ€ν‘œ INCI": safe_str(item["component"].get("INCI Name", "")) or "-", "κ²°κ³Ό": "확인 ν•„μš”", "λΉ„κ³ ": "batch κ²°κ³Ό λˆ„λ½"}
1758
+ item["row_data"][col_name] = result.get("κ²°κ³Ό", "")
1759
+ note = safe_str(result.get("λΉ„κ³ ", "-"))
1760
+ if note and note != "-":
1761
+ item["notes"].append(f"{col_name}: {note}")
1762
+
1763
+ country_cols = [display_country(c) for c in countries]
1764
+ for item in row_items:
1765
+ row_data = item["row_data"]
1766
+ row_data["Result"] = build_integrated_result(row_data, country_cols)
1767
+ row_data["λΉ„κ³ "] = " / ".join(item["notes"]) if item["notes"] else "-"
1768
+
1769
+ formula_df = make_formula_statement_rows(row_items)
1770
+ regulatory_df = make_regulatory_summary_rows(row_items, country_cols)
1771
+
1772
+ raw_columns = ["target_id", "κ΅­κ°€/채널", "μ„±λΆ„λͺ…", "INCI Name", "νŒμ •", "좜처", "검색 원문"]
1773
+ raw_df = pd.DataFrame(RAW_SEARCH_LOGS)
1774
+ if raw_df.empty:
1775
+ raw_df = pd.DataFrame(columns=raw_columns)
1776
+ else:
1777
+ for col in raw_columns:
1778
+ if col not in raw_df.columns:
1779
+ raw_df[col] = ""
1780
+ raw_df = raw_df[raw_columns]
1781
+
1782
+ formula_total = sum_formula_percent(formula_df)
1783
+ safe_country_name = "_".join([re.sub(r"[^a-zA-Z0-9κ°€-힣_-]", "_", str(c)) for c in countries])
1784
+ product_part = safe_filename(product_name) if safe_str(product_name) else "product"
1785
+ out_path = str(OUTPUT_DIR / f"screening_result_{product_part}_{safe_country_name}.xlsx")
1786
+
1787
+ write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw_df)
1788
+
1789
+ issue_count = len(regulatory_df)
1790
+ mfds_count = len(mfds_df) if mfds_df is not None else 0
1791
+
1792
+ msg = (
1793
+ "βœ… 뢄석 μ™„λ£Œ\n"
1794
+ f"- Product Name: {safe_str(product_name) or '-'}\n"
1795
+ f"- μ „μ„±λΆ„ ν–‰ 수: {len(formula_df)}개\n"
1796
+ f"- In formula 합계: {format_amount(formula_total)}%\n"
1797
+ f"- μž¬κ²€ν†  ν•„μš” μ„±λΆ„: {issue_count}개\n"
1798
+ f"- MFDS 상세 DB ν–‰ 수: {mfds_count}개\n"
1799
+ "- κ²°κ³Ό νŒŒμΌμ€ 3개 μ‹œνŠΈλ‘œ μ €μž₯ν–ˆμŠ΅λ‹ˆλ‹€.\n"
1800
+ " 1) Formula Ingredients Statement: κ°„μ†Œν™” μ „μ„±λΆ„ν‘œ\n"
1801
+ " 2) Regulatory Screening Summary: 문제 μžˆλŠ” μ„±λΆ„λ§Œ ꡭ가별 μš”μ•½\n"
1802
+ " 3) Raw Search Log: 둜컬 κ·œμΉ™/MFDS/GPT 검색 κ·Όκ±° 둜그\n"
1803
+ "- νŒμ • μš°μ„ μˆœμœ„: 둜컬 κ³ μ • κ·œμΉ™ β†’ MFDS 상세 DB β†’ ꡭ가별 FAISS/GPT\n"
1804
+ "- GPT 호좜 μ „ 검색 원문에 μ‹€μ œ μ„±λΆ„λͺ…이 μ—†μœΌλ©΄ GPTλ₯Ό ν˜ΈμΆœν•˜μ§€ μ•Šκ³  'ν•΄λ‹Ή 자료 λ‚΄ μ œν•œ κ·Όκ±° μ—†μŒ'으둜 μ²˜λ¦¬ν•©λ‹ˆλ‹€.\n"
1805
+ "- MergedCell column_letter 였λ₯˜ μˆ˜μ • μ™„λ£Œ λ²„μ „μž…λ‹ˆλ‹€.\n"
1806
+ "- public share linkκ°€ μƒμ„±λ˜λ„λ‘ share=True둜 μ‹€ν–‰ν•©λ‹ˆλ‹€."
1807
+ )
1808
+
1809
+ return formula_df, out_path, msg
1810
+
1811
+ except Exception as e:
1812
+ tb = traceback.format_exc()
1813
+ print(tb)
1814
+ return None, None, f"❌ 였λ₯˜ λ°œμƒ: {str(e)}\n\n{tb[-3000:]}"
1815
+
1816
+
1817
+ # ============================================================
1818
+ # 13. Gradio UI
1819
+ # ============================================================
1820
+
1821
+ with gr.Blocks(css=custom_css) as demo:
1822
+ gr.Markdown("# 🌍 reBom Regulatory Screening AI")
1823
+ gr.Markdown("### κΈ€λ‘œλ²Œ ν™”μž₯ν’ˆ 규제 기반 μ „μ„±λΆ„ μŠ€ν¬λ¦¬λ‹ + MFDS 상세 DB 연동")
1824
+
1825
+ with gr.Row():
1826
+ gr.Button("πŸšͺ λ‘œκ·Έμ•„μ›ƒ", link="/logout?all_session=false", variant="secondary")
1827
+
1828
+ with gr.Tab("πŸš€ μŠ€ν¬λ¦¬λ‹"):
1829
+ country = gr.CheckboxGroup(
1830
+ choices=get_country_folders(),
1831
+ value=[],
1832
+ label="🌍 κ΅­κ°€ / 채널 선택",
1833
+ elem_id="country_checks",
1834
+ )
1835
+
1836
+ refresh = gr.Button("πŸ”„ 폴더/규제파일 μƒˆλ‘œκ³ μΉ¨")
1837
+
1838
+ product_name = gr.Textbox(label="μ œν’ˆλͺ… / PRODUCT NAME", placeholder="예: Mania Holic Sunscreen Pack")
1839
+
1840
+ file = gr.File(label="μ „μ„±λΆ„ μ—‘μ…€ μ—…λ‘œλ“œ", file_types=[".xlsx"])
1841
+
1842
+ use_mfds_db = gr.Checkbox(label="MFDS 상세 DB μš°μ„  반영", value=True)
1843
+
1844
+ btn = gr.Button("πŸš€ 뢄석 μ‹œμž‘", variant="primary")
1845
+
1846
+ df_out = gr.Dataframe(label="미리보기 - Formula Ingredients Statement", wrap=True, interactive=False)
1847
+ file_out = gr.File(label="κ²°κ³Ό λ‹€μš΄λ‘œλ“œ")
1848
+ msg_out = gr.Textbox(label="μƒνƒœ / 였λ₯˜ λ©”μ‹œμ§€", interactive=False, lines=14)
1849
+
1850
+ refresh.click(fn=refresh_country_choices_and_clear_cache, inputs=country, outputs=country)
1851
+
1852
+ try:
1853
+ auto_refresh_timer = gr.Timer(15)
1854
+ auto_refresh_timer.tick(fn=refresh_country_choices_keep_selection, inputs=country, outputs=country)
1855
+ except Exception as e:
1856
+ print(f"μžλ™ κ΅­κ°€ λͺ©λ‘ κ°±μ‹  타이머 λΉ„ν™œμ„±ν™”: {e}")
1857
+
1858
+ file.change(fn=preview_excel, inputs=file, outputs=df_out)
1859
+ btn.click(process, inputs=[country, file, product_name, use_mfds_db], outputs=[df_out, file_out, msg_out])
1860
+
1861
+ with gr.Tab("πŸ‡°πŸ‡· MFDS 상세 DB 관리"):
1862
+ gr.Markdown(
1863
+ """
1864
+ ### MFDS 상세 DB μ‚¬μš© 방식
1865
+
1866
+ μ˜μ•½ν’ˆμ•ˆμ „λ‚˜λΌ μ‚¬μ΄νŠΈλŠ” μžλ™ 접속이 λ§‰νžˆκ±°λ‚˜ 동적 νŽ˜μ΄μ§€ 문제둜 λΆˆμ•ˆμ •ν•  수 μžˆμ–΄μ„œ,
1867
+ 이 μ•±μ—μ„œλŠ” **μ‚¬μ΄νŠΈ μ‹€μ‹œκ°„ 크둀링 λŒ€μ‹  상세정보 μ—‘μ…€ DB 방식**으둜 μ—°λ™ν•©λ‹ˆλ‹€.
1868
+
1869
+ μ—‘μ…€ 파일λͺ…은 μžλ™μœΌλ‘œ μ•„λž˜ μ΄λ¦„μœΌλ‘œ μ €μž₯λ©λ‹ˆλ‹€.
1870
+
1871
+ `MFDS_ꡭ가별_κΈˆμ§€μ œν•œ_상세.xlsx`
1872
+
1873
+ ν•„μˆ˜ 컬럼:
1874
+ - μ›λ£Œλͺ…
1875
+ - INCI
1876
+ - CAS.No
1877
+ - ꡬ뢄
1878
+ - κ΅­κ°€
1879
+ - κ·œμ œλ‚΄μš©
1880
+ - ν•œλ„
1881
+ - 쑰건
1882
+ - 좜처
1883
+ - 상세원문
1884
+ """
1885
+ )
1886
+
1887
+ template_btn = gr.Button("πŸ“„ MFDS 상세 DB ν…œν”Œλ¦Ώ λ‹€μš΄λ‘œλ“œ")
1888
+ template_file = gr.File(label="ν…œν”Œλ¦Ώ λ‹€μš΄λ‘œλ“œ")
1889
+ template_msg = gr.Textbox(label="ν…œν”Œλ¦Ώ μƒνƒœ", interactive=False, lines=3)
1890
+ template_btn.click(download_mfds_template, inputs=[], outputs=[template_file, template_msg])
1891
+
1892
+ mfds_upload = gr.File(label="MFDS 상세 DB μ—‘μ…€ μ—…λ‘œλ“œ", file_types=[".xlsx"])
1893
+ mfds_save_btn = gr.Button("πŸ“₯ μ—…λ‘œλ“œ 엑셀을 MFDS 상세 DB둜 μ €μž₯", variant="primary")
1894
+ mfds_db_file = gr.File(label="ν˜„μž¬ MFDS 상세 DB λ‹€μš΄λ‘œλ“œ")
1895
+ mfds_db_msg = gr.Textbox(label="MFDS DB μƒνƒœ", lines=8, interactive=False)
1896
+ mfds_save_btn.click(upload_mfds_db, inputs=mfds_upload, outputs=[mfds_db_file, mfds_db_msg])
1897
+
1898
+
1899
+ # ============================================================
1900
+ # 14. 둜그인 인증
1901
+ # ============================================================
1902
+
1903
+ USER_DB = {
1904
+ "jin2li@rebom.kr": "qwer0515!",
1905
+ "jkh@rebom.kr": "rebom123!",
1906
+ "member2": "1111",
1907
+ }
1908
+
1909
+
1910
+ def auth_fn(username, password):
1911
+ username = str(username).strip()
1912
+ password = str(password).strip()
1913
+ return username in USER_DB and USER_DB[username] == password
1914
+
1915
+
1916
+ # ============================================================
1917
+ # 15. μ•± μ‹€ν–‰
1918
+ # ============================================================
1919
+
1920
+ try:
1921
+ demo.launch(
1922
+ server_name="0.0.0.0",
1923
+ server_port=7860,
1924
+ share=True,
1925
+ ssr_mode=False,
1926
+ auth=auth_fn,
1927
+ allowed_paths=ALLOWED_PATHS,
1928
+ blocked_paths=BLOCKED_PATHS,
1929
+ show_api=False,
1930
+ footer_links=[],
1931
+ app_kwargs={"docs_url": None, "redoc_url": None, "openapi_url": None},
1932
+ )
1933
+ except TypeError:
1934
+ demo.launch(
1935
+ server_name="0.0.0.0",
1936
+ server_port=7860,
1937
+ share=True,
1938
+ auth=auth_fn,
1939
+ allowed_paths=ALLOWED_PATHS,
1940
+ blocked_paths=BLOCKED_PATHS,
1941
+ )