jin2li commited on
Commit
6c87d2d
ยท
verified ยท
1 Parent(s): de2c42b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +768 -0
app.py CHANGED
@@ -585,4 +585,772 @@ def get_current_db_signature(country):
585
  cached = VECTOR_DB_CACHE.get(folder)
586
  if isinstance(cached, dict):
587
  return cached.get("signature_hash")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
588
  return None
 
585
  cached = VECTOR_DB_CACHE.get(folder)
586
  if isinstance(cached, dict):
587
  return cached.get("signature_hash")
588
+ return None
589
+
590
+ # ============================================================
591
+ # 4. ์ž…๋ ฅ ์—‘์…€ ๋ฏธ๋ฆฌ๋ณด๊ธฐ / ์ปฌ๋Ÿผ ์ธ์‹
592
+ # ============================================================
593
+
594
+ def preview_excel(file):
595
+ if not file:
596
+ return None
597
+ try:
598
+ return pd.read_excel(file.name)
599
+ except Exception as e:
600
+ return pd.DataFrame({"์˜ค๋ฅ˜": [str(e)]})
601
+
602
+
603
+ def find_best_col(df, keywords, default_index=None, exclude_cols=None):
604
+ exclude_cols = exclude_cols or []
605
+ scores = []
606
+
607
+ for idx, col in enumerate(df.columns):
608
+ if col in exclude_cols:
609
+ continue
610
+
611
+ header = str(col).lower()
612
+ values = df[col].dropna().astype(str).str.strip()
613
+ sample = " ".join(values.head(80).tolist()).lower()
614
+
615
+ score = 0
616
+
617
+ for kw in keywords:
618
+ if kw.lower() in header:
619
+ score += 30
620
+
621
+ markers = [
622
+ "aqua", "water", "glycerin", "octocrylene", "homosalate",
623
+ "octisalate", "avobenzone", "niacinamide", "phenoxyethanol",
624
+ "limonene", "linalool", "citral", "extract", "acid",
625
+ "ceramide", "glycol", "retinol",
626
+ ]
627
+
628
+ if any(x in sample for x in markers):
629
+ if any(k.lower() in ["inci", "ingredient", "์„ฑ๋ถ„", "์ „์„ฑ๋ถ„", "๊ตฌ์„ฑ", "inci name"] for k in keywords):
630
+ score += 10
631
+
632
+ scores.append((score, idx, col))
633
+
634
+ scores = sorted(scores, reverse=True, key=lambda x: (x[0], -x[1]))
635
+
636
+ if scores and scores[0][0] > 0:
637
+ return scores[0][2]
638
+
639
+ if default_index is not None and len(df.columns) > default_index:
640
+ return df.columns[default_index]
641
+
642
+ return df.columns[0]
643
+
644
+
645
+ def find_numeric_col(df, keywords, default_index=None, exclude_cols=None, prefer_many_values=True):
646
+ exclude_cols = exclude_cols or []
647
+ candidates = []
648
+
649
+ for idx, col in enumerate(df.columns):
650
+ if col in exclude_cols:
651
+ continue
652
+
653
+ header = str(col).lower()
654
+ values = df[col].dropna()
655
+
656
+ if values.empty:
657
+ continue
658
+
659
+ count = values.apply(is_numeric_like).sum()
660
+ if count <= 0:
661
+ continue
662
+
663
+ score = 0
664
+
665
+ for kw in keywords:
666
+ if kw.lower() in header:
667
+ score += 30
668
+
669
+ candidates.append({
670
+ "col": col,
671
+ "idx": idx,
672
+ "score": score,
673
+ "count": count,
674
+ "non_null": len(values),
675
+ })
676
+
677
+ if not candidates:
678
+ if default_index is not None and len(df.columns) > default_index:
679
+ return df.columns[default_index]
680
+ return None
681
+
682
+ if prefer_many_values:
683
+ candidates = sorted(candidates, key=lambda x: (x["score"], x["non_null"], x["idx"]), reverse=True)
684
+ else:
685
+ candidates = sorted(candidates, key=lambda x: (x["score"], -x["non_null"], -x["idx"]), reverse=True)
686
+
687
+ return candidates[0]["col"]
688
+
689
+
690
+ def find_main_columns(df):
691
+ no_col = find_best_col(df, ["no", "๋ฒˆํ˜ธ", "์ˆœ๋ฒˆ"], default_index=0)
692
+
693
+ korean_ing_col = find_best_col(
694
+ df,
695
+ ["ํ•œ๊ธ€ ํ‘œ์ค€ํ™” ๋ช…์นญ", "ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", "๊ตญ๋ฌธ ์„ฑ๋ถ„๋ช…", "ํ•œ๊ธ€์„ฑ๋ถ„๋ช…", "korean", "๊ตญ๋ฌธinci", "์„ฑ๋ถ„๋ช…"],
696
+ default_index=1 if len(df.columns) > 1 else None,
697
+ exclude_cols=[no_col],
698
+ )
699
+
700
+ inci_col = find_best_col(
701
+ df,
702
+ ["ingredient name (inci)", "inci name", "inci", "ingredient", "์ „์„ฑ๋ถ„", "๊ตฌ์„ฑ"],
703
+ default_index=2 if len(df.columns) > 2 else None,
704
+ exclude_cols=[no_col, korean_ing_col],
705
+ )
706
+
707
+ function_col = find_best_col(
708
+ df,
709
+ ["function", "๊ธฐ๋Šฅ", "์šฉ๋„"],
710
+ default_index=3 if len(df.columns) > 3 else None,
711
+ exclude_cols=[no_col, korean_ing_col, inci_col],
712
+ )
713
+
714
+ cas_col = find_best_col(
715
+ df,
716
+ ["cas.no", "cas no", "cas", "cas๋ฒˆํ˜ธ", "cas no."],
717
+ default_index=4 if len(df.columns) > 4 else None,
718
+ exclude_cols=[no_col, korean_ing_col, inci_col, function_col],
719
+ )
720
+
721
+ source_col = find_best_col(
722
+ df,
723
+ ["source", "์ถœ์ฒ˜", "icid"],
724
+ default_index=5 if len(df.columns) > 5 else None,
725
+ exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col],
726
+ )
727
+
728
+ formula_col = find_numeric_col(
729
+ df,
730
+ ["%(w/w)", "w/w", "in formula", "formula", "์ฒ˜๋ฐฉ", "์ตœ์ข…", "์ œํ’ˆ ๋‚ด", "์ œํ’ˆ๋‚ด", "๋ฐฐํ•ฉ๋Ÿ‰", "ํ•จ๋Ÿ‰", "%"],
731
+ default_index=6 if len(df.columns) > 6 else None,
732
+ exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col],
733
+ prefer_many_values=True,
734
+ )
735
+
736
+ trade_ko_col = find_best_col(
737
+ df,
738
+ ["trade name(๊ตญ๋ฌธ)", "trade name ๊ตญ๋ฌธ", "์›๋ฃŒ๋ช…", "์ƒํ’ˆ๋ช…", "๊ตญ๋ฌธ"],
739
+ default_index=None,
740
+ exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col, formula_col],
741
+ )
742
+
743
+ trade_en_col = find_best_col(
744
+ df,
745
+ ["trade name(์˜๋ฌธ)", "trade name ์˜๋ฌธ", "trade", "raw material", "material", "์˜๋ฌธ"],
746
+ default_index=None,
747
+ exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col, formula_col, trade_ko_col],
748
+ )
749
+
750
+ return {
751
+ "no_col": no_col,
752
+ "korean_ing_col": korean_ing_col,
753
+ "inci_col": inci_col,
754
+ "function_col": function_col,
755
+ "cas_col": cas_col,
756
+ "source_col": source_col,
757
+ "formula_col": formula_col,
758
+ "trade_ko_col": trade_ko_col,
759
+ "trade_en_col": trade_en_col,
760
+ }
761
+
762
+
763
+ # ============================================================
764
+ # 5. ์ž…๋ ฅ ์—‘์…€ ์ •๋ฆฌ / ์ „์„ฑ๋ถ„ ํ–‰ ์ƒ์„ฑ
765
+ # ============================================================
766
+
767
+ def clean_input_df(df, cols):
768
+ no_col = cols["no_col"]
769
+ korean_ing_col = cols["korean_ing_col"]
770
+ inci_col = cols["inci_col"]
771
+
772
+ footer_markers = [
773
+ "commitment of the manufacturer",
774
+ "the manufacturer here",
775
+ "it is illegal",
776
+ "rebom co",
777
+ "myeonghaksandanseo",
778
+ "sejong special",
779
+ "tel :",
780
+ "fax :",
781
+ "lab no.",
782
+ "permission",
783
+ ]
784
+
785
+ keep_indices = []
786
+ footer_started = False
787
+
788
+ for idx, row in df.iterrows():
789
+ row_values = [safe_str(v) for v in row.values]
790
+ row_text = " ".join([v for v in row_values if v]).strip()
791
+ row_text_lower = row_text.lower()
792
+
793
+ if not row_text:
794
+ continue
795
+
796
+ no_text = safe_str(row.get(no_col, "")).lower() if no_col in df.columns else ""
797
+ korean_text = safe_str(row.get(korean_ing_col, "")).lower() if korean_ing_col in df.columns else ""
798
+ inci_text = safe_str(row.get(inci_col, "")).lower() if inci_col in df.columns else ""
799
+
800
+ if no_text in ["no", "๋ฒˆํ˜ธ", "์ˆœ๋ฒˆ"]:
801
+ continue
802
+
803
+ if korean_text in ["ํ•œ๊ธ€ ํ‘œ์ค€ํ™” ๋ช…์นญ", "ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", "ํ•œ๊ธ€์„ฑ๋ถ„๋ช…", "๊ตญ๋ฌธ ์„ฑ๋ถ„๋ช…"]:
804
+ continue
805
+
806
+ if inci_text in ["ingredient name (inci)", "inci", "inci name"]:
807
+ continue
808
+
809
+ if no_text.startswith("ํ•ฉ๊ณ„") or korean_text.startswith("ํ•ฉ๊ณ„") or inci_text.startswith("total"):
810
+ footer_started = True
811
+ continue
812
+
813
+ if any(marker in row_text_lower for marker in footer_markers):
814
+ footer_started = True
815
+ continue
816
+
817
+ if footer_started:
818
+ continue
819
+
820
+ keep_indices.append(idx)
821
+
822
+ return df.loc[keep_indices].reset_index(drop=True)
823
+
824
+
825
+ def make_grouped_materials(df):
826
+ cols = find_main_columns(df)
827
+ cleaned_df = clean_input_df(df, cols)
828
+
829
+ no_col = cols["no_col"]
830
+ korean_ing_col = cols["korean_ing_col"]
831
+ inci_col = cols["inci_col"]
832
+ function_col = cols["function_col"]
833
+ cas_col = cols["cas_col"]
834
+ source_col = cols["source_col"]
835
+ formula_col = cols["formula_col"]
836
+ trade_ko_col = cols.get("trade_ko_col")
837
+ trade_en_col = cols.get("trade_en_col")
838
+
839
+ row_materials = []
840
+
841
+ for _, row in cleaned_df.iterrows():
842
+ no_value = format_no(row.get(no_col, "")) if no_col in row else ""
843
+ korean_ing = safe_str(row.get(korean_ing_col, "")) if korean_ing_col in row else ""
844
+ inci_name = safe_str(row.get(inci_col, "")) if inci_col in row else ""
845
+
846
+ if not korean_ing and not inci_name:
847
+ continue
848
+
849
+ function_value = safe_str(row.get(function_col, "")) if function_col and function_col in row else ""
850
+ cas_value = safe_str(row.get(cas_col, "")) if cas_col and cas_col in row else ""
851
+ source_value = safe_str(row.get(source_col, "")) if source_col and source_col in row else ""
852
+ formula_value = format_amount(row.get(formula_col)) if formula_col and formula_col in row else ""
853
+
854
+ if not source_value:
855
+ source_value = "ICID"
856
+
857
+ trade_ko = safe_str(row.get(trade_ko_col, "")) if trade_ko_col and trade_ko_col in row else korean_ing
858
+ trade_en = safe_str(row.get(trade_en_col, "")) if trade_en_col and trade_en_col in row else inci_name
859
+
860
+ component = {
861
+ "ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…": korean_ing,
862
+ "INCI Name": inci_name,
863
+ "FUNCTION": function_value,
864
+ "CAS.No": cas_value,
865
+ "SOURCE": source_value,
866
+ "In formula(w/w %)": formula_value,
867
+ "amount_float": to_number(row.get(formula_col)) if formula_col and formula_col in row else None,
868
+ }
869
+
870
+ material = {
871
+ "NO": no_value,
872
+ "Trade name(๊ตญ๋ฌธ)": trade_ko,
873
+ "Trade name(์˜๋ฌธ)": trade_en,
874
+ "Components": [component],
875
+ }
876
+
877
+ row_materials.append(material)
878
+
879
+ ingredient_totals = defaultdict(float)
880
+ ingredient_amount_parts = defaultdict(list)
881
+
882
+ for material in row_materials:
883
+ comp = material["Components"][0]
884
+ identity = get_identity_text(material, comp)
885
+ amount = comp.get("amount_float")
886
+ if amount is None:
887
+ continue
888
+
889
+ for canonical, rule in FRAGRANCE_ALLERGEN_RULES.items():
890
+ for alias in rule.get("aliases", []):
891
+ alias_norm = normalize_text(alias)
892
+ if alias_norm and alias_norm in identity:
893
+ ingredient_totals[canonical] += amount
894
+ ingredient_amount_parts[canonical].append(amount)
895
+
896
+ meta = {
897
+ "cols": cols,
898
+ "cleaned_df": cleaned_df,
899
+ "ingredient_totals": ingredient_totals,
900
+ "ingredient_amount_parts": ingredient_amount_parts,
901
+ }
902
+
903
+ return row_materials, meta
904
+
905
+
906
+ # ============================================================
907
+ # 6. ์‹์•ฝ์ฒ˜ ์‹ค์‹œ๊ฐ„ ์กฐํšŒ
908
+ # ============================================================
909
+
910
+ def extract_terms_for_mfds_live(row_items):
911
+ terms = []
912
+
913
+ for item in row_items:
914
+ comp = item["component"]
915
+ for value in [comp.get("INCI Name", ""), comp.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", "")]:
916
+ value = safe_str(value)
917
+ if value and len(normalize_compact(value)) >= 3:
918
+ terms.append(value)
919
+
920
+ seen = set()
921
+ unique = []
922
+
923
+ for term in terms:
924
+ key = normalize_compact(term)
925
+ if key and key not in seen:
926
+ seen.add(key)
927
+ unique.append(term)
928
+
929
+ return unique
930
+
931
+
932
+ def mfds_live_visible_text(page):
933
+ try:
934
+ html = page.content()
935
+ if BeautifulSoup is not None:
936
+ soup = BeautifulSoup(html, "html.parser")
937
+ for tag in soup(["script", "style", "nav", "footer", "header"]):
938
+ tag.decompose()
939
+ return soup.get_text(separator=" ")
940
+ return page.locator("body").inner_text(timeout=5000)
941
+ except Exception:
942
+ try:
943
+ return page.locator("body").inner_text(timeout=5000)
944
+ except Exception:
945
+ return ""
946
+
947
+
948
+ def mfds_live_fill_search_input(page, term):
949
+ selectors = [
950
+ "input[type='search']",
951
+ "input[type='text']",
952
+ "input:not([type])",
953
+ ]
954
+
955
+ for selector in selectors:
956
+ try:
957
+ loc = page.locator(selector)
958
+ for i in range(min(loc.count(), 20)):
959
+ item = loc.nth(i)
960
+ try:
961
+ if item.is_visible(timeout=1000) and item.is_enabled(timeout=1000):
962
+ item.fill(term, timeout=3000)
963
+ return True
964
+ except Exception:
965
+ continue
966
+ except Exception:
967
+ continue
968
+
969
+ return False
970
+
971
+
972
+ def mfds_live_click_search(page):
973
+ for txt in ["๊ฒ€์ƒ‰", "์กฐํšŒ", "Search"]:
974
+ try:
975
+ loc = page.get_by_text(txt, exact=True)
976
+ if loc.count() > 0:
977
+ loc.first.click(timeout=3000)
978
+ return True
979
+ except Exception:
980
+ pass
981
+
982
+ for selector in ["button", "input[type='submit']", "a"]:
983
+ try:
984
+ loc = page.locator(selector)
985
+ for i in range(min(loc.count(), 20)):
986
+ item = loc.nth(i)
987
+ try:
988
+ if selector == "input[type='submit']":
989
+ item.click(timeout=3000)
990
+ return True
991
+
992
+ text = item.inner_text(timeout=500)
993
+ if "๊ฒ€์ƒ‰" in text or "์กฐํšŒ" in text:
994
+ item.click(timeout=3000)
995
+ return True
996
+ except Exception:
997
+ continue
998
+ except Exception:
999
+ continue
1000
+
1001
+ return False
1002
+
1003
+
1004
+ def mfds_live_click_result_row(page, term):
1005
+ term_norm = normalize_compact(term)
1006
+
1007
+ for selector in ["table tbody tr", "tbody tr", "tr"]:
1008
+ try:
1009
+ rows = page.locator(selector)
1010
+ for i in range(min(rows.count(), 30)):
1011
+ row = rows.nth(i)
1012
+ try:
1013
+ row_text = row.inner_text(timeout=1000)
1014
+ except Exception:
1015
+ continue
1016
+
1017
+ if term_norm and term_norm in normalize_compact(row_text):
1018
+ row.click(timeout=3000)
1019
+ page.wait_for_timeout(1500)
1020
+ return True
1021
+ except Exception:
1022
+ continue
1023
+
1024
+ try:
1025
+ loc = page.get_by_text(term, exact=False)
1026
+ if loc.count() > 0:
1027
+ loc.first.click(timeout=3000)
1028
+ page.wait_for_timeout(1500)
1029
+ return True
1030
+ except Exception:
1031
+ pass
1032
+
1033
+ return False
1034
+
1035
+
1036
+ def parse_mfds_live_text(term, text):
1037
+ clean = " ".join(safe_str(text).split())
1038
+
1039
+ if not clean:
1040
+ return []
1041
+
1042
+ lower_clean = clean.lower()
1043
+
1044
+ country_patterns = {
1045
+ "EU": ["eu", "์œ ๋Ÿฝ", "์œ ๋Ÿฝ์—ฐํ•ฉ", "european union", "europe"],
1046
+ "FDA": ["๋ฏธ๊ตญ", "usa", "fda", "united states"],
1047
+ "Korea": ["ํ•œ๊ตญ", "๋Œ€ํ•œ๋ฏผ๊ตญ", "korea"],
1048
+ "์ผ๋ณธ": ["์ผ๋ณธ", "japan"],
1049
+ "์ค‘๊ตญ": ["์ค‘๊ตญ", "china"],
1050
+ "ASEAN": ["asean", "์•„์„ธ์•ˆ"],
1051
+ "UK": ["์˜๊ตญ", "uk", "united kingdom"],
1052
+ }
1053
+
1054
+ rows = []
1055
+
1056
+ for country, aliases in country_patterns.items():
1057
+ found_index = -1
1058
+
1059
+ for alias in aliases:
1060
+ idx = lower_clean.find(alias)
1061
+ if idx >= 0:
1062
+ found_index = idx
1063
+ break
1064
+
1065
+ if found_index < 0:
1066
+ continue
1067
+
1068
+ start = max(0, found_index - 350)
1069
+ end = min(len(clean), found_index + 1000)
1070
+ snippet = clean[start:end]
1071
+ snippet_lower = snippet.lower()
1072
+
1073
+ category = "์ œํ•œ"
1074
+ if any(k in snippet_lower for k in ["๊ธˆ์ง€", "์‚ฌ์šฉ๊ธˆ์ง€", "๋ฐฐํ•ฉ๊ธˆ์ง€", "prohibited", "banned", "not allowed"]):
1075
+ category = "๊ธˆ์ง€"
1076
+
1077
+ limit = ""
1078
+ limit_match = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*%", snippet)
1079
+ if limit_match:
1080
+ limit = limit_match.group(0).replace(" ", "")
1081
+
1082
+ rows.append({
1083
+ "์›๋ฃŒ๋ช…": term,
1084
+ "INCI": term,
1085
+ "CAS.No": "",
1086
+ "๊ตฌ๋ถ„": category,
1087
+ "๊ตญ๊ฐ€": country,
1088
+ "๊ทœ์ œ๋‚ด์šฉ": snippet[:500],
1089
+ "ํ•œ๋„": limit,
1090
+ "์กฐ๊ฑด": "",
1091
+ "์ถœ์ฒ˜": "MFDS live: " + MFDS_LIVE_URL,
1092
+ "์ƒ์„ธ์›๋ฌธ": clean[:5000],
1093
+ })
1094
+
1095
+ return rows
1096
+
1097
+
1098
+ def mfds_live_lookup_terms(terms, max_terms=30, headless=True):
1099
+ if not PLAYWRIGHT_AVAILABLE or sync_playwright is None:
1100
+ return pd.DataFrame(), "playwright ๋ฏธ์„ค์น˜ ๋˜๋Š” ๋ธŒ๋ผ์šฐ์ € ๋ฏธ์„ค์น˜"
1101
+
1102
+ terms = [safe_str(t) for t in terms if safe_str(t)]
1103
+ terms = terms[:int(max_terms)] if max_terms else terms[:30]
1104
+
1105
+ all_rows = []
1106
+ errors = []
1107
+
1108
+ try:
1109
+ with sync_playwright() as p:
1110
+ browser = p.chromium.launch(headless=bool(headless))
1111
+ context = browser.new_context(
1112
+ viewport={"width": 1400, "height": 1000},
1113
+ user_agent="Mozilla/5.0 reBom Regulatory Screening",
1114
+ )
1115
+ page = context.new_page()
1116
+
1117
+ for idx, term in enumerate(terms, start=1):
1118
+ try:
1119
+ print(f"MFDS ์‹ค์‹œ๊ฐ„ ์กฐํšŒ {idx}/{len(terms)}: {term}")
1120
+
1121
+ page.goto(MFDS_LIVE_URL, wait_until="domcontentloaded", timeout=30000)
1122
+ page.wait_for_timeout(2000)
1123
+
1124
+ if not mfds_live_fill_search_input(page, term):
1125
+ errors.append(f"{term}: ๊ฒ€์ƒ‰ ์ž…๋ ฅ์ฐฝ ์ฐพ๊ธฐ ์‹คํŒจ")
1126
+ continue
1127
+
1128
+ if not mfds_live_click_search(page):
1129
+ try:
1130
+ page.keyboard.press("Enter")
1131
+ except Exception:
1132
+ pass
1133
+
1134
+ page.wait_for_timeout(2500)
1135
+
1136
+ mfds_live_click_result_row(page)
1137
+ page.wait_for_timeout(1500)
1138
+
1139
+ text = mfds_live_visible_text(page)
1140
+ rows = parse_mfds_live_text(term, text)
1141
+
1142
+ if rows:
1143
+ all_rows.extend(rows)
1144
+ else:
1145
+ errors.append(f"{term}: ๊ตญ๊ฐ€๋ณ„ ์ƒ์„ธ์ •๋ณด ๋ฏธ๊ฒ€์ถœ")
1146
+
1147
+ except Exception as e:
1148
+ errors.append(f"{term}: {e}")
1149
+
1150
+ context.close()
1151
+ browser.close()
1152
+
1153
+ except Exception as e:
1154
+ return pd.DataFrame(), f"MFDS ๋ธŒ๋ผ์šฐ์ € ์‹คํ–‰ ์‹คํŒจ: {e}"
1155
+
1156
+ df = pd.DataFrame(all_rows)
1157
+ msg = f"MFDS ์‹ค์‹œ๊ฐ„ ์กฐํšŒ ์™„๋ฃŒ: ๊ฒ€์ƒ‰์–ด {len(terms)}๊ฐœ, ๊ฒฐ๊ณผ {len(df)}ํ–‰"
1158
+
1159
+ if errors:
1160
+ msg += " / ์ผ๋ถ€ ์‹คํŒจ: " + " ; ".join(errors[:5])
1161
+ if len(errors) > 5:
1162
+ msg += f" ์™ธ {len(errors) - 5}๊ฑด"
1163
+
1164
+ return df, msg
1165
+
1166
+
1167
+ def ingredient_matches_mfds_row(material, component, row):
1168
+ identity_values = [
1169
+ component.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", ""),
1170
+ component.get("INCI Name", ""),
1171
+ material.get("Trade name(๊ตญ๋ฌธ)", ""),
1172
+ material.get("Trade name(์˜๋ฌธ)", ""),
1173
+ ]
1174
+
1175
+ identity = normalize_compact(" ".join([safe_str(x) for x in identity_values if safe_str(x)]))
1176
+ row_terms = [row.get("์›๋ฃŒ๋ช…", ""), row.get("INCI", ""), row.get("CAS.No", "")]
1177
+
1178
+ for term in row_terms:
1179
+ term_norm = normalize_compact(term)
1180
+ if term_norm and len(term_norm) >= 3 and term_norm in identity:
1181
+ return True
1182
+
1183
+ return False
1184
+
1185
+
1186
+ def mfds_row_country_matches(country, row_country):
1187
+ row_country_norm = normalize_compact(row_country)
1188
+ col = display_country(country)
1189
+ aliases = [country, col, country_key(country)]
1190
+
1191
+ if col == "Korea":
1192
+ aliases += ["ํ•œ๊ตญ", "๋Œ€ํ•œ๋ฏผ๊ตญ", "KOREA", "KR"]
1193
+ elif col == "FDA":
1194
+ aliases += ["๋ฏธ๊ตญ", "USA", "US", "United States", "FDA"]
1195
+ elif col == "EU":
1196
+ aliases += ["EU", "์œ ๋Ÿฝ", "์œ ๋Ÿฝ์—ฐํ•ฉ", "European Union", "Europe"]
1197
+
1198
+ aliases_norm = [normalize_compact(x) for x in aliases if safe_str(x)]
1199
+ return any(alias and alias in row_country_norm for alias in aliases_norm)
1200
+
1201
+
1202
+ def evaluate_mfds_detail_rule(country, material, component, mfds_df):
1203
+ if mfds_df is None or mfds_df.empty:
1204
+ return None
1205
+
1206
+ hits = []
1207
+
1208
+ for _, row in mfds_df.iterrows():
1209
+ if ingredient_matches_mfds_row(material, component, row) and mfds_row_country_matches(country, row.get("๊ตญ๊ฐ€", "")):
1210
+ hits.append(row)
1211
+
1212
+ if not hits:
1213
+ return None
1214
+
1215
+ row = hits[0]
1216
+ category = safe_str(row.get("๊ตฌ๋ถ„", "")) or "์ œํ•œ"
1217
+ regulation = safe_str(row.get("๊ทœ์ œ๋‚ด์šฉ", ""))
1218
+ limit = safe_str(row.get("ํ•œ๋„", ""))
1219
+ source = safe_str(row.get("์ถœ์ฒ˜", "MFDS live"))
1220
+
1221
+ parts = [category]
1222
+
1223
+ if limit:
1224
+ parts.append(f"ํ•œ๋„ {limit}")
1225
+
1226
+ if regulation:
1227
+ parts.append(regulation[:300])
1228
+
1229
+ result_text = " / ".join([p for p in parts if p])
1230
+
1231
+ return {
1232
+ "๋Œ€ํ‘œ INCI": safe_str(component.get("INCI Name", "")) or safe_str(row.get("์›๋ฃŒ๋ช…", "")) or "-",
1233
+ "๊ฒฐ๊ณผ": result_text,
1234
+ "ํ‘œ์‹œ๋ฌธ๊ตฌ": normalize_formula_country_text(result_text, display_country(country), component.get("INCI Name", "")),
1235
+ "๋น„๊ณ ": source,
1236
+ }
1237
+
1238
+
1239
+ # ============================================================
1240
+ # 7. ๋กœ์ปฌ ๊ทœ์น™ ํŒ์ •
1241
+ # ============================================================
1242
+
1243
+ def evaluate_limit_rule(country, material, component, rule_group, rule_type_name):
1244
+ ckey = country_key(country)
1245
+ key = match_rule_key(material, component, rule_group)
1246
+
1247
+ if not key:
1248
+ return None
1249
+
1250
+ rule = rule_group[key]
1251
+ country_rule = rule.get(ckey)
1252
+
1253
+ if not country_rule:
1254
+ return None
1255
+
1256
+ label = rule.get("label", key)
1257
+ amount = component.get("amount_float")
1258
+ amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1259
+ status = country_rule.get("status", "allowed")
1260
+ formula_text = country_rule.get("formula_text", "")
1261
+
1262
+ if status == "prohibited":
1263
+ return {
1264
+ "๋Œ€ํ‘œ INCI": label,
1265
+ "๊ฒฐ๊ณผ": f"{label} ๋ฐฐํ•ฉ๊ธˆ์ง€ / ํ˜„์žฌ ํ•จ๋Ÿ‰ {amount_text}% / ์žฌ๊ฒ€ํ†  ํ•„์š”",
1266
+ "ํ‘œ์‹œ๋ฌธ๊ตฌ": formula_text or "๋ฐฐํ•ฉ๊ธˆ์ง€",
1267
+ "๋น„๊ณ ": "-",
1268
+ }
1269
+
1270
+ limit = country_rule.get("limit")
1271
+
1272
+ if limit is not None:
1273
+ if amount is not None and amount > limit:
1274
+ result_text = f"{rule_type_name} / {label} ํ˜„์žฌ ํ•จ๋Ÿ‰ {amount_text}%, ํ•œ๋„ {format_percent(limit)}% ์ดˆ๊ณผ(์žฌ๊ฒ€ํ†  ํ•„์š”)"
1275
+ else:
1276
+ result_text = f"{rule_type_name} / {label} ํ˜„์žฌ ํ•จ๋Ÿ‰ {amount_text}%, ํ•œ๋„ {format_percent(limit)}% ์ด๋‚ด(ํ†ต๊ณผ)"
1277
+
1278
+ return {
1279
+ "๋Œ€ํ‘œ INCI": label,
1280
+ "๊ฒฐ๊ณผ": result_text,
1281
+ "ํ‘œ์‹œ๋ฌธ๊ตฌ": formula_text or f"๋ฐฐํ•ฉํ•œ๋„: {format_percent(limit)}%",
1282
+ "๋น„๊ณ ": "-",
1283
+ }
1284
+
1285
+ return {
1286
+ "๋Œ€ํ‘œ INCI": label,
1287
+ "๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
1288
+ "ํ‘œ์‹œ๋ฌธ๊ตฌ": "Pass",
1289
+ "๋น„๊ณ ": "-",
1290
+ }
1291
+
1292
+
1293
+ def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts):
1294
+ ckey = country_key(country)
1295
+ amount = component.get("amount_float")
1296
+
1297
+ uv_result = evaluate_limit_rule(country, material, component, UV_FILTER_RULES, "UV ํ•„ํ„ฐ")
1298
+ if uv_result is not None:
1299
+ return uv_result
1300
+
1301
+ preservative_result = evaluate_limit_rule(country, material, component, PRESERVATIVE_RULES, "๋ณด์กด์ œ/์ œํ•œ์„ฑ๋ถ„")
1302
+ if preservative_result is not None:
1303
+ return preservative_result
1304
+
1305
+ functional_key = match_rule_key(material, component, FUNCTIONAL_KOREA_RULES)
1306
+
1307
+ if ckey == "KOREA" and functional_key:
1308
+ rule = FUNCTIONAL_KOREA_RULES[functional_key]
1309
+ amount_text = format_percent(amount) if amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1310
+ return {
1311
+ "๋Œ€ํ‘œ INCI": rule["label"],
1312
+ "๊ฒฐ๊ณผ": rule["result"].format(amount=amount_text),
1313
+ "ํ‘œ์‹œ๋ฌธ๊ตฌ": rule.get("formula_text", "๊ธฐ๋Šฅ์„ฑ ํ™•์ธ"),
1314
+ "๋น„๊ณ ": "๊ธฐ๋Šฅ์„ฑ ํ‘œ์‹œยท๊ด‘๊ณ  ์—ฌ๋ถ€ ํ™•์ธ",
1315
+ }
1316
+
1317
+ identity = get_identity_text(material, component)
1318
+
1319
+ for fragrance_key, rule in FRAGRANCE_ALLERGEN_RULES.items():
1320
+ matched = False
1321
+ for alias in rule.get("aliases", []):
1322
+ if normalize_text(alias) in identity:
1323
+ matched = True
1324
+ break
1325
+
1326
+ if not matched:
1327
+ continue
1328
+
1329
+ if ckey not in ["EU", "EU_FUTURE", "UK", "KOREA"]:
1330
+ continue
1331
+
1332
+ total_amount = ingredient_totals.get(fragrance_key, amount)
1333
+ total_text = format_percent(total_amount) if total_amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”"
1334
+
1335
+ result_text = (
1336
+ f"ํ–ฅ๋ฃŒ ์•Œ๋ ˆ๋ฅด๊ฒ / {rule['label']} ์ด {total_text}%, "
1337
+ f"Leave-on ๊ธฐ์ค€ {format_percent(rule['leave_on'])}%, "
1338
+ f"Wash-off ๊ธฐ์ค€ {format_percent(rule['wash_off'])}% ํ™•์ธ ํ•„์š”"
1339
+ )
1340
+
1341
+ return {
1342
+ "๋Œ€ํ‘œ INCI": rule["label"],
1343
+ "๊ฒฐ๊ณผ": result_text,
1344
+ "ํ‘œ์‹œ๋ฌธ๊ตฌ": "ํ‘œ์‹œ๊ธฐ์ค€ ํ™•์ธ",
1345
+ "๋น„๊ณ ": "-",
1346
+ }
1347
+
1348
+ if amount is None:
1349
+ return {
1350
+ "๋Œ€ํ‘œ INCI": safe_str(component.get("INCI Name", "")) or "-",
1351
+ "๊ฒฐ๊ณผ": "ํ•จ๋Ÿ‰ ์ •๋ณด ์—†์Œ / In formula(w/w %) ํ™•์ธ ํ•„์š”",
1352
+ "ํ‘œ์‹œ๋ฌธ๊ตฌ": "ํ•จ๋Ÿ‰ ํ™•์ธ",
1353
+ "๋น„๊ณ ": "-",
1354
+ }
1355
+
1356
  return None