diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -14,6 +14,15 @@ # - MergedCell column_letter 오류 수정 완료 # ============================================================ +# ============================================================ +# reBom Regulatory Screening AI +# - 국가별 규제 폴더 안에서만 검색 +# - FAISS 디스크 캐시 +# - GPT는 검색된 원문 안에서만 판정 +# - 식약처 사이트 실시간 조회 옵션 +# - Formular Ingredients Statement 원본 양식 출력 +# ============================================================ + import os import re import json @@ -25,12 +34,17 @@ from collections import defaultdict import pandas as pd import pdfplumber import gradio as gr -from bs4 import BeautifulSoup + +try: + from bs4 import BeautifulSoup +except Exception: + BeautifulSoup = None try: from playwright.sync_api import sync_playwright PLAYWRIGHT_AVAILABLE = True except Exception: + sync_playwright = None PLAYWRIGHT_AVAILABLE = False from openpyxl import load_workbook @@ -54,8 +68,8 @@ OUTPUT_DIR = (BASE_DIR / "outputs").resolve() OUTPUT_DIR.mkdir(parents=True, exist_ok=True) FAISS_CACHE_DIR = ".faiss_cache" -MFDS_DETAIL_DB_PATH = BASE_DIR / "MFDS_국가별_금지제한_상세.xlsx" MFDS_LIVE_URL = "https://nedrug.mfds.go.kr/pbp/CCBDF01" +NO_EVIDENCE_TEXT = "해당 자료 내 제한 근거 없음" VECTOR_DB_CACHE = {} EVAL_CACHE = {} @@ -70,50 +84,42 @@ COUNTRY_ORDER = [ ] COUNTRY_DISPLAY = { + "EU": "EU", "유럽": "EU", "EUROPE": "EU", + "FDA": "FDA", "미국": "FDA", "USA": "FDA", "US": "FDA", + "KOREA": "Korea", "한국": "Korea", "KR": "Korea", + "JAPAN": "일본", "일본": "일본", "JP": "일본", + "CHINA": "중국", "중국": "중국", "CN": "중국", "ASEAN": "ASEAN", "아세안": "ASEAN", - "CALIFORNIA": "CALIFORNIA", "CA": "CALIFORNIA", "캘리포니아": "CALIFORNIA", - "CHINA": "중국", "CN": "중국", "중국": "중국", - "EU (FUTURE)": "EU (FUTURE)", "EU_FUTURE": "EU (FUTURE)", "EU FUTURE": "EU (FUTURE)", "EU-FUTURE": "EU (FUTURE)", - "EU": "EU", "E.U.": "EU", "EUROPE": "EU", "유럽": "EU", - "FDA": "미국", "USA": "미국", "US": "미국", "미국": "미국", - "JAPAN": "일본", "JP": "일본", "일본": "일본", - "KOREA": "한국", "KR": "한국", "한국": "한국", - "MEXICO": "MEXICO", "MX": "MEXICO", "멕시코": "MEXICO", - "SEPHORA": "SEPHORA", "TARGET": "TARGET", - "UK": "UK", "UNITED KINGDOM": "UK", "영국": "UK", - "ULTA": "ULTA", + "UK": "UK", "영국": "UK", + "EU (FUTURE)": "EU (FUTURE)", "EU_FUTURE": "EU (FUTURE)", + "CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO", + "SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA", } COUNTRY_FOLDER_ALIASES = { - "한국": "KOREA", "KOREA": "KOREA", "KR": "KOREA", - "일본": "JAPAN", "JAPAN": "JAPAN", "JP": "JAPAN", - "중국": "CHINA", "CHINA": "CHINA", "CN": "CHINA", - "미국": "FDA", "USA": "FDA", "US": "FDA", "FDA": "FDA", - "유럽": "EU", "EUROPE": "EU", "EU": "EU", - "EU (FUTURE)": "EU (FUTURE)", "EU_FUTURE": "EU (FUTURE)", "EU FUTURE": "EU (FUTURE)", "EU-FUTURE": "EU (FUTURE)", + "EU": "EU", "유럽": "EU", "EUROPE": "EU", + "FDA": "FDA", "미국": "FDA", "USA": "FDA", "US": "FDA", + "KOREA": "KOREA", "한국": "KOREA", "KR": "KOREA", + "JAPAN": "JAPAN", "일본": "JAPAN", "JP": "JAPAN", + "CHINA": "CHINA", "중국": "CHINA", "CN": "CHINA", "ASEAN": "ASEAN", "아세안": "ASEAN", - "CALIFORNIA": "CALIFORNIA", "CA": "CALIFORNIA", "캘리포니아": "CALIFORNIA", - "MEXICO": "MEXICO", "MX": "MEXICO", "멕시코": "MEXICO", - "SEPHORA": "SEPHORA", "TARGET": "TARGET", - "UK": "UK", "UNITED KINGDOM": "UK", "영국": "UK", - "ULTA": "ULTA", + "UK": "UK", "영국": "UK", + "EU (FUTURE)": "EU (FUTURE)", "EU_FUTURE": "EU (FUTURE)", "EU FUTURE": "EU (FUTURE)", + "CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO", + "SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA", } -BLOCKED_PATHS = [ - str(BASE_DIR / c) for c in COUNTRY_ORDER -] + [ +BLOCKED_PATHS = [str(BASE_DIR / c) for c in COUNTRY_ORDER] + [ str(BASE_DIR / FAISS_CACHE_DIR), str(BASE_DIR / ".env"), str(BASE_DIR / "__pycache__"), ] - ALLOWED_PATHS = [str(OUTPUT_DIR), str(BASE_DIR)] BATCH_SIZE = 40 RAG_TOP_K_BATCH = 4 RAG_TOP_K_SINGLE = 2 MEANINGFUL_HIT_K = 2 -NO_EVIDENCE_TEXT = "해당 자료 내 제한 근거 없음" custom_css = """ #country_checks .wrap, @@ -137,63 +143,41 @@ custom_css = """ # ============================================================ -# 1. 로컬 고정 규칙 +# 1. 로컬 규칙 # ============================================================ UV_FILTER_RULES = { "octocrylene": { "label": "Octocrylene", "aliases": ["octocrylene", "옥토크릴렌", "6197-30-4"], - "EU": {"status": "allowed", "limit": 10}, - "FDA": {"status": "allowed", "limit": 10}, - "KOREA": {"status": "allowed", "limit": 10}, - "JAPAN": {"status": "allowed", "limit": 10}, - "SEPHORA": {"status": "prohibited"}, + "EU": {"status": "allowed", "limit": 10, "formula_text": "배합 한도:\n스프레이: 9% /\n기타제품: 10%"}, + "FDA": {"status": "allowed", "limit": 10, "formula_text": "라벨링 필수"}, + "KOREA": {"status": "allowed", "limit": 10, "formula_text": "배합한도: 10%"}, + "JAPAN": {"status": "allowed", "limit": 10, "formula_text": "배합한도: 10%"}, + "SEPHORA": {"status": "prohibited", "formula_text": "배합금지"}, }, "homosalate": { "label": "Homosalate", "aliases": ["homosalate", "호모살레이트", "118-56-9"], - "EU": {"status": "allowed", "limit": 7.34}, - "FDA": {"status": "allowed", "limit": 15}, - "KOREA": {"status": "allowed", "limit": 10}, - "JAPAN": {"status": "allowed", "limit": 10}, - "SEPHORA": {"status": "allowed"}, + "EU": {"status": "allowed", "limit": 7.34, "formula_text": "배합한도: 7.34%"}, + "FDA": {"status": "allowed", "limit": 15, "formula_text": "배합한도: 15%"}, + "KOREA": {"status": "allowed", "limit": 10, "formula_text": "배합한도: 10%"}, + "JAPAN": {"status": "allowed", "limit": 10, "formula_text": "배합한도: 10%"}, }, "octisalate": { "label": "Octisalate / Ethylhexyl Salicylate", "aliases": ["octisalate", "ethylhexyl salicylate", "옥티살레이트", "118-60-5"], - "EU": {"status": "allowed", "limit": 5}, - "FDA": {"status": "allowed", "limit": 5}, - "KOREA": {"status": "allowed", "limit": 5}, - "JAPAN": {"status": "allowed", "limit": 5}, - "SEPHORA": {"status": "allowed"}, + "EU": {"status": "allowed", "limit": 5, "formula_text": "배합한도: 5%"}, + "FDA": {"status": "allowed", "limit": 5, "formula_text": "배합한도: 5%"}, + "KOREA": {"status": "allowed", "limit": 5, "formula_text": "배합한도: 5%"}, + "JAPAN": {"status": "allowed", "limit": 5, "formula_text": "배합한도: 5%"}, }, "avobenzone": { "label": "Avobenzone", "aliases": ["avobenzone", "butyl methoxydibenzoylmethane", "아보벤존", "70356-09-1"], - "EU": {"status": "allowed", "limit": 5}, - "FDA": {"status": "allowed", "limit": 3}, - "KOREA": {"status": "allowed", "limit": 5}, - "JAPAN": {"status": "allowed"}, - "SEPHORA": {"status": "allowed"}, - }, - "titanium dioxide": { - "label": "Titanium Dioxide", - "aliases": ["titanium dioxide", "티타늄디옥사이드", "ci 77891"], - "EU": {"status": "allowed"}, - "FDA": {"status": "allowed", "limit": 25}, - "KOREA": {"status": "allowed"}, - "JAPAN": {"status": "allowed"}, - "SEPHORA": {"status": "allowed"}, - }, - "zinc oxide": { - "label": "Zinc Oxide", - "aliases": ["zinc oxide", "징크옥사이드", "1314-13-2"], - "EU": {"status": "allowed"}, - "FDA": {"status": "allowed", "limit": 25}, - "KOREA": {"status": "allowed"}, - "JAPAN": {"status": "allowed"}, - "SEPHORA": {"status": "allowed"}, + "EU": {"status": "allowed", "limit": 5, "formula_text": "배합한도: 5%"}, + "FDA": {"status": "allowed", "limit": 3, "formula_text": "배합한도: 3%"}, + "KOREA": {"status": "allowed", "limit": 5, "formula_text": "배합한도: 5%"}, }, } @@ -201,18 +185,9 @@ PRESERVATIVE_RULES = { "phenoxyethanol": { "label": "Phenoxyethanol", "aliases": ["phenoxyethanol", "페녹시에탄올", "122-99-6"], - "EU": {"status": "allowed", "limit": 1}, - "KOREA": {"status": "allowed", "limit": 1}, - "JAPAN": {"status": "allowed", "limit": 1}, - "FDA": {"status": "allowed"}, - }, - "salicylic acid": { - "label": "Salicylic Acid", - "aliases": ["salicylic acid", "살리실릭애씨드", "69-72-7"], - "EU": {"status": "allowed", "limit": 2}, - "KOREA": {"status": "allowed"}, - "JAPAN": {"status": "allowed", "limit": 0.2}, - "FDA": {"status": "allowed"}, + "EU": {"status": "allowed", "limit": 1, "formula_text": "배합한도: 1%"}, + "KOREA": {"status": "allowed", "limit": 1, "formula_text": "배합한도: 1%"}, + "JAPAN": {"status": "allowed", "limit": 1, "formula_text": "배합한도: 1%"}, }, } @@ -220,67 +195,24 @@ FUNCTIONAL_KOREA_RULES = { "niacinamide": { "label": "Niacinamide", "aliases": ["niacinamide", "나이아신아마이드", "98-92-0"], - "result": "기능성화장품 검토 / Niacinamide 현재 함량 {amount}%, 미백 기능성 표시·광고 시 기능성화장품 요건 확인 필요", - "note": "단순 배합 자체가 아니라 미백 기능성 표시·광고 여부에 따라 검토", + "result": "기능성화장품 검토 / Niacinamide 현재 함량 {amount}%, 미백 기능성 표시·광고 시 요건 확인 필요", + "formula_text": "기능성 확인", }, "adenosine": { "label": "Adenosine", "aliases": ["adenosine", "아데노신", "58-61-7"], - "result": "기능성화장품 검토 / Adenosine 현재 함량 {amount}%, 주름개선 기능성 표시·광고 시 기능성화장품 요건 확인 필요", - "note": "단순 배합 자체가 아니라 주름개선 기능성 표시·광고 여부에 따라 검토", + "result": "기능성화장품 검토 / Adenosine 현재 함량 {amount}%, 주름개선 기능성 표시·광고 시 요건 확인 필요", + "formula_text": "기능성 확인", }, } FRAGRANCE_ALLERGEN_RULES = { - "limonene": { - "label": "Limonene", - "aliases": ["limonene", "d-limonene", "dl-limonene", "l-limonene", "리모넨"], - "leave_on": 0.001, - "wash_off": 0.01, - "extra": "peroxide value <20 mmol/L 확인 필요", - }, - "linalool": { - "label": "Linalool", - "aliases": ["linalool", "리날룰"], - "leave_on": 0.001, - "wash_off": 0.01, - "extra": "-", - }, - "citral": { - "label": "Citral", - "aliases": ["citral", "geranial", "neral", "시트랄"], - "leave_on": 0.001, - "wash_off": 0.01, - "extra": "-", - }, - "geraniol": { - "label": "Geraniol", - "aliases": ["geraniol", "제라니올"], - "leave_on": 0.001, - "wash_off": 0.01, - "extra": "-", - }, - "citronellol": { - "label": "Citronellol", - "aliases": ["citronellol", "시트로넬올"], - "leave_on": 0.001, - "wash_off": 0.01, - "extra": "-", - }, - "eugenol": { - "label": "Eugenol", - "aliases": ["eugenol", "유제놀"], - "leave_on": 0.001, - "wash_off": 0.01, - "extra": "-", - }, - "benzyl alcohol": { - "label": "Benzyl Alcohol", - "aliases": ["benzyl alcohol", "벤질알코올"], - "leave_on": 0.001, - "wash_off": 0.01, - "extra": "보존 목적 사용 시 별도 보존제 한도 검토 필요", - }, + "limonene": {"label": "Limonene", "aliases": ["limonene", "리모넨"], "leave_on": 0.001, "wash_off": 0.01}, + "linalool": {"label": "Linalool", "aliases": ["linalool", "리날룰"], "leave_on": 0.001, "wash_off": 0.01}, + "citral": {"label": "Citral", "aliases": ["citral", "시트랄"], "leave_on": 0.001, "wash_off": 0.01}, + "geraniol": {"label": "Geraniol", "aliases": ["geraniol", "제라니올"], "leave_on": 0.001, "wash_off": 0.01}, + "eugenol": {"label": "Eugenol", "aliases": ["eugenol", "유제놀"], "leave_on": 0.001, "wash_off": 0.01}, + "benzyl alcohol": {"label": "Benzyl Alcohol", "aliases": ["benzyl alcohol", "벤질알코올"], "leave_on": 0.001, "wash_off": 0.01}, } @@ -305,10 +237,6 @@ def normalize_compact(text): return re.sub(r"\s+", "", normalize_text(text)) -def display_country(country): - return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), str(country))) - - def country_key(country): text = safe_str(country).upper().replace("_", " ").replace("-", " ") text = re.sub(r"\s+", " ", text).strip() @@ -320,34 +248,14 @@ def country_key(country): "CHINA": "CHINA", "CN": "CHINA", "중국": "CHINA", "USA": "FDA", "US": "FDA", "미국": "FDA", "FDA": "FDA", "ASEAN": "ASEAN", "아세안": "ASEAN", - "CALIFORNIA": "CALIFORNIA", "CA": "CALIFORNIA", "캘리포니아": "CALIFORNIA", - "MEXICO": "MEXICO", "MX": "MEXICO", "멕시코": "MEXICO", - "SEPHORA": "SEPHORA", "TARGET": "TARGET", "UK": "UK", "UNITED KINGDOM": "UK", "영국": "UK", - "ULTA": "ULTA", + "SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA", } return mapping.get(text, text) -def mfds_country_aliases(country): - ckey = country_key(country) - alias_map = { - "EU": ["EU", "유럽", "유럽연합", "European Union", "Europe"], - "EU_FUTURE": ["EU", "유럽", "유럽연합", "European Union", "Europe", "EU FUTURE"], - "KOREA": ["한국", "대한민국", "KOREA", "KR"], - "JAPAN": ["일본", "JAPAN", "JP"], - "CHINA": ["중국", "CHINA", "CN"], - "FDA": ["미국", "USA", "US", "FDA", "United States"], - "ASEAN": ["ASEAN", "아세안"], - "UK": ["UK", "영국", "United Kingdom"], - "CALIFORNIA": ["California", "캘리포니아", "CA"], - "MEXICO": ["Mexico", "멕시코", "MX"], - "SEPHORA": ["SEPHORA"], - "TARGET": ["TARGET"], - "ULTA": ["ULTA"], - } - aliases = alias_map.get(ckey, [display_country(country), ckey, country]) - return [normalize_compact(x) for x in aliases if safe_str(x)] +def display_country(country): + return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), str(country))) def to_number(value): @@ -366,13 +274,6 @@ def is_numeric_like(value): return to_number(value) is not None -def format_no(value): - num = to_number(value) - if num is not None and float(num).is_integer(): - return str(int(num)) - return safe_str(value) - - def format_amount(value, digits=10): num = to_number(value) if num is None: @@ -386,6 +287,13 @@ def format_percent(value): return format_amount(value, digits=10) +def format_no(value): + num = to_number(value) + if num is not None and float(num).is_integer(): + return str(int(num)) + return safe_str(value) + + def stable_hash(obj): text = json.dumps(obj, ensure_ascii=False, sort_keys=True, default=str) return hashlib.sha256(text.encode("utf-8")).hexdigest() @@ -410,22 +318,6 @@ def get_embeddings(): return EMBEDDINGS_CACHE -def amount_status(amount, threshold, action_text): - threshold_text = format_percent(threshold) - if amount is None: - return f"{threshold_text}% 기준 / 현재 함량 확인 필요" - if amount > threshold: - return f"{threshold_text}% 초과({action_text})" - return f"{threshold_text}% 이하(통과, 표시 불필요)" - - -def build_calc_text(amounts): - clean_amounts = [a for a in amounts if a is not None] - if len(clean_amounts) <= 1: - return "" - return "(=" + "+".join(format_percent(a) for a in clean_amounts) + ")" - - def get_identity_text(material, component): texts = [ component.get("한글 성분명", ""), @@ -446,59 +338,12 @@ def match_rule_key(material, component, rule_dict): return None -def canonical_fragrance_name(material, component): - return match_rule_key(material, component, FRAGRANCE_ALLERGEN_RULES) - - def is_country_result_issue(text): text = safe_str(text) - if not text or text == "-": - return False - - pass_values = [ - "PASS", "pass", "제한 없음 (통과)", "제한없음 (통과)", - "해당없음", "해당 없음", "특이 규제 확인 없음", NO_EVIDENCE_TEXT, - ] - if text in pass_values: + if not text or text in ["-", NO_EVIDENCE_TEXT, "Pass", "PASS", "pass"]: return False - - issue_keywords = [ - "배합금지", "금지", "Prohibited", "prohibited", "초과", "부적합", - "재검토", "확인 필요", "자료 확인", "표시 필요", "사용 불가", - "사용불가", "불가", "주의", "경고", - ] - for keyword in issue_keywords: - if keyword in text: - return True - - pass_keywords = ["이내", "통과", "문제 없음", "한도 이내", "기준 이내"] - for keyword in pass_keywords: - if keyword in text: - return False - - return False - - -def compact_result_reason(text, max_len=18): - text = safe_str(text) - if not text: - return "" - text = text.replace("확인 필요 / 규제 세부 계산 재확인 필요", "확인 필요") - text = text.replace("기능성화장품 검토", "기능성 검토") - text = text.replace("Leave-on", "LO").replace("Wash-off", "WO") - if len(text) > max_len: - text = text[:max_len].rstrip() + "..." - return text - - -def build_integrated_result(row_data, selected_country_display_names): - issue_items = [] - for country_col in selected_country_display_names: - value = safe_str(row_data.get(country_col, "")) - if is_country_result_issue(value): - reason = compact_result_reason(value) - issue_items.append(f"{country_col}({reason})" if reason else country_col) - return "PASS" if not issue_items else "재검토 필요: " + ", ".join(issue_items) + keywords = ["배합금지", "금지", "초과", "부적합", "재검토", "확인 필요", "자료 확인", "표시 필요", "라벨링", "불가", "주의", "경고"] + return any(k in text for k in keywords) def log_search_context(target_id, country, component, result_text, source, context): @@ -513,228 +358,604 @@ def log_search_context(target_id, country, component, result_text, source, conte }) -def sum_formula_percent(formula_df): - total = 0.0 - if formula_df is None or formula_df.empty: - return total - for value in formula_df.get("%(w/w)", []): - num = to_number(value) - if num is not None: - total += num - return total - - -def make_country_cell_status(text): - """ - Formula Ingredients Statement의 국가별 칸에는 긴 문장 대신 짧은 판정만 표시한다. - 상세 설명과 근거는 Regulatory Screening Summary / Evidence Log에 남긴다. - """ +def normalize_formula_country_text(text, country_col="", inci_name="", amount_text=""): text = safe_str(text) + country_col = safe_str(country_col) + inci_norm = normalize_compact(inci_name) if not text or text == "-" or text == NO_EVIDENCE_TEXT: - return "" + return "Pass" lower = text.lower() - if "배합금지" in text or "사용금지" in text or "금지" in text or "prohibited" in lower: - return "FAIL" + if "octocrylene" in inci_norm or "옥토크릴렌" in inci_norm: + if country_col == "EU": + return "배합 한도:\n스프레이: 9% /\n기타제품: 10%" + if country_col == "FDA": + return "라벨링 필수" + if country_col == "Korea": + return "배합한도: 10%" + + if "homosalate" in inci_norm or "호모살레이트" in inci_norm: + if country_col == "EU": + return "배합한도: 7.34%" + if country_col == "FDA": + return "배합한도: 15%" + if country_col == "Korea": + return "배합한도: 10%" + + if "octisalate" in inci_norm or "ethylhexylsalicylate" in inci_norm or "옥티살레이트" in inci_norm: + return "배합한도: 5%" + + if "avobenzone" in inci_norm or "아보벤존" in inci_norm: + if country_col == "FDA": + return "배합한도: 3%" + return "배합한도: 5%" + if "배합금지" in text or "사용금지" in text or "금지" in text or "prohibited" in lower: + return "배합금지" if "초과" in text or "부적합" in text or "사용 불가" in text or "사용불가" in text: - return "FAIL" + return "한도 초과" + if "표시 필요" in text or "라벨" in text or "label" in lower: + return "라벨링 필수" - if "표시 필요" in text: - return "LABEL" + limit_match = re.search(r"한도\s*([0-9]+(?:\.[0-9]+)?\s*%)", text) + if limit_match: + return "배합한도: " + limit_match.group(1).replace(" ", "") - if "확인 필요" in text or "자료 확인" in text or "재검토" in text or "검토 필요" in text: - return "CHECK" + percent_match = re.search(r"([0-9]+(?:\.[0-9]+)?\s*%)", text) + if percent_match and ("한도" in text or "limit" in lower or "max" in lower): + return "배합한도: " + percent_match.group(1).replace(" ", "") + if "확인 필요" in text or "자료 확인" in text or "재검토" in text or "검토 필요" in text: + return "확인 필요" if "이내" in text or "통과" in text or "한도 이내" in text: - return "PASS" + return "Pass" - return "CHECK" + return text[:120] # ============================================================ -# 3. MFDS 상세 DB 엑셀 연동 +# 3. 국가 폴더 / 규제 DB # ============================================================ -def load_mfds_detail_db(): - columns = ["원료명", "INCI", "CAS.No", "구분", "국가", "규제내용", "한도", "조건", "출처", "상세원문"] - if not MFDS_DETAIL_DB_PATH.exists(): - return pd.DataFrame(columns=columns) - try: - df = pd.read_excel(MFDS_DETAIL_DB_PATH, dtype=str).fillna("") - for col in columns: - if col not in df.columns: - df[col] = "" - return df[columns] - except Exception as e: - print(f"MFDS 상세 DB 로딩 실패: {e}") - return pd.DataFrame(columns=columns) - - -def save_mfds_detail_db(df): - columns = ["원료명", "INCI", "CAS.No", "구분", "국가", "규제내용", "한도", "조건", "출처", "상세원문"] - if df is None or df.empty: - df = pd.DataFrame(columns=columns) - for col in columns: - if col not in df.columns: - df[col] = "" - df = df[columns].fillna("").drop_duplicates() - df.to_excel(MFDS_DETAIL_DB_PATH, index=False) - return str(MFDS_DETAIL_DB_PATH) - - -def create_empty_mfds_template(): - columns = ["원료명", "INCI", "CAS.No", "구분", "국가", "규제내용", "한도", "조건", "출처", "상세원문"] - template = pd.DataFrame([ - { - "원료명": "Retinol", - "INCI": "Retinol", - "CAS.No": "68-26-8", - "구분": "제한", - "국가": "EU", - "규제내용": "제품유형별 배합한도 적용", - "한도": "0.05% / 0.3%", - "조건": "제품유형 확인", - "출처": "MFDS 상세화면", - "상세원문": "식약처 상세화면에서 복사한 원문 입력", - } - ], columns=columns) - out_path = str(OUTPUT_DIR / "MFDS_국가별_금지제한_상세_템플릿.xlsx") - template.to_excel(out_path, index=False) - return out_path +def resolve_country_folder(country): + if not country or country == "폴더 없음": + return None + raw = safe_str(country) + alias = COUNTRY_FOLDER_ALIASES.get(raw, COUNTRY_FOLDER_ALIASES.get(raw.upper(), raw)) + candidates = [ + raw, alias, raw.upper(), alias.upper(), + raw.replace("_", " "), raw.replace("-", " "), + raw.replace("EU FUTURE", "EU (FUTURE)"), raw.replace("EU_FUTURE", "EU (FUTURE)"), + alias.replace("_", " "), alias.replace("-", " "), + ] + seen = [] + for item in candidates: + item = safe_str(item) + if item and item not in seen: + seen.append(item) + for item in seen: + if os.path.isdir(item): + return item + folder_map = {f.lower(): f for f in os.listdir(".") if os.path.isdir(f)} + for item in seen: + matched = folder_map.get(item.lower()) + if matched: + return matched + return alias -def ingredient_matches_mfds_row(material, component, row): - identity_values = [ - component.get("한글 성분명", ""), component.get("INCI Name", ""), - material.get("Trade name(국문)", ""), material.get("Trade name(영문)", ""), - ] - identity = normalize_compact(" ".join([safe_str(x) for x in identity_values if safe_str(x)])) - row_terms = [row.get("원료명", ""), row.get("INCI", ""), row.get("CAS.No", "")] - for term in row_terms: - term_norm = normalize_compact(term) - if term_norm and len(term_norm) >= 3 and term_norm in identity: - return True - return False +def get_country_folders(): + exclude = [".git", ".cache", "__pycache__", ".ipynb_checkpoints", ".venv", "venv", "node_modules", FAISS_CACHE_DIR, "outputs"] + folders = [f for f in os.listdir(".") if os.path.isdir(f) and f not in exclude] + existing = set(folders) + ordered = [c for c in COUNTRY_ORDER if c in existing] + extras = sorted([f for f in folders if f not in COUNTRY_ORDER]) + return ordered + extras if ordered or extras else COUNTRY_ORDER.copy() -def mfds_row_country_matches(country, row_country): - row_country_norm = normalize_compact(row_country) - if not row_country_norm: - return False - aliases = mfds_country_aliases(country) - return any(alias and alias in row_country_norm for alias in aliases) +def refresh_country_choices_keep_selection(current_values=None): + choices = get_country_folders() + current_values = current_values or [] + kept = [v for v in current_values if v in choices] + return gr.update(choices=choices, value=kept) -def evaluate_mfds_detail_rule(country, material, component, mfds_df): - if mfds_df is None or mfds_df.empty: - return None +def refresh_country_choices_and_clear_cache(current_values=None): + VECTOR_DB_CACHE.clear() + EVAL_CACHE.clear() + return refresh_country_choices_keep_selection(current_values) - hits = [] - for _, row in mfds_df.iterrows(): - if ingredient_matches_mfds_row(material, component, row) and mfds_row_country_matches(country, row.get("국가", "")): - hits.append(row) - if not hits: - return None +def get_regulatory_file_list(country_folder): + files = [] + if not country_folder or not os.path.isdir(country_folder): + return files + for root, dirs, filenames in os.walk(country_folder): + dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ["__pycache__", ".ipynb_checkpoints"]] + for filename in filenames: + ext = os.path.splitext(filename)[1].lower() + if ext not in SUPPORTED_REG_FILE_EXTENSIONS: + continue + path = os.path.join(root, filename) + try: + stat = os.stat(path) + except FileNotFoundError: + continue + files.append({"path": path, "relative_path": os.path.relpath(path, country_folder), "size": stat.st_size, "mtime_ns": stat.st_mtime_ns, "ext": ext}) + return sorted(files, key=lambda x: x["relative_path"].lower()) - priority = {"금지": 1, "배합금지": 1, "사용금지": 1, "제한": 2, "한도": 2, "표시": 3, "확인 필요": 4} - hits = sorted(hits, key=lambda r: priority.get(safe_str(r.get("구분", "")), 9)) - row = hits[0] - category = safe_str(row.get("구분", "")) or "제한" - regulation = safe_str(row.get("규제내용", "")) - limit = safe_str(row.get("한도", "")) - condition = safe_str(row.get("조건", "")) - source = safe_str(row.get("출처", "MFDS 상세정보")) +def read_text_file_with_fallback(file_path): + for enc in ["utf-8", "utf-8-sig", "cp949", "euc-kr", "latin-1"]: + try: + with open(file_path, "r", encoding=enc) as f: + return f.read() + except Exception: + continue + return "" - parts = [category] - if limit: - parts.append(f"한도 {limit}") - if regulation: - parts.append(regulation[:300]) - if condition: - parts.append(condition) - result_text = " / ".join([p for p in parts if p]) or "MFDS 국가별 금지/제한 상세정보 확인 필요" +def extract_text_from_regulatory_file(file_item): + path = file_item["path"] + rel = file_item["relative_path"] + ext = file_item["ext"] + texts = [] + try: + if ext == ".pdf": + with pdfplumber.open(path) as pdf: + for page_no, page in enumerate(pdf.pages, start=1): + text = page.extract_text() + if text: + texts.append(f"[파일: {rel}] [페이지: {page_no}]\n{text}") + elif ext == ".txt": + text = read_text_file_with_fallback(path) + if text: + texts.append(f"[파일: {rel}]\n{text}") + elif ext == ".csv": + try: + df = pd.read_csv(path, dtype=str) + except UnicodeDecodeError: + df = pd.read_csv(path, dtype=str, encoding="cp949") + texts.append(f"[파일: {rel}]\n{df.fillna('').to_string(index=False)}") + elif ext in [".xlsx", ".xls"]: + sheets = pd.read_excel(path, sheet_name=None, dtype=str) + for sheet_name, sheet_df in sheets.items(): + texts.append(f"[파일: {rel}] [시트: {sheet_name}]\n{sheet_df.fillna('').to_string(index=False)}") + except Exception as e: + print(f"규제 파일 읽기 오류: {path} / {e}") + return "\n\n".join(texts) + - return { - "대표 INCI": safe_str(component.get("INCI Name", "")) or safe_str(row.get("원료명", "")) or "-", - "결과": f"MFDS 국가별 참고정보 / {result_text}", - "비고": source, - } +def build_database(country): + folder = resolve_country_folder(country) + if not folder or not os.path.isdir(folder): + return None + files = get_regulatory_file_list(folder) + if not files: + return None + signature = tuple((f["relative_path"], f["size"], f["mtime_ns"]) for f in files) + sig_hash = stable_hash(signature) + cached = VECTOR_DB_CACHE.get(folder) + if isinstance(cached, dict) and cached.get("signature_hash") == sig_hash: + return cached.get("db") + + embeddings = get_embeddings() + os.makedirs(FAISS_CACHE_DIR, exist_ok=True) + cache_path = os.path.join(FAISS_CACHE_DIR, f"{safe_filename(folder)}_{sig_hash[:16]}") + meta_path = os.path.join(cache_path, "metadata.json") + if os.path.isdir(cache_path) and os.path.exists(meta_path): + try: + with open(meta_path, "r", encoding="utf-8") as f: + meta = json.load(f) + if meta.get("signature_hash") == sig_hash: + print(f"✅ FAISS 디스크 캐시 로드: {folder}") + db = FAISS.load_local(cache_path, embeddings, allow_dangerous_deserialization=True) + VECTOR_DB_CACHE[folder] = {"signature_hash": sig_hash, "db": db} + return db + except Exception as e: + print(f"FAISS 캐시 로드 실패: {folder} / {e}") -def upload_mfds_db(file): - if not file: - return None, "❌ MFDS 상세 DB 엑셀 파일을 업로드해주세요." + print(f"🔄 규제 DB 재색인: {folder} / 파일 {len(files)}개") + EVAL_CACHE.clear() + splitter = RecursiveCharacterTextSplitter(chunk_size=900, chunk_overlap=120) + chunks = [] + for item in files: + raw = extract_text_from_regulatory_file(item) + if raw: + chunks.extend(splitter.split_text(f"[국가/채널: {folder}] [출처파일: {item['relative_path']}]\n{raw}")) + if not chunks: + return None + db = FAISS.from_texts(chunks, embeddings) try: - df = pd.read_excel(file.name, dtype=str).fillna("") - out_path = save_mfds_detail_db(df) - loaded = load_mfds_detail_db() - return out_path, ( - "✅ MFDS 상세 DB 저장 완료\n" - f"- 저장 위치: {out_path}\n" - f"- 행 수: {len(loaded)}개\n" - "- 이후 스크리닝 탭에서 'MFDS 상세 DB 우선 반영'을 체크하면 적용됩니다." - ) + os.makedirs(cache_path, exist_ok=True) + db.save_local(cache_path) + with open(meta_path, "w", encoding="utf-8") as f: + json.dump({"country_folder": folder, "signature_hash": sig_hash, "file_count": len(files)}, f, ensure_ascii=False, indent=2) + print(f"✅ FAISS 디스크 캐시 저장: {cache_path}") except Exception as e: - tb = traceback.format_exc() - print(tb) - return None, f"❌ MFDS 상세 DB 저장 실패: {e}" + print(f"FAISS 캐시 저장 실패: {folder} / {e}") + VECTOR_DB_CACHE[folder] = {"signature_hash": sig_hash, "db": db} + return db + +def get_current_db_signature(country): + folder = resolve_country_folder(country) + cached = VECTOR_DB_CACHE.get(folder) + if isinstance(cached, dict): + return cached.get("signature_hash") + return None + + # ============================================================ +# 4. 입력 엑셀 미리보기 / 컬럼 인식 +# ============================================================ -def download_mfds_template(): +def preview_excel(file): + if not file: + return None try: - out_path = create_empty_mfds_template() - return out_path, "✅ MFDS 상세 DB 템플릿 생성 완료" + return pd.read_excel(file.name) except Exception as e: - return None, f"❌ 템플릿 생성 실패: {e}" + return pd.DataFrame({"오류": [str(e)]}) -# ============================================================ -# 3-1. MFDS 식약처 사이트 실시간 조회 -# ============================================================ +def find_best_col(df, keywords, default_index=None, exclude_cols=None): + exclude_cols = exclude_cols or [] + scores = [] -def extract_terms_for_mfds_live(row_items): - terms = [] - for item in row_items: - comp = item["component"] - for value in [comp.get("INCI Name", ""), comp.get("한글 성분명", "")]: - value = safe_str(value) - if value and len(normalize_compact(value)) >= 3: - terms.append(value) - seen = set() - unique = [] - for term in terms: - key = normalize_compact(term) - if key and key not in seen: - seen.add(key) - unique.append(term) - return unique + for idx, col in enumerate(df.columns): + if col in exclude_cols: + continue + header = str(col).lower() + values = df[col].dropna().astype(str).str.strip() + sample = " ".join(values.head(80).tolist()).lower() -def mfds_live_visible_text(page): - try: - html = page.content() - soup = BeautifulSoup(html, "html.parser") - for tag in soup(["script", "style", "nav", "footer", "header"]): - tag.decompose() - return soup.get_text(separator=" ") - except Exception: - try: - return page.locator("body").inner_text(timeout=5000) - except Exception: - return "" + score = 0 + for kw in keywords: + if kw.lower() in header: + score += 30 -def mfds_live_fill_search_input(page, term): - selectors = ["input[type='search']", "input[type='text']", "input:not([type])"] - for selector in selectors: - try: - loc = page.locator(selector) + markers = [ + "aqua", "water", "glycerin", "octocrylene", "homosalate", + "octisalate", "avobenzone", "niacinamide", "phenoxyethanol", + "limonene", "linalool", "citral", "extract", "acid", + "ceramide", "glycol", "retinol", + ] + + if any(x in sample for x in markers): + if any(k.lower() in ["inci", "ingredient", "성분", "전성분", "구성", "inci name"] for k in keywords): + score += 10 + + scores.append((score, idx, col)) + + scores = sorted(scores, reverse=True, key=lambda x: (x[0], -x[1])) + + if scores and scores[0][0] > 0: + return scores[0][2] + + if default_index is not None and len(df.columns) > default_index: + return df.columns[default_index] + + return df.columns[0] + + +def find_numeric_col(df, keywords, default_index=None, exclude_cols=None, prefer_many_values=True): + exclude_cols = exclude_cols or [] + candidates = [] + + for idx, col in enumerate(df.columns): + if col in exclude_cols: + continue + + header = str(col).lower() + values = df[col].dropna() + + if values.empty: + continue + + count = values.apply(is_numeric_like).sum() + if count <= 0: + continue + + score = 0 + + for kw in keywords: + if kw.lower() in header: + score += 30 + + candidates.append({ + "col": col, + "idx": idx, + "score": score, + "count": count, + "non_null": len(values), + }) + + if not candidates: + if default_index is not None and len(df.columns) > default_index: + return df.columns[default_index] + return None + + if prefer_many_values: + candidates = sorted(candidates, key=lambda x: (x["score"], x["non_null"], x["idx"]), reverse=True) + else: + candidates = sorted(candidates, key=lambda x: (x["score"], -x["non_null"], -x["idx"]), reverse=True) + + return candidates[0]["col"] + + +def find_main_columns(df): + no_col = find_best_col(df, ["no", "번호", "순번"], default_index=0) + + korean_ing_col = find_best_col( + df, + ["한글 표준화 명칭", "한글 성분명", "국문 성분명", "한글성분명", "korean", "국문inci", "성분명"], + default_index=1 if len(df.columns) > 1 else None, + exclude_cols=[no_col], + ) + + inci_col = find_best_col( + df, + ["ingredient name (inci)", "inci name", "inci", "ingredient", "전성분", "구성"], + default_index=2 if len(df.columns) > 2 else None, + exclude_cols=[no_col, korean_ing_col], + ) + + function_col = find_best_col( + df, + ["function", "기능", "용도"], + default_index=3 if len(df.columns) > 3 else None, + exclude_cols=[no_col, korean_ing_col, inci_col], + ) + + cas_col = find_best_col( + df, + ["cas.no", "cas no", "cas", "cas번호", "cas no."], + default_index=4 if len(df.columns) > 4 else None, + exclude_cols=[no_col, korean_ing_col, inci_col, function_col], + ) + + source_col = find_best_col( + df, + ["source", "출처", "icid"], + default_index=5 if len(df.columns) > 5 else None, + exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col], + ) + + formula_col = find_numeric_col( + df, + ["%(w/w)", "w/w", "in formula", "formula", "처방", "최종", "제품 내", "제품내", "배합량", "함량", "%"], + default_index=6 if len(df.columns) > 6 else None, + exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col], + prefer_many_values=True, + ) + + trade_ko_col = find_best_col( + df, + ["trade name(국문)", "trade name 국문", "원료명", "상품명", "국문"], + default_index=None, + exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col, formula_col], + ) + + trade_en_col = find_best_col( + df, + ["trade name(영문)", "trade name 영문", "trade", "raw material", "material", "영문"], + default_index=None, + exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col, formula_col, trade_ko_col], + ) + + return { + "no_col": no_col, + "korean_ing_col": korean_ing_col, + "inci_col": inci_col, + "function_col": function_col, + "cas_col": cas_col, + "source_col": source_col, + "formula_col": formula_col, + "trade_ko_col": trade_ko_col, + "trade_en_col": trade_en_col, + } + + +# ============================================================ +# 5. 입력 엑셀 정리 / 전성분 행 생성 +# ============================================================ + +def clean_input_df(df, cols): + no_col = cols["no_col"] + korean_ing_col = cols["korean_ing_col"] + inci_col = cols["inci_col"] + + footer_markers = [ + "commitment of the manufacturer", + "the manufacturer here", + "it is illegal", + "rebom co", + "myeonghaksandanseo", + "sejong special", + "tel :", + "fax :", + "lab no.", + "permission", + ] + + keep_indices = [] + footer_started = False + + for idx, row in df.iterrows(): + row_values = [safe_str(v) for v in row.values] + row_text = " ".join([v for v in row_values if v]).strip() + row_text_lower = row_text.lower() + + if not row_text: + continue + + no_text = safe_str(row.get(no_col, "")).lower() if no_col in df.columns else "" + korean_text = safe_str(row.get(korean_ing_col, "")).lower() if korean_ing_col in df.columns else "" + inci_text = safe_str(row.get(inci_col, "")).lower() if inci_col in df.columns else "" + + if no_text in ["no", "번호", "순번"]: + continue + + if korean_text in ["한글 표준화 명칭", "한글 성분명", "한글성분명", "국문 성분명"]: + continue + + if inci_text in ["ingredient name (inci)", "inci", "inci name"]: + continue + + if no_text.startswith("합계") or korean_text.startswith("합계") or inci_text.startswith("total"): + footer_started = True + continue + + if any(marker in row_text_lower for marker in footer_markers): + footer_started = True + continue + + if footer_started: + continue + + keep_indices.append(idx) + + return df.loc[keep_indices].reset_index(drop=True) + + +def make_grouped_materials(df): + cols = find_main_columns(df) + cleaned_df = clean_input_df(df, cols) + + no_col = cols["no_col"] + korean_ing_col = cols["korean_ing_col"] + inci_col = cols["inci_col"] + function_col = cols["function_col"] + cas_col = cols["cas_col"] + source_col = cols["source_col"] + formula_col = cols["formula_col"] + trade_ko_col = cols.get("trade_ko_col") + trade_en_col = cols.get("trade_en_col") + + row_materials = [] + + for _, row in cleaned_df.iterrows(): + no_value = format_no(row.get(no_col, "")) if no_col in row else "" + korean_ing = safe_str(row.get(korean_ing_col, "")) if korean_ing_col in row else "" + inci_name = safe_str(row.get(inci_col, "")) if inci_col in row else "" + + if not korean_ing and not inci_name: + continue + + function_value = safe_str(row.get(function_col, "")) if function_col and function_col in row else "" + cas_value = safe_str(row.get(cas_col, "")) if cas_col and cas_col in row else "" + source_value = safe_str(row.get(source_col, "")) if source_col and source_col in row else "" + formula_value = format_amount(row.get(formula_col)) if formula_col and formula_col in row else "" + + if not source_value: + source_value = "ICID" + + trade_ko = safe_str(row.get(trade_ko_col, "")) if trade_ko_col and trade_ko_col in row else korean_ing + trade_en = safe_str(row.get(trade_en_col, "")) if trade_en_col and trade_en_col in row else inci_name + + component = { + "한글 성분명": korean_ing, + "INCI Name": inci_name, + "FUNCTION": function_value, + "CAS.No": cas_value, + "SOURCE": source_value, + "In formula(w/w %)": formula_value, + "amount_float": to_number(row.get(formula_col)) if formula_col and formula_col in row else None, + } + + material = { + "NO": no_value, + "Trade name(국문)": trade_ko, + "Trade name(영문)": trade_en, + "Components": [component], + } + + row_materials.append(material) + + ingredient_totals = defaultdict(float) + ingredient_amount_parts = defaultdict(list) + + for material in row_materials: + comp = material["Components"][0] + identity = get_identity_text(material, comp) + amount = comp.get("amount_float") + if amount is None: + continue + + for canonical, rule in FRAGRANCE_ALLERGEN_RULES.items(): + for alias in rule.get("aliases", []): + alias_norm = normalize_text(alias) + if alias_norm and alias_norm in identity: + ingredient_totals[canonical] += amount + ingredient_amount_parts[canonical].append(amount) + + meta = { + "cols": cols, + "cleaned_df": cleaned_df, + "ingredient_totals": ingredient_totals, + "ingredient_amount_parts": ingredient_amount_parts, + } + + return row_materials, meta + + +# ============================================================ +# 6. 식약처 실시간 조회 +# ============================================================ + +def extract_terms_for_mfds_live(row_items): + terms = [] + + for item in row_items: + comp = item["component"] + for value in [comp.get("INCI Name", ""), comp.get("한글 성분명", "")]: + value = safe_str(value) + if value and len(normalize_compact(value)) >= 3: + terms.append(value) + + seen = set() + unique = [] + + for term in terms: + key = normalize_compact(term) + if key and key not in seen: + seen.add(key) + unique.append(term) + + return unique + + +def mfds_live_visible_text(page): + try: + html = page.content() + if BeautifulSoup is not None: + soup = BeautifulSoup(html, "html.parser") + for tag in soup(["script", "style", "nav", "footer", "header"]): + tag.decompose() + return soup.get_text(separator=" ") + return page.locator("body").inner_text(timeout=5000) + except Exception: + try: + return page.locator("body").inner_text(timeout=5000) + except Exception: + return "" + + +def mfds_live_fill_search_input(page, term): + selectors = [ + "input[type='search']", + "input[type='text']", + "input:not([type])", + ] + + for selector in selectors: + try: + loc = page.locator(selector) for i in range(min(loc.count(), 20)): item = loc.nth(i) try: @@ -745,6 +966,7 @@ def mfds_live_fill_search_input(page, term): continue except Exception: continue + return False @@ -757,25 +979,32 @@ def mfds_live_click_search(page): return True except Exception: pass + for selector in ["button", "input[type='submit']", "a"]: try: loc = page.locator(selector) for i in range(min(loc.count(), 20)): item = loc.nth(i) try: - text = item.inner_text(timeout=500) if selector != "input[type='submit']" else "검색" - if "검색" in text or selector == "input[type='submit']": + if selector == "input[type='submit']": + item.click(timeout=3000) + return True + + text = item.inner_text(timeout=500) + if "검색" in text or "조회" in text: item.click(timeout=3000) return True except Exception: continue except Exception: continue + return False def mfds_live_click_result_row(page, term): term_norm = normalize_compact(term) + for selector in ["table tbody tr", "tbody tr", "tr"]: try: rows = page.locator(selector) @@ -785,12 +1014,14 @@ def mfds_live_click_result_row(page, term): row_text = row.inner_text(timeout=1000) except Exception: continue + if term_norm and term_norm in normalize_compact(row_text): row.click(timeout=3000) page.wait_for_timeout(1500) return True except Exception: continue + try: loc = page.get_by_text(term, exact=False) if loc.count() > 0: @@ -799,40 +1030,56 @@ def mfds_live_click_result_row(page, term): return True except Exception: pass + return False def parse_mfds_live_text(term, text): clean = " ".join(safe_str(text).split()) + if not clean: return [] + lower_clean = clean.lower() + country_patterns = { "EU": ["eu", "유럽", "유럽연합", "european union", "europe"], - "미국": ["미국", "usa", "fda", "united states"], + "FDA": ["미국", "usa", "fda", "united states"], + "Korea": ["한국", "대한민국", "korea"], "일본": ["일본", "japan"], "중국": ["중국", "china"], "ASEAN": ["asean", "아세안"], - "한국": ["한국", "대한민국", "korea"], - "영국": ["영국", "uk", "united kingdom"], + "UK": ["영국", "uk", "united kingdom"], } + rows = [] + for country, aliases in country_patterns.items(): found_index = -1 + for alias in aliases: idx = lower_clean.find(alias) if idx >= 0: found_index = idx break + if found_index < 0: continue + start = max(0, found_index - 350) end = min(len(clean), found_index + 1000) snippet = clean[start:end] snippet_lower = snippet.lower() + category = "제한" if any(k in snippet_lower for k in ["금지", "사용금지", "배합금지", "prohibited", "banned", "not allowed"]): category = "금지" + + limit = "" + limit_match = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*%", snippet) + if limit_match: + limit = limit_match.group(0).replace(" ", "") + rows.append({ "원료명": term, "INCI": term, @@ -840,571 +1087,170 @@ def parse_mfds_live_text(term, text): "구분": category, "국가": country, "규제내용": snippet[:500], - "한도": "", + "한도": limit, "조건": "", "출처": "MFDS live: " + MFDS_LIVE_URL, "상세원문": clean[:5000], }) + return rows def mfds_live_lookup_terms(terms, max_terms=30, headless=True): - if not PLAYWRIGHT_AVAILABLE: - return pd.DataFrame(), "playwright 미설치: pip install playwright && python -m playwright install chromium 필요" + if not PLAYWRIGHT_AVAILABLE or sync_playwright is None: + return pd.DataFrame(), "playwright 미설치 또는 브라우저 미설치" + terms = [safe_str(t) for t in terms if safe_str(t)] terms = terms[:int(max_terms)] if max_terms else terms[:30] + all_rows = [] errors = [] + try: with sync_playwright() as p: browser = p.chromium.launch(headless=bool(headless)) - context = browser.new_context(viewport={"width": 1400, "height": 1000}, user_agent="Mozilla/5.0 reBom Regulatory Screening") + context = browser.new_context( + viewport={"width": 1400, "height": 1000}, + user_agent="Mozilla/5.0 reBom Regulatory Screening", + ) page = context.new_page() + for idx, term in enumerate(terms, start=1): try: print(f"MFDS 실시간 조회 {idx}/{len(terms)}: {term}") + page.goto(MFDS_LIVE_URL, wait_until="domcontentloaded", timeout=30000) page.wait_for_timeout(2000) + if not mfds_live_fill_search_input(page, term): errors.append(f"{term}: 검색 입력창 찾기 실패") continue + if not mfds_live_click_search(page): try: page.keyboard.press("Enter") except Exception: pass + page.wait_for_timeout(2500) + mfds_live_click_result_row(page, term) page.wait_for_timeout(1500) + text = mfds_live_visible_text(page) rows = parse_mfds_live_text(term, text) + if rows: all_rows.extend(rows) else: errors.append(f"{term}: 국가별 상세정보 미검출") + except Exception as e: errors.append(f"{term}: {e}") + context.close() browser.close() + except Exception as e: return pd.DataFrame(), f"MFDS 브라우저 실행 실패: {e}" + df = pd.DataFrame(all_rows) msg = f"MFDS 실시간 조회 완료: 검색어 {len(terms)}개, 결과 {len(df)}행" + if errors: msg += " / 일부 실패: " + " ; ".join(errors[:5]) if len(errors) > 5: msg += f" 외 {len(errors) - 5}건" - return df, msg - - -# ============================================================ -# 4. 국가 폴더 자동 인식 -# ============================================================ -def resolve_country_folder(country): - if not country or country == "폴더 없음": - return None + return df, msg - raw = safe_str(country) - alias = COUNTRY_FOLDER_ALIASES.get(raw, COUNTRY_FOLDER_ALIASES.get(raw.upper(), raw)) - candidates = [ - raw, - alias, - raw.upper(), - alias.upper(), - raw.replace("_", " "), - raw.replace("-", " "), - raw.replace("EU FUTURE", "EU (FUTURE)"), - raw.replace("EU_FUTURE", "EU (FUTURE)"), - alias.replace("_", " "), - alias.replace("-", " "), +def ingredient_matches_mfds_row(material, component, row): + identity_values = [ + component.get("한글 ��분명", ""), + component.get("INCI Name", ""), + material.get("Trade name(국문)", ""), + material.get("Trade name(영문)", ""), ] - seen = [] - for item in candidates: - item = safe_str(item) - if item and item not in seen: - seen.append(item) - - for item in seen: - if os.path.isdir(item): - return item - - folder_map = { - f.lower(): f - for f in os.listdir(".") - if os.path.isdir(f) - } - - for item in seen: - matched = folder_map.get(item.lower()) - if matched: - return matched - - return alias + identity = normalize_compact(" ".join([safe_str(x) for x in identity_values if safe_str(x)])) + row_terms = [row.get("원료명", ""), row.get("INCI", ""), row.get("CAS.No", "")] + for term in row_terms: + term_norm = normalize_compact(term) + if term_norm and len(term_norm) >= 3 and term_norm in identity: + return True -# ============================================================ -# 4-1. 국가 폴더 목록 갱신 -# ============================================================ + return False -def get_country_folders(): - exclude = [".git", ".cache", "__pycache__", ".ipynb_checkpoints", ".venv", "venv", "node_modules", FAISS_CACHE_DIR, "outputs"] - existing_folders = [f for f in os.listdir(".") if os.path.isdir(f) and f not in exclude] - existing_set = set(existing_folders) - ordered = [c for c in COUNTRY_ORDER if c in existing_set] - extras = sorted([f for f in existing_folders if f not in COUNTRY_ORDER]) - if not ordered and not extras: - return COUNTRY_ORDER.copy() - return ordered + extras +def mfds_row_country_matches(country, row_country): + row_country_norm = normalize_compact(row_country) + col = display_country(country) + aliases = [country, col, country_key(country)] -def refresh_country_choices_keep_selection(current_values=None): - choices = get_country_folders() - current_values = current_values or [] - kept_values = [v for v in current_values if v in choices] - return gr.update(choices=choices, value=kept_values) + if col == "Korea": + aliases += ["한국", "대한민국", "KOREA", "KR"] + elif col == "FDA": + aliases += ["미국", "USA", "US", "United States", "FDA"] + elif col == "EU": + aliases += ["EU", "유럽", "유럽연합", "European Union", "Europe"] + aliases_norm = [normalize_compact(x) for x in aliases if safe_str(x)] + return any(alias and alias in row_country_norm for alias in aliases_norm) -def refresh_country_choices_and_clear_cache(current_values=None): - VECTOR_DB_CACHE.clear() - EVAL_CACHE.clear() - return refresh_country_choices_keep_selection(current_values) - -# ============================================================ -# 5. 입력 엑셀 미리보기 / 컬럼 인식 -# ============================================================ - -def preview_excel(file): - if not file: +def evaluate_mfds_detail_rule(country, material, component, mfds_df): + if mfds_df is None or mfds_df.empty: return None - try: - return pd.read_excel(file.name) - except Exception as e: - return pd.DataFrame({"오류": [str(e)]}) + hits = [] -def find_best_col(df, keywords, default_index=None, exclude_cols=None): - exclude_cols = exclude_cols or [] - scores = [] - for idx, col in enumerate(df.columns): - if col in exclude_cols: - continue - header = str(col).lower() - values = df[col].dropna().astype(str).str.strip() - sample = " ".join(values.head(80).tolist()).lower() - score = 0 - for kw in keywords: - if kw.lower() in header: - score += 30 - markers = [ - "aqua", "water", "glycerin", "octocrylene", "homosalate", "octisalate", "avobenzone", - "niacinamide", "phenoxyethanol", "limonene", "linalool", "citral", "extract", "acid", "ceramide", "glycol", "retinol", - ] - if any(x in sample for x in markers): - if any(k.lower() in ["inci", "ingredient", "성분", "전성분", "구성", "inci name"] for k in keywords): - score += 10 - scores.append((score, idx, col)) - scores = sorted(scores, reverse=True, key=lambda x: (x[0], -x[1])) - if scores and scores[0][0] > 0: - return scores[0][2] - if default_index is not None and len(df.columns) > default_index: - return df.columns[default_index] - return df.columns[0] - + for _, row in mfds_df.iterrows(): + if ingredient_matches_mfds_row(material, component, row) and mfds_row_country_matches(country, row.get("국가", "")): + hits.append(row) -def find_numeric_col(df, keywords, default_index=None, exclude_cols=None, prefer_many_values=True): - exclude_cols = exclude_cols or [] - candidates = [] - for idx, col in enumerate(df.columns): - if col in exclude_cols: - continue - header = str(col).lower() - values = df[col].dropna() - if values.empty: - continue - count = values.apply(is_numeric_like).sum() - if count <= 0: - continue - score = 0 - for kw in keywords: - if kw.lower() in header: - score += 30 - candidates.append({"col": col, "idx": idx, "score": score, "count": count, "non_null": len(values)}) - if not candidates: - if default_index is not None and len(df.columns) > default_index: - return df.columns[default_index] + if not hits: return None - if prefer_many_values: - candidates = sorted(candidates, key=lambda x: (x["score"], x["non_null"], x["idx"]), reverse=True) - else: - candidates = sorted(candidates, key=lambda x: (x["score"], -x["non_null"], -x["idx"]), reverse=True) - return candidates[0]["col"] + row = hits[0] + category = safe_str(row.get("구분", "")) or "제한" + regulation = safe_str(row.get("규제내용", "")) + limit = safe_str(row.get("한도", "")) + source = safe_str(row.get("출처", "MFDS live")) -def find_main_columns(df): - no_col = find_best_col(df, ["no", "번호", "순번"], default_index=0) - trade_ko_col = find_best_col(df, ["trade name(국문)", "trade name 국문", "국문", "원료명", "상품명"], default_index=1, exclude_cols=[no_col]) - 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]) - 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]) - inci_col = find_best_col(df, ["inci name", "inci", "ingredient", "성분", "전성분", "구성"], default_index=4 if len(df.columns) > 4 else 2, exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col]) - 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) - 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) + parts = [category] - function_col = find_best_col( - df, - ["function", "기능", "용도"], - default_index=None, - exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col, contents_col, formula_col], - ) + if limit: + parts.append(f"한도 {limit}") - cas_col = find_best_col( - df, - ["cas.no", "cas no", "cas", "cas번호", "cas no."], - default_index=None, - exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col, contents_col, formula_col, function_col], - ) + if regulation: + parts.append(regulation[:300]) - source_col = find_best_col( - df, - ["source", "출처", "icid"], - default_index=None, - exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col, contents_col, formula_col, function_col, cas_col], - ) - - if contents_col == formula_col: - numeric_cols = [] - for col in df.columns: - if col in [no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col]: - continue - values = df[col].dropna() - if not values.empty and values.apply(is_numeric_like).sum() > 0: - numeric_cols.append(col) - if len(numeric_cols) >= 2: - contents_col = numeric_cols[-2] - formula_col = numeric_cols[-1] + result_text = " / ".join([p for p in parts if p]) return { - "no_col": no_col, - "trade_ko_col": trade_ko_col, - "trade_en_col": trade_en_col, - "korean_ing_col": korean_ing_col, - "inci_col": inci_col, - "contents_col": contents_col, - "formula_col": formula_col, - "function_col": function_col, - "cas_col": cas_col, - "source_col": source_col, + "대표 INCI": safe_str(component.get("INCI Name", "")) or safe_str(row.get("원료명", "")) or "-", + "결과": result_text, + "비고": source, } # ============================================================ -# 6. 입력 엑셀 정리 / 그룹화 -# ============================================================ - -def clean_input_df(df, cols): - no_col = cols["no_col"] - trade_ko_col = cols["trade_ko_col"] - trade_en_col = cols["trade_en_col"] - korean_ing_col = cols["korean_ing_col"] - inci_col = cols["inci_col"] - - footer_markers = [ - "commitment of the manufacturer", "the manufacturer here", "it is illegal", "rebom co", - "myeonghaksandanseo", "sejong special", "tel :", "fax :", "lab no.", "permission", - ] - - keep_indices = [] - footer_started = False - - for idx, row in df.iterrows(): - row_values = [safe_str(v) for v in row.values] - row_text = " ".join([v for v in row_values if v]).strip() - row_text_lower = row_text.lower() - if not row_text: - continue - - no_text = safe_str(row.get(no_col, "")).lower() if no_col in df.columns else "" - trade_ko_text = safe_str(row.get(trade_ko_col, "")).lower() if trade_ko_col in df.columns else "" - trade_en_text = safe_str(row.get(trade_en_col, "")).lower() if trade_en_col in df.columns else "" - korean_ing_text = safe_str(row.get(korean_ing_col, "")).lower() if korean_ing_col in df.columns else "" - inci_text = safe_str(row.get(inci_col, "")).lower() if inci_col in df.columns else "" - - if no_text in ["no", "번호", "순번"] or inci_text in ["inci", "inci name"] or korean_ing_text in ["한글 성분명", "한글성분명", "국문 성분명"]: - continue - if no_text.startswith("합계") or trade_ko_text.startswith("합계") or trade_en_text.startswith("합계"): - footer_started = True - continue - if any(marker in row_text_lower for marker in footer_markers): - footer_started = True - continue - if footer_started: - continue - keep_indices.append(idx) - - return df.loc[keep_indices].reset_index(drop=True) - - -def compute_ingredient_totals(cleaned_df, cols): - formula_col = cols["formula_col"] - totals = defaultdict(float) - amount_parts = defaultdict(list) - if not formula_col: - return totals, amount_parts - for _, row in cleaned_df.iterrows(): - identity = normalize_text(" ".join([safe_str(v) for v in row.values])) - amount = to_number(row.get(formula_col, "")) - if amount is None: - continue - for canonical, rule in FRAGRANCE_ALLERGEN_RULES.items(): - for alias in rule.get("aliases", []): - alias_norm = normalize_text(alias) - if alias_norm and alias_norm in identity: - totals[canonical] += amount - amount_parts[canonical].append(amount) - return totals, amount_parts - - -def make_grouped_materials(df): - cols = find_main_columns(df) - cleaned_df = clean_input_df(df, cols) - - no_col = cols["no_col"] - trade_ko_col = cols["trade_ko_col"] - trade_en_col = cols["trade_en_col"] - korean_ing_col = cols["korean_ing_col"] - inci_col = cols["inci_col"] - contents_col = cols["contents_col"] - formula_col = cols["formula_col"] - function_col = cols.get("function_col") - cas_col = cols.get("cas_col") - source_col = cols.get("source_col") - - work_df = cleaned_df.copy() - for col in [no_col, trade_ko_col, trade_en_col]: - if col and col in work_df.columns: - work_df[col] = work_df[col].ffill() - - group_keys = [c for c in [no_col, trade_ko_col, trade_en_col] if c and c in work_df.columns] - grouped_materials = [] - - for key, group in work_df.groupby(group_keys, dropna=True, sort=False): - if not isinstance(key, tuple): - key = (key,) - no_value = format_no(key[0]) if len(key) > 0 else "" - trade_ko = safe_str(key[1]) if len(key) > 1 else "" - trade_en = safe_str(key[2]) if len(key) > 2 else trade_ko - - if no_value and not is_numeric_like(no_value): - continue - if not trade_ko and not trade_en: - continue - - components = [] - for _, row in group.iterrows(): - korean_ing = safe_str(row.get(korean_ing_col, "")) if korean_ing_col in row else "" - inci_name = safe_str(row.get(inci_col, "")) if inci_col in row else "" - if not inci_name and not korean_ing: - continue - contents_value = format_amount(row.get(contents_col)) if contents_col and contents_col in row else "" - formula_value = format_amount(row.get(formula_col)) if formula_col and formula_col in row else "" - function_value = safe_str(row.get(function_col, "")) if function_col and function_col in row else "" - cas_value = safe_str(row.get(cas_col, "")) if cas_col and cas_col in row else "" - source_value = safe_str(row.get(source_col, "")) if source_col and source_col in row else "" - - if not source_value: - source_value = "ICID" - - components.append({ - "한글 성분명": korean_ing, - "INCI Name": inci_name, - "FUNCTION": function_value, - "CAS.No": cas_value, - "SOURCE": source_value, - "Contents(w/w %)": contents_value, - "In formula(w/w %)": formula_value, - "amount_float": to_number(row.get(formula_col)) if formula_col and formula_col in row else None, - }) - - if components: - grouped_materials.append({ - "NO": no_value, - "Trade name(국문)": trade_ko, - "Trade name(영문)": trade_en, - "Components": components, - "Group_records": group.to_dict(orient="records"), - }) - - ingredient_totals, ingredient_amount_parts = compute_ingredient_totals(cleaned_df, cols) - meta = {"cols": cols, "cleaned_df": cleaned_df, "ingredient_totals": ingredient_totals, "ingredient_amount_parts": ingredient_amount_parts} - return grouped_materials, meta - - -# ============================================================ -# 7. 규제 문서 FAISS DB -# ============================================================ - -def get_regulatory_file_list(country_folder): - files = [] - if not country_folder or not os.path.isdir(country_folder): - return files - for root, dirs, filenames in os.walk(country_folder): - dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ["__pycache__", ".ipynb_checkpoints"]] - for filename in filenames: - ext = os.path.splitext(filename)[1].lower() - if ext not in SUPPORTED_REG_FILE_EXTENSIONS: - continue - file_path = os.path.join(root, filename) - try: - stat = os.stat(file_path) - except FileNotFoundError: - continue - 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}) - return sorted(files, key=lambda x: x["relative_path"].lower()) - - -def get_regulatory_folder_signature(country_folder): - file_list = get_regulatory_file_list(country_folder) - signature = tuple((item["relative_path"], item["size"], item["mtime_ns"]) for item in file_list) - return signature, file_list - - -def read_text_file_with_fallback(file_path): - for enc in ["utf-8", "utf-8-sig", "cp949", "euc-kr", "latin-1"]: - try: - with open(file_path, "r", encoding=enc) as f: - return f.read() - except Exception: - continue - return "" - - -def extract_text_from_regulatory_file(file_item): - file_path = file_item["path"] - rel_path = file_item["relative_path"] - ext = file_item["ext"] - texts = [] - try: - if ext == ".pdf": - with pdfplumber.open(file_path) as pdf: - for page_no, page in enumerate(pdf.pages, start=1): - text = page.extract_text() - if text: - texts.append(f"[파일: {rel_path}] [페이지: {page_no}]\n{text}") - elif ext == ".txt": - text = read_text_file_with_fallback(file_path) - if text: - texts.append(f"[파일: {rel_path}]\n{text}") - elif ext == ".csv": - try: - df = pd.read_csv(file_path, dtype=str) - except UnicodeDecodeError: - df = pd.read_csv(file_path, dtype=str, encoding="cp949") - texts.append(f"[파일: {rel_path}]\n{df.fillna('').to_string(index=False)}") - elif ext in [".xlsx", ".xls"]: - sheets = pd.read_excel(file_path, sheet_name=None, dtype=str) - for sheet_name, sheet_df in sheets.items(): - texts.append(f"[파일: {rel_path}] [시트: {sheet_name}]\n{sheet_df.fillna('').to_string(index=False)}") - except Exception as e: - print(f"규제 파일 읽기 오류: {file_path} / {e}") - return "\n\n".join(texts) - - -def get_faiss_cache_path(country_folder, signature_hash): - os.makedirs(FAISS_CACHE_DIR, exist_ok=True) - folder_key = safe_filename(country_folder) - cache_folder = f"{folder_key}_{signature_hash[:16]}" - return os.path.join(FAISS_CACHE_DIR, cache_folder) - - -def get_current_db_signature(country): - folder = resolve_country_folder(country) - cached = VECTOR_DB_CACHE.get(folder) - if isinstance(cached, dict): - return cached.get("signature_hash") - return None - - -def build_database(country_folder): - country_folder = resolve_country_folder(country_folder) - if not country_folder or country_folder == "폴더 없음" or not os.path.isdir(country_folder): - return None - - current_signature, file_list = get_regulatory_folder_signature(country_folder) - if not file_list: - VECTOR_DB_CACHE.pop(country_folder, None) - return None - - signature_hash = stable_hash(current_signature) - cached = VECTOR_DB_CACHE.get(country_folder) - if isinstance(cached, dict) and cached.get("signature_hash") == signature_hash and cached.get("db") is not None: - return cached["db"] - - embeddings = get_embeddings() - cache_path = get_faiss_cache_path(country_folder, signature_hash) - metadata_path = os.path.join(cache_path, "metadata.json") - - if os.path.isdir(cache_path) and os.path.exists(metadata_path): - try: - with open(metadata_path, "r", encoding="utf-8") as f: - metadata = json.load(f) - if metadata.get("signature_hash") == signature_hash: - print(f"✅ FAISS 디스크 캐시 로드: {country_folder}") - db = FAISS.load_local(cache_path, embeddings, allow_dangerous_deserialization=True) - VECTOR_DB_CACHE[country_folder] = {"signature_hash": signature_hash, "db": db, "file_count": len(file_list)} - return db - except Exception as e: - print(f"FAISS 디스크 캐시 로드 실패: {country_folder} / {e}") - - print(f"🔄 규제 DB 재색인: {country_folder} / 파일 {len(file_list)}개") - EVAL_CACHE.clear() - - texts = [] - splitter = RecursiveCharacterTextSplitter(chunk_size=900, chunk_overlap=120) - for file_item in file_list: - raw_text = extract_text_from_regulatory_file(file_item) - if not raw_text: - continue - source_text = f"[국가/채널: {country_folder}] [출처파일: {file_item['relative_path']}]\n{raw_text}" - texts.extend(splitter.split_text(source_text)) - - if not texts: - VECTOR_DB_CACHE.pop(country_folder, None) - return None - - db = FAISS.from_texts(texts, embeddings) - - try: - os.makedirs(cache_path, exist_ok=True) - db.save_local(cache_path) - with open(metadata_path, "w", encoding="utf-8") as f: - json.dump({ - "country_folder": country_folder, - "signature_hash": signature_hash, - "file_count": len(file_list), - "files": [{"relative_path": item["relative_path"], "size": item["size"], "mtime_ns": item["mtime_ns"], "ext": item["ext"]} for item in file_list], - }, f, ensure_ascii=False, indent=2) - print(f"✅ FAISS 디스크 캐시 저장: {cache_path}") - except Exception as e: - print(f"FAISS 디스크 캐시 저장 실패: {country_folder} / {e}") - - VECTOR_DB_CACHE[country_folder] = {"signature_hash": signature_hash, "db": db, "file_count": len(file_list)} - return db - - -# ============================================================ -# 8. 로컬 규칙 판정 +# 7. 로컬 규칙 판정 # ============================================================ def evaluate_limit_rule(country, material, component, rule_group, rule_type_name): ckey = country_key(country) + col_name = display_country(country) key = match_rule_key(material, component, rule_group) + if not key: return None + rule = rule_group[key] country_rule = rule.get(ckey) + if not country_rule: return None @@ -1412,23 +1258,42 @@ def evaluate_limit_rule(country, material, component, rule_group, rule_type_name amount = component.get("amount_float") amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" status = country_rule.get("status", "allowed") + formula_text = country_rule.get("formula_text", "") if status == "prohibited": - return {"대표 INCI": label, "결과": f"{label} 배합금지 / 현재 함량 {amount_text}% / 재검토 필요", "비고": "-"} + return { + "대표 INCI": label, + "결과": f"{label} 배합금지 / 현재 함량 {amount_text}% / 재검토 필요", + "표시문구": formula_text or "배합금지", + "비고": "-", + } limit = country_rule.get("limit") + if limit is not None: - if amount is None: - return {"대표 INCI": label, "결과": f"{rule_type_name} / {label}, 한도 {format_percent(limit)}%, 현재 함량 확인 필요", "비고": "함량 확인 필요"} - if amount > limit: - return {"대표 INCI": label, "결과": f"{rule_type_name} / {label} 현재 함량 {amount_text}%, 한도 {format_percent(limit)}% 초과(재검토 필요)", "비고": "-"} - return {"대표 INCI": label, "결과": f"{rule_type_name} / {label} 현재 함량 {amount_text}%, 한도 {format_percent(limit)}% 이내(통과)", "비고": "-"} + if amount is not None and amount > limit: + result_text = f"{rule_type_name} / {label} 현재 함량 {amount_text}%, 한도 {format_percent(limit)}% 초과(재검토 필요)" + else: + result_text = f"{rule_type_name} / {label} 현재 함량 {amount_text}%, 한도 {format_percent(limit)}% 이내(통과)" + + return { + "대표 INCI": label, + "결과": result_text, + "표시문구": formula_text or f"배합한도: {format_percent(limit)}%", + "비고": "-", + } - return {"대표 INCI": label, "결과": NO_EVIDENCE_TEXT, "비고": "-"} + return { + "대표 INCI": label, + "결과": NO_EVIDENCE_TEXT, + "표시문구": "Pass", + "비고": "-", + } def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts): ckey = country_key(country) + col_name = display_country(country) amount = component.get("amount_float") uv_result = evaluate_limit_rule(country, material, component, UV_FILTER_RULES, "UV 필터") @@ -1440,867 +1305,54 @@ def evaluate_local_rules(country, material, component, ingredient_totals, ingred return preservative_result functional_key = match_rule_key(material, component, FUNCTIONAL_KOREA_RULES) + if ckey == "KOREA" and functional_key: rule = FUNCTIONAL_KOREA_RULES[functional_key] - amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" - return {"대표 INCI": rule["label"], "결과": rule["result"].format(amount=amount_text), "비고": rule.get("note", "-")} - - fragrance_key = canonical_fragrance_name(material, component) - if ckey in ["EU", "EU_FUTURE", "UK", "KOREA"] and fragrance_key: - rule = FRAGRANCE_ALLERGEN_RULES[fragrance_key] - total_amount = ingredient_totals.get(fragrance_key, amount) - parts = ingredient_amount_parts.get(fragrance_key, []) - calc_text = build_calc_text(parts) - leave_status = amount_status(total_amount, rule["leave_on"], "표시 필요") - wash_status = amount_status(total_amount, rule["wash_off"], "표시 필요") - extra = rule.get("extra", "-") - extra_text = "" if not extra or extra == "-" else f", {extra}" - result_text = f"향료 알레르겐 / {rule['label']} 총 {format_percent(total_amount)}%{calc_text}, Leave-on 표시기준 {leave_status}, Wash-off 표시기준 {wash_status}{extra_text}" - return {"대표 INCI": rule["label"], "결과": result_text, "비고": "-"} - - identity = get_identity_text(material, component) - - 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"]): - amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" - return { - "대표 INCI": safe_str(component.get("INCI Name", "")) or "-", - "결과": f"시트러스 원료 / 현재 함량 {amount_text}%, furocoumarines 원료자료 확인 필요. 자외선차단·태닝 등 햇빛 노출 제품 해당 시 총 furocoumarines 1 mg/kg 이하 관리 필요", - "비고": "COA 또는 원료규격서에서 furocoumarines 확인 권장", - } - - if ckey in ["EU", "EU_FUTURE", "UK"] and any(x in identity for x in ["essential oil", "leaf oil", "peel oil"]): amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" return { - "대표 INCI": safe_str(component.get("INCI Name", "")) or "-", - "결과": f"정유류 / 현재 함량 {amount_text}%, 구성 향료 알레르겐 및 산화물 자료 확인 필요", - "비고": "하위 구성성분에 Limonene, Linalool, Citral 등 존재 시 총량 기준으로 표시기준 검토", - } - - if ckey in ["EU", "EU_FUTURE"] and any(x in identity for x in ["carbomer", "copolymer", "crosspolymer", "polymer"]): - amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" - return { - "대표 INCI": safe_str(component.get("INCI Name", "")) or "-", - "결과": f"합성고분자 / 현재 함량 {amount_text}%, EU synthetic polymer microparticles 해당성 검토 필요", - "비고": "고체 입자성, 용해성, 생분해성, 입자 크기 등 원료자료 확인 필요", - } - - if amount is None: - return {"대표 INCI": safe_str(component.get("INCI Name", "")) or "-", "결과": "함량 정보 없음 / In formula(w/w %) 확인 필요", "비고": "-"} - - return None - - -# ============================================================ -# 9. GPT 보조 판정 -# ============================================================ - -def parse_country_response(text): - result = {"대표 INCI": "-", "결과": NO_EVIDENCE_TEXT, "비고": "-"} - for line in text.splitlines(): - line = line.strip() - if line.startswith("대표 INCI:"): - result["대표 INCI"] = line.split(":", 1)[1].strip() or "-" - elif line.startswith("결과:"): - result["결과"] = line.split(":", 1)[1].strip() or NO_EVIDENCE_TEXT - elif line.startswith("비고:"): - result["비고"] = line.split(":", 1)[1].strip() or "-" - return result - - -def clean_json_text(text): - text = safe_str(text) - text = re.sub(r"^```json\s*", "", text.strip(), flags=re.IGNORECASE) - text = re.sub(r"^```\s*", "", text.strip()) - text = re.sub(r"\s*```$", "", text.strip()) - match = re.search(r"\[.*\]", text, flags=re.DOTALL) - if match: - return match.group(0) - match = re.search(r"\{.*\}", text, flags=re.DOTALL) - if match: - return match.group(0) - return text - - -def sanitize_country_result(parsed, fallback_inci="-"): - if not isinstance(parsed, dict): - parsed = {} - representative = safe_str(parsed.get("대표 INCI", "")) or fallback_inci or "-" - result_text = safe_str(parsed.get("결과", "")) or NO_EVIDENCE_TEXT - note = safe_str(parsed.get("비고", "")) or "-" - bad_tokens = ["규제명", "총량 계산", "규제 / 총량", "{규제군명}", "{성분명", "{함량}", "{기준치}", "placeholder", "N/A", "n/a"] - if any(token in result_text for token in bad_tokens): - result_text = "확인 필요 / 규제 세부 계산 재확인 필요" - if note == "-": - note = "구체 한도 또는 총량 계산값 확인 필요" - return {"대표 INCI": representative, "결과": result_text, "비고": note} - - -def make_eval_cache_key(country, component): - amount = component.get("amount_float") - amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" - db_signature = get_current_db_signature(country) - return (str(country), str(db_signature), safe_str(component.get("INCI Name", "")).lower(), safe_str(component.get("한글 성분명", "")).lower(), amount_text) - - -def has_meaningful_search_hit(db, search_text, ingredient_names, k=MEANINGFUL_HIT_K): - if not db: - return False, "" - try: - docs = db.similarity_search(search_text, k=k) - context = "\n".join([d.page_content for d in docs]) - except Exception: - return False, "" - context_norm = normalize_compact(context) - for name in ingredient_names: - name_norm = normalize_compact(name) - if name_norm and len(name_norm) >= 3 and name_norm in context_norm: - return True, context - return False, context - - -def evaluate_component_with_llm(country, material, component, llm, target_id=""): - db = build_database(country) - inci_name = safe_str(component.get("INCI Name", "")) - korean_name = safe_str(component.get("한글 성분명", "")) - amount = component.get("amount_float") - amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" - - if not inci_name and not korean_name: - return {"대표 INCI": "-", "결과": "", "비고": "-"} - - if not db: - result = {"대표 INCI": inci_name or "-", "결과": NO_EVIDENCE_TEXT, "비고": "-"} - log_search_context(target_id, country, component, result["결과"], "NO_DB", "해당 국가/채널 규제 DB 없음") - return result - - cache_key = make_eval_cache_key(country, component) - if cache_key in EVAL_CACHE: - return EVAL_CACHE[cache_key] - - trade_ko = material["Trade name(국문)"] - trade_en = material["Trade name(영문)"] - search_text = f""" -국가/채널: {country} -원료명 국문: {trade_ko} -원료명 영문: {trade_en} -검토 성분 국문: {korean_name} -검토 성분 INCI/CAS: {inci_name} -최종 제품 내 함량: {amount_text}% -제품유형: Leave-on 및 Wash-off 기준 모두 확인 -""" - - has_hit, pre_context = has_meaningful_search_hit(db, search_text, [inci_name, korean_name], k=MEANINGFUL_HIT_K) - if not has_hit: - result = {"대표 INCI": inci_name or "-", "결과": NO_EVIDENCE_TEXT, "비고": "-"} - EVAL_CACHE[cache_key] = result - log_search_context(target_id, country, component, result["결과"], "NO_MEANINGFUL_HIT", pre_context) - return result - - docs = db.similarity_search(search_text, k=RAG_TOP_K_SINGLE) - context = "\n".join([d.page_content for d in docs]) - - prompt = f""" -너는 화장품 전성분 규제 스크리닝 전문가야. -아래 단일 구성성분을 반드시 "{country}" 기준으로만 검토해. - -[절대 규칙] -- 현재 검토 국가는 "{country}"이다. -- 아래 검색 원문은 "{country}" 폴더 또는 채널에서만 검색된 근거다. -- 외부 지식, 학습 지식, 일반 규제 지식을 사용하지 마. -- 다른 국가 규정, EU Annex, ASEAN 채택 규정을 현재 국가에 임의 적용하지 마. -- 특히 EU 규정을 한국/일본/미국/FDA/중국에 복사 적용하지 마. -- 검색된 "{country}" 원문에 명시되지 않은 제한, 배합금지, 배합한도는 만들지 마. -- 검색 원문에 명시된 제한/금지/한도 근거가 없으면 결과는 정확히 "{NO_EVIDENCE_TEXT}"으로 작성해. - -[원료명 국문] -{trade_ko} - -[원료명 영문] -{trade_en} - -[검토 성분] -국문명: {korean_name} -INCI/CAS: {inci_name} -최종 제품 내 함량: {amount_text}% - -[검색된 {country} 규제 원문] -{context} - -반드시 아래 형식으로만 답변해. -대표 INCI: -결과: -비고: - -작성 원칙: -- 검색된 규제 원문에 근거가 있는 내용만 작성해. -- 원문에 근거가 없는데 특정 한도나 금지 여부를 만들지 마. -- 현재 함량이 한도 이내라면 반드시 "이내(통과)"라고 작성해. -- 현재 함량이 한도를 초과할 때만 "초과" 또는 "재검토 필요"라고 작성해. -- 배합금지, 표시 필요, 자료 확인 필요는 재검토 대상이다. -""" - - try: - response = llm.invoke(prompt).content - parsed = sanitize_country_result(parse_country_response(response), fallback_inci=inci_name or "-") - EVAL_CACHE[cache_key] = parsed - log_search_context(target_id, country, component, parsed["결과"], "GPT_SINGLE", context) - return parsed - except Exception as e: - result = {"대표 INCI": inci_name or "-", "결과": "확인 필요", "비고": str(e)} - log_search_context(target_id, country, component, result["결과"], "GPT_SINGLE_ERROR", str(e)) - return result - - -def evaluate_components_with_llm_batch(country, targets, llm): - results = {} - if not targets: - return results - - db = build_database(country) - if not db: - for item in targets: - comp = item["component"] - inci_name = safe_str(comp.get("INCI Name", "")) - results[item["target_id"]] = {"대표 INCI": inci_name or "-", "결과": NO_EVIDENCE_TEXT, "비고": "-"} - log_search_context(item["target_id"], country, comp, NO_EVIDENCE_TEXT, "NO_DB", "해당 국가/채널 규제 DB 없음") - return results - - uncached_targets = [] - for item in targets: - comp = item["component"] - cache_key = make_eval_cache_key(country, comp) - if cache_key in EVAL_CACHE: - results[item["target_id"]] = EVAL_CACHE[cache_key] - else: - uncached_targets.append(item) - - if not uncached_targets: - return results - - filtered_targets = [] - for item in uncached_targets: - material = item["material"] - comp = item["component"] - inci_name = safe_str(comp.get("INCI Name", "")) - korean_name = safe_str(comp.get("한글 성분명", "")) - amount = comp.get("amount_float") - amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" - search_text = f""" -국가/채널: {country} -원료명 국문: {material.get('Trade name(국문)', '')} -원료명 영문: {material.get('Trade name(영문)', '')} -검토 성분 국문: {korean_name} -검토 성분 INCI/CAS: {inci_name} -최종 제품 내 함량: {amount_text}% -""" - has_hit, context = has_meaningful_search_hit(db, search_text, [inci_name, korean_name], k=MEANINGFUL_HIT_K) - if has_hit: - filtered_targets.append(item) - else: - result = {"대표 INCI": inci_name or "-", "결과": NO_EVIDENCE_TEXT, "비고": "-"} - results[item["target_id"]] = result - EVAL_CACHE[make_eval_cache_key(country, comp)] = result - log_search_context(item["target_id"], country, comp, result["결과"], "NO_MEANINGFUL_HIT", context) - - uncached_targets = filtered_targets - if not uncached_targets: - return results - - for batch in chunk_list(uncached_targets, BATCH_SIZE): - target_payload = [] - search_blocks = [] - for item in batch: - material = item["material"] - comp = item["component"] - inci_name = safe_str(comp.get("INCI Name", "")) - korean_name = safe_str(comp.get("한글 성분명", "")) - amount = comp.get("amount_float") - amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" - target_payload.append({ - "target_id": item["target_id"], - "원료명 국문": material["Trade name(국문)"], - "원료명 영문": material["Trade name(영문)"], - "성분 국문명": korean_name, - "INCI/CAS": inci_name, - "최종 제품 내 함량(%)": amount_text, - }) - search_blocks.append(f"{material['Trade name(영문)']} {inci_name} {korean_name} {amount_text}%") - - search_text = f""" -국가/채널: {country} -제품유형: Leave-on 및 Wash-off 기준 모두 확인 -검토 대상 성분: -{chr(10).join(search_blocks)} -""" - - try: - docs = db.similarity_search(search_text, k=RAG_TOP_K_BATCH) - context = "\n".join([d.page_content for d in docs]) - prompt = f""" -너는 화장품 전성분 규제 스크리닝 전문가야. -아래 여러 구성성분을 반드시 "{country}" 기준으로만 한 번에 검토해. - -[절대 규칙] -- 현재 검토 국가는 "{country}"이다. -- 아래 검색 원문은 "{country}" 폴더 또는 채널에서만 검색된 근거다. -- 외부 지식, 학습 지식, 일반 규제 지식을 사용하지 마. -- 다른 국가 규정, EU Annex, ASEAN 채택 규정을 현재 국가에 임의 적용하지 마. -- 특히 EU 규정을 한국/일본/미국/FDA/중국에 복사 적용하지 마. -- 검색된 "{country}" 원문에 명시되지 않은 제한, 배합금지, 배합한도는 만들지 마. -- 검색 원문에 명시된 제한/금지/한도 근거가 없으면 결과는 정확히 "{NO_EVIDENCE_TEXT}"으로 작성해. - -[검토 대상 JSON] -{json.dumps(target_payload, ensure_ascii=False, indent=2)} - -[검색된 {country} 규제 원문] -{context} - -반드시 JSON 배열만 출력해. -마크다운, 설명문, 코드블록 없이 순수 JSON만 출력해. - -출력 형식: -[ - {{ - "target_id": "입력 target_id 그대로", - "대표 INCI": "대표 INCI 또는 -", - "결과": "{NO_EVIDENCE_TEXT} 또는 규제 내용", - "비고": "-" - }} -] - -작성 원칙: -- 검색된 규제 원문에 근거가 있는 내용만 작성해. -- 원문에 근거가 없는데 특정 한도나 금지 여부를 만들지 마. -- 현재 함량이 한도 이내라면 반드시 "이내(통과)"라고 작성해. -- 현재 함량이 한도를 초과할 때만 "초과" 또는 "재검토 필요"라고 작성해. -- 배합금지, 표시 필요, 자료 확인 필요는 재검토 대상이다. -- 입력된 모든 target_id를 빠짐없이 반환해. -""" - response = llm.invoke(prompt).content - parsed = json.loads(clean_json_text(response)) - if isinstance(parsed, dict): - parsed = [parsed] - - parsed_by_id = {} - for obj in parsed: - if not isinstance(obj, dict): - continue - target_id = safe_str(obj.get("target_id", "")) - if target_id: - parsed_by_id[target_id] = sanitize_country_result(obj, fallback_inci=safe_str(obj.get("대표 INCI", "-"))) - - for item in batch: - target_id = item["target_id"] - comp = item["component"] - if target_id in parsed_by_id: - result = parsed_by_id[target_id] - results[target_id] = result - EVAL_CACHE[make_eval_cache_key(country, comp)] = result - log_search_context(target_id, country, comp, result["결과"], "GPT_BATCH", context) - - for item in batch: - target_id = item["target_id"] - if target_id in results: - continue - results[target_id] = evaluate_component_with_llm(country, item["material"], item["component"], llm, target_id) - - except Exception as e: - print(f"batch GPT 판정 실패: {country} / {e}") - for item in batch: - target_id = item["target_id"] - if target_id not in results: - results[target_id] = evaluate_component_with_llm(country, item["material"], item["component"], llm, target_id) - - return results - - -# ============================================================ -# 10. 출력 데이터 구성 -# ============================================================ - -def make_formula_statement_rows(row_items, country_cols): - rows = [] - for item in row_items: - material = item["material"] - comp = item["component"] - row_data = item["row_data"] - - row = { - "NO.": material.get("NO", ""), - "한글 표준화 명칭": comp.get("한글 성분명", ""), - "INGREDIENT NAME (INCI)": comp.get("INCI Name", ""), - "FUNCTION": comp.get("FUNCTION", ""), - "CAS.No": comp.get("CAS.No", ""), - "SOURCE": comp.get("SOURCE", "ICID") or "ICID", - "%(w/w)": comp.get("In formula(w/w %)", ""), + "대표 INCI": rule["label"], + "결과": rule["result"].format(amount=amount_text), + "표시문구": rule.get("formula_text", "기능성 확인"), + "비고": "기능성 표시·광고 여부 확인", } - for country_col in country_cols: - row[country_col] = make_country_cell_status(row_data.get(country_col, "")) - - rows.append(row) - - total = 0.0 - for row in rows: - value = to_number(row.get("%(w/w)", "")) - if value is not None: - total += value - - total_row = { - "NO.": "", - "한글 표준화 명칭": "", - "INGREDIENT NAME (INCI)": "TOTAL", - "FUNCTION": "", - "CAS.No": "", - "SOURCE": "", - "%(w/w)": format_amount(total), - } - for country_col in country_cols: - total_row[country_col] = "" - - rows.append(total_row) - return pd.DataFrame(rows) + identity = get_identity_text(material, component) + for fragrance_key, rule in FRAGRANCE_ALLERGEN_RULES.items(): + matched = False + for alias in rule.get("aliases", []): + if normalize_text(alias) in identity: + matched = True + break -def make_regulatory_summary_rows(row_items, country_cols): - rows = [] - for item in row_items: - row_data = item["row_data"] - if not is_country_result_issue(row_data.get("Result", "")): + if not matched: continue - row = { - "한글 성분명": row_data.get("한글 성분명", ""), - "INCI Name": row_data.get("INCI Name", ""), - "In formula(w/w %)": row_data.get("In formula\n(w/w %)", ""), - "Result": row_data.get("Result", ""), - } - for country_col in country_cols: - value = safe_str(row_data.get(country_col, "")) - row[country_col] = value if is_country_result_issue(value) else "-" - row["비고"] = row_data.get("비고", "-") - rows.append(row) - - columns = ["한글 성분명", "INCI Name", "In formula(w/w %)", "Result"] + country_cols + ["비고"] - if not rows: - return pd.DataFrame(columns=columns) - return pd.DataFrame(rows)[columns] - - -# ============================================================ -# 11. 엑셀 저장 / 스타일 -# ============================================================ - -def write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw_df): - with pd.ExcelWriter(out_path, engine="openpyxl") as writer: - formula_df.to_excel(writer, index=False, sheet_name="Formula Ingredients Statement", startrow=5) - regulatory_df.to_excel(writer, index=False, sheet_name="Regulatory Screening Summary") - raw_df.to_excel(writer, index=False, sheet_name="Evidence Log") - - wb = load_workbook(out_path) - ws = wb["Formula Ingredients Statement"] - max_col = max(1, ws.max_column) - - ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=max_col) - ws["A1"] = "Formular Ingredients Statement" - ws["A1"].font = Font(bold=True, size=22, underline="single") - ws["A1"].alignment = Alignment(horizontal="center", vertical="center") - - ws.merge_cells(start_row=4, start_column=1, end_row=4, end_column=max_col) - ws["A4"] = f"PRODUCT NAME : {safe_str(product_name)}" - ws["A4"].font = Font(bold=True, size=13) - ws["A4"].alignment = Alignment(horizontal="left", vertical="center") - - wb.save(out_path) - style_output_workbook(out_path) - - -def style_output_workbook(path): - wb = load_workbook(path) - - thin_border = Border( - left=Side(style="thin", color="808080"), - right=Side(style="thin", color="808080"), - top=Side(style="thin", color="808080"), - bottom=Side(style="thin", color="808080"), - ) - - header_fill = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid") - issue_fill = PatternFill(start_color="FFF2CC", end_color="FFF2CC", fill_type="solid") - fail_fill = PatternFill(start_color="F4CCCC", end_color="F4CCCC", fill_type="solid") - pass_fill = PatternFill(start_color="D9EAD3", end_color="D9EAD3", fill_type="solid") - label_fill = PatternFill(start_color="D9EAF7", end_color="D9EAF7", fill_type="solid") - - header_font = Font(color="000000", bold=True, size=10) - body_font = Font(color="000000", size=10) - title_font = Font(color="000000", bold=True, size=22, underline="single") - product_font = Font(color="000000", bold=True, size=13) - - for ws in wb.worksheets: - if ws.title == "Formula Ingredients Statement": - header_row = 6 - ws.sheet_view.showGridLines = False - - ws.row_dimensions[1].height = 32 - ws.row_dimensions[2].height = 20 - ws.row_dimensions[3].height = 20 - ws.row_dimensions[4].height = 24 - ws.row_dimensions[5].height = 18 - ws.row_dimensions[6].height = 26 - - ws["A1"].font = title_font - ws["A1"].alignment = Alignment(horizontal="center", vertical="center") - ws["A4"].font = product_font - ws["A4"].alignment = Alignment(horizontal="left", vertical="center") - - for row in range(header_row, ws.max_row + 1): - for col in range(1, ws.max_column + 1): - cell = ws.cell(row=row, column=col) - cell.border = thin_border - cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) - cell.font = body_font - - if row == header_row: - cell.fill = header_fill - cell.font = header_font - - if row > header_row: - value = safe_str(cell.value) - if value == "FAIL": - cell.fill = fail_fill - cell.font = Font(color="9C0006", bold=True) - elif value == "CHECK": - cell.fill = issue_fill - cell.font = Font(color="9C6500", bold=True) - elif value == "LABEL": - cell.fill = label_fill - cell.font = Font(color="0B5394", bold=True) - elif value == "PASS": - cell.fill = pass_fill - cell.font = Font(color="38761D", bold=True) - - total_row = None - for row in range(header_row + 1, ws.max_row + 1): - if safe_str(ws.cell(row=row, column=3).value).upper() == "TOTAL": - total_row = row - break - - if total_row: - for col in range(1, ws.max_column + 1): - cell = ws.cell(row=total_row, column=col) - cell.font = Font(bold=True) - cell.border = thin_border - cell.alignment = Alignment(horizontal="center", vertical="center") - try: - ws.merge_cells(start_row=total_row, start_column=2, end_row=total_row, end_column=6) - ws.cell(row=total_row, column=2).value = "TOTAL" - ws.cell(row=total_row, column=2).font = Font(bold=True) - ws.cell(row=total_row, column=2).alignment = Alignment(horizontal="center", vertical="center") - ws.cell(row=total_row, column=3).value = None - except Exception: - pass - - widths = { - 1: 6, - 2: 28, - 3: 34, - 4: 24, - 5: 16, - 6: 10, - 7: 12, - } - for col_idx in range(1, ws.max_column + 1): - col_letter = get_column_letter(col_idx) - ws.column_dimensions[col_letter].width = widths.get(col_idx, 10) - - for row in range(header_row + 1, ws.max_row + 1): - cell = ws.cell(row=row, column=7) - if to_number(cell.value) is not None: - cell.number_format = "0.000######" - - ws.freeze_panes = "A7" - - else: - header_row = 1 - ws.sheet_view.showGridLines = False - - for row in range(1, ws.max_row + 1): - for col in range(1, ws.max_column + 1): - cell = ws.cell(row=row, column=col) - cell.border = thin_border - cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) - - if row == header_row: - cell.fill = PatternFill(start_color="D9D9D9", end_color="D9D9D9", fill_type="solid") - cell.font = header_font - - for col_idx in range(1, ws.max_column + 1): - col_letter = get_column_letter(col_idx) - header = safe_str(ws.cell(row=header_row, column=col_idx).value) - if header in ["Evidence", "검색 원문", "Evidence Text"]: - ws.column_dimensions[col_letter].width = 70 - elif header in ["Result", "Required Action", "비고"]: - ws.column_dimensions[col_letter].width = 45 - elif header in ["INCI Name", "Ingredient"]: - ws.column_dimensions[col_letter].width = 32 - else: - ws.column_dimensions[col_letter].width = 18 - - ws.freeze_panes = "A2" - - wb.save(path) + if ckey not in ["EU", "EU_FUTURE", "UK", "KOREA"]: + continue -# ============================================================ -# 12. 메인 처리 -# ============================================================ - -def process(countries, file, product_name="", use_mfds_live=False, mfds_max_terms=30, mfds_headless=True): - global RAW_SEARCH_LOGS - RAW_SEARCH_LOGS = [] - - try: - if not file: - return None, None, "❌ 엑셀 파일을 업로드해주세요." - if not countries: - return None, None, "❌ 스크리닝 국가를 선택해주세요." - - df = pd.read_excel(file.name) - grouped_materials, meta = make_grouped_materials(df) - if not grouped_materials: - return None, None, "❌ 엑셀에서 원료 정보를 읽지 못했습니다. 컬럼명 또는 합계/footer 위치를 확인해주세요." - - ingredient_totals = meta["ingredient_totals"] - ingredient_amount_parts = meta["ingredient_amount_parts"] - mfds_df = pd.DataFrame() - mfds_live_msg = "" - - llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) - - row_items = [] - for material in grouped_materials: - components = material["Components"] - for idx, comp in enumerate(components): - is_first = idx == 0 - target_id = f"row_{len(row_items)}" - row_data = { - "NO": material["NO"] if is_first else "", - "Trade name(국문)": material["Trade name(국문)"] if is_first else "", - "Trade name(영문)": material["Trade name(영문)"] if is_first else "", - "한글 성분명": comp["한글 성분명"], - "INCI Name": comp["INCI Name"], - "Contents\n(w/w %)": comp["Contents(w/w %)"] if is_first else "", - "In formula\n(w/w %)": comp["In formula(w/w %)"], - "Result": "", - } - row_items.append({"target_id": target_id, "material": material, "component": comp, "row_data": row_data, "notes": []}) - - if use_mfds_live: - try: - terms = extract_terms_for_mfds_live(row_items) - mfds_df, mfds_live_msg = mfds_live_lookup_terms( - terms=terms, - max_terms=mfds_max_terms, - headless=mfds_headless, - ) - except Exception as e: - mfds_df = pd.DataFrame() - mfds_live_msg = f"MFDS 실시간 조회 실패: {e}" - - for country in countries: - col_name = display_country(country) - gpt_targets = [] - - for item in row_items: - local_result = evaluate_local_rules(country, item["material"], item["component"], ingredient_totals, ingredient_amount_parts) - if local_result is not None: - item["row_data"][col_name] = local_result.get("결과", "") - note = safe_str(local_result.get("비고", "-")) - if note and note != "-": - item["notes"].append(f"{col_name}: {note}") - log_search_context(item["target_id"], country, item["component"], local_result.get("결과", ""), "LOCAL_RULE", note if note and note != "-" else "로컬 고정 규칙 우선 판정") - continue - - mfds_result = None - if use_mfds_live and mfds_df is not None and not mfds_df.empty: - mfds_result = evaluate_mfds_detail_rule(country, item["material"], item["component"], mfds_df) - - if mfds_result is not None: - item["row_data"][col_name] = mfds_result.get("결과", "") - note = safe_str(mfds_result.get("비고", "-")) - if note and note != "-": - item["notes"].append(f"{col_name}: {note}") - log_search_context(item["target_id"], country, item["component"], mfds_result.get("결과", ""), "MFDS_DETAIL_DB", note) - continue - - gpt_targets.append({"target_id": item["target_id"], "material": item["material"], "component": item["component"]}) - - batch_results = evaluate_components_with_llm_batch(country, gpt_targets, llm) - - for item in row_items: - if col_name in item["row_data"]: - continue - result = batch_results.get(item["target_id"]) - if result is None: - result = {"대표 INCI": safe_str(item["component"].get("INCI Name", "")) or "-", "결과": "확인 필요", "비고": "batch 결과 누락"} - item["row_data"][col_name] = result.get("결과", "") - note = safe_str(result.get("비고", "-")) - if note and note != "-": - item["notes"].append(f"{col_name}: {note}") - - country_cols = [display_country(c) for c in countries] - for item in row_items: - row_data = item["row_data"] - row_data["Result"] = build_integrated_result(row_data, country_cols) - row_data["비고"] = " / ".join(item["notes"]) if item["notes"] else "-" - - formula_df = make_formula_statement_rows(row_items, country_cols) - regulatory_df = make_regulatory_summary_rows(row_items, country_cols) - - raw_columns = ["target_id", "국가/채널", "성분명", "INCI Name", "판정", "출처", "검색 원문"] - raw_df = pd.DataFrame(RAW_SEARCH_LOGS) - if raw_df.empty: - raw_df = pd.DataFrame(columns=raw_columns) - else: - for col in raw_columns: - if col not in raw_df.columns: - raw_df[col] = "" - raw_df = raw_df[raw_columns] - - formula_total = sum_formula_percent(formula_df) - safe_country_name = "_".join([re.sub(r"[^a-zA-Z0-9가-힣_-]", "_", str(c)) for c in countries]) - product_part = safe_filename(product_name) if safe_str(product_name) else "product" - out_path = str(OUTPUT_DIR / f"screening_result_{product_part}_{safe_country_name}.xlsx") - - write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw_df) - - issue_count = len(regulatory_df) - mfds_count = len(mfds_df) if mfds_df is not None else 0 - - msg = ( - "✅ 분석 완료\n" - f"- Product Name: {safe_str(product_name) or '-'}\n" - f"- 전성분 행 수: {len(formula_df)}개\n" - f"- In formula 합계: {format_amount(formula_total)}%\n" - f"- 재검토 필요 성분: {issue_count}개\n" - f"- MFDS 실시간 조회 결과 행 수: {mfds_count}개\n" - "- 결과 파일은 3개 시트로 저장했습니다.\n" - " 1) Formula Ingredients Statement: 원본 양식 전성분표 + 국가별 짧은 판정\n" - " 2) Regulatory Screening Summary: 문제 있는 성분만 국가별 요약\n" - " 3) Raw Search Log: 로컬 규칙/MFDS/GPT 검색 근거 로그\n" - "- 판정 우선순위: 로컬 고정 규칙 → MFDS 실시간 조회 → 국가별 FAISS/GPT\n" - f"- MFDS 상태: {mfds_live_msg or '사용 안 함'}\n" - "- GPT 호출 전 검색 원문에 실제 성분명이 없으면 GPT를 호출하지 않고 '해당 자료 내 제한 근거 없음'으로 처리합니다.\n" - "- MergedCell column_letter 오류 수정 완료 버전입니다.\n" - "- public share link가 생성되도록 share=True로 실행합니다." - ) - - return formula_df, out_path, msg - - except Exception as e: - tb = traceback.format_exc() - print(tb) - return None, None, f"❌ 오류 발생: {str(e)}\n\n{tb[-3000:]}" - - -# ============================================================ -# 13. Gradio UI -# ============================================================ - -with gr.Blocks(css=custom_css) as demo: - gr.Markdown("# 🌍 reBom Regulatory Screening AI") - gr.Markdown("### 글로벌 화장품 규제 기반 전성분 스크리닝 + MFDS 상세 DB 연동") - - with gr.Row(): - gr.Button("🚪 로그아웃", link="/logout?all_session=false", variant="secondary") - - with gr.Tab("🚀 스크리닝"): - country = gr.CheckboxGroup( - choices=get_country_folders(), - value=[], - label="🌍 국가 / 채널 선택", - elem_id="country_checks", - ) - - refresh = gr.Button("🔄 폴더/규제파일 새로고침") - - product_name = gr.Textbox(label="제품명 / PRODUCT NAME", placeholder="예: Mania Holic Sunscreen Pack") - - file = gr.File(label="전성분 엑셀 업로드", file_types=[".xlsx"]) - - use_mfds_live = gr.Checkbox(label="식약처 사이트 실시간 조회 사용", value=False) - - mfds_max_terms = gr.Number( - label="식약처 실시간 조회 최대 검색어 수", - value=30, - precision=0, - ) + total_amount = ingredient_totals.get(fragrance_key, amount) + total_text = format_percent(total_amount) if total_amount is not None else "함량 확인 필요" - mfds_headless = gr.Checkbox( - label="식약처 조회 브라우저 숨김 모드", - value=True, + result_text = ( + f"향료 알레르겐 / {rule['label']} 총 {total_text}%, " + f"Leave-on 기준 {format_percent(rule['leave_on'])}%, " + f"Wash-off 기준 {format_percent(rule['wash_off'])}% 확인 필요" ) - btn = gr.Button("🚀 분석 시작", variant="primary") - - df_out = gr.Dataframe(label="미리보기 - Formula Ingredients Statement", wrap=True, interactive=False) - file_out = gr.File(label="결과 다운로드") - msg_out = gr.Textbox(label="상태 / 오류 메시지", interactive=False, lines=14) - - refresh.click(fn=refresh_country_choices_and_clear_cache, inputs=country, outputs=country) - - try: - auto_refresh_timer = gr.Timer(15) - auto_refresh_timer.tick(fn=refresh_country_choices_keep_selection, inputs=country, outputs=country) - except Exception as e: - print(f"자동 국가 목록 갱신 타이머 비활성화: {e}") - - file.change(fn=preview_excel, inputs=file, outputs=df_out) - btn.click(process, inputs=[country, file, product_name, use_mfds_live, mfds_max_terms, mfds_headless], outputs=[df_out, file_out, msg_out]) - - # MFDS 엑셀 DB 관리 탭은 제거했습니다. - # 식약처 정보는 스크리닝 탭의 '식약처 사이트 실시간 조회 사용' 옵션으로만 조회합니다. - - -# ============================================================ -# 14. 로그인 인증 -# ============================================================ - -USER_DB = { - "jin2li@rebom.kr": "qwer0515!", - "jkh@rebom.kr": "rebom123!", - "member2": "1111", -} - - -def auth_fn(username, password): - username = str(username).strip() - password = str(password).strip() - return username in USER_DB and USER_DB[username] == password - + return { + "대표 INCI": rule["label"], + "결과": result_text, + "표시문구": "표시기준 확인", + "비고": "-", + } -# ============================================================ -# 15. 앱 실행 -# ============================================================ + if amount is None: + return { + "대표 INCI": safe_str(component.get("INCI Name", "")) or "-", + "결과": "함량 정보 없음 / In formula(w/w %) 확인 필요", + "표시문구": "함량 확인", + "비고": "-", + } -try: - demo.launch( - server_name="0.0.0.0", - server_port=7860, - share=True, - ssr_mode=False, - auth=auth_fn, - allowed_paths=ALLOWED_PATHS, - blocked_paths=BLOCKED_PATHS, - show_api=False, - footer_links=[], - app_kwargs={"docs_url": None, "redoc_url": None, "openapi_url": None}, - ) -except TypeError: - demo.launch( - server_name="0.0.0.0", - server_port=7860, - share=True, - auth=auth_fn, - allowed_paths=ALLOWED_PATHS, - blocked_paths=BLOCKED_PATHS, - ) + return None