jin2li commited on
Commit
de2c42b
·
verified ·
1 Parent(s): 217de4e

Update app.py

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