Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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,
|
| 670 |
-
|
| 671 |
-
raw.
|
| 672 |
-
alias.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
)
|