screening / app.py
jin2li's picture
Update app.py
5bf7cd5 verified
Raw History Blame
88.9 kB
# ============================================================ # reBom Regulatory Screening AI - Fast Grounded Fixed Version # - ๊ตญ๊ฐ€/์ฑ„๋„ ํด๋” ์ž๋™ ์ธ์‹ # - ๊ทœ์ œ ํŒŒ์ผ ์ž๋™ ๋ณ€๊ฒฝ ๊ฐ์ง€ # - ๊ตญ๊ฐ€๋ณ„ FAISS ๋ฒกํ„ฐ DB ๋””์Šคํฌ ์บ์‹œ # - ๊ตญ๊ฐ€๋ณ„ ๋ฌธ์„œ ๊ฒฉ๋ฆฌ ๊ฒ€์ƒ‰์œผ๋กœ ํƒ€๊ตญ ๊ทœ์ • ํ™•์‚ฐ ๋ฐฉ์ง€ # - ๋กœ์ปฌ ๊ทœ์น™ ์šฐ์„  ํŒ์ • # - MFDS ์˜์•ฝํ’ˆ์•ˆ์ „๋‚˜๋ผ ์ƒ์„ธ DB ์—‘์…€ ์—ฐ๋™ # - GPT ํ˜ธ์ถœ ์ „ ์˜๋ฏธ ์žˆ๋Š” ๊ฒ€์ƒ‰๊ฒฐ๊ณผ ํ•„ํ„ฐ๋ง # - Formula Ingredients Statement ์›๋ณธ ์–‘์‹ ์ถœ๋ ฅ # - ๋ฌธ์ œ ์„ฑ๋ถ„๋งŒ Regulatory Screening Summary ์ถœ๋ ฅ # - Raw Search Log ๋ณ„๋„ ์ €์žฅ # - Gradio ๋กœ๊ทธ์ธ ์ธ์ฆ / public share link ์ ์šฉ # - MergedCell column_letter ์˜ค๋ฅ˜ ์ˆ˜์ • ์™„๋ฃŒ # ============================================================ # ============================================================ # reBom Regulatory Screening AI # - ๊ตญ๊ฐ€๋ณ„ ๊ทœ์ œ ํด๋” ์•ˆ์—์„œ๋งŒ ๊ฒ€์ƒ‰ # - FAISS ๋””์Šคํฌ ์บ์‹œ # - GPT๋Š” ๊ฒ€์ƒ‰๋œ ์›๋ฌธ ์•ˆ์—์„œ๋งŒ ํŒ์ • # - ์‹์•ฝ์ฒ˜ ์‚ฌ์ดํŠธ ์‹ค์‹œ๊ฐ„ ์กฐํšŒ ์˜ต์…˜ # - Formular Ingredients Statement ์›๋ณธ ์–‘์‹ ์ถœ๋ ฅ # - ์›๋ณธ TOTAL ํ–‰ ์ œ๊ฑฐ ํ›„ ์ƒˆ TOTAL ํ–‰ 1๊ฐœ๋งŒ ์ƒ์„ฑ # ============================================================ import os import re import json import hashlib import traceback from pathlib import Path from collections import defaultdict import pandas as pd import pdfplumber import gradio as gr 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 from openpyxl.styles import PatternFill, Font, Alignment, Border, Side from openpyxl.utils import get_column_letter from langchain_openai import OpenAIEmbeddings, ChatOpenAI from langchain_community.vectorstores import FAISS from langchain_text_splitters import RecursiveCharacterTextSplitter # ============================================================ # 0. ๊ธฐ๋ณธ ์„ค์ • # ============================================================ api_key = os.getenv("OPENAI_API_KEY") print("โœ… OPENAI_API_KEY ์ •์ƒ" if api_key else "โŒ OPENAI_API_KEY ์—†์Œ") BASE_DIR = Path.cwd().resolve() OUTPUT_DIR = (BASE_DIR / "outputs").resolve() OUTPUT_DIR.mkdir(parents=True, exist_ok=True) FAISS_CACHE_DIR = ".faiss_cache" MFDS_LIVE_URL = "https://nedrug.mfds.go.kr/pbp/CCBDF01" NO_EVIDENCE_TEXT = "ํ•ด๋‹น ์ž๋ฃŒ ๋‚ด ์ œํ•œ ๊ทผ๊ฑฐ ์—†์Œ" VECTOR_DB_CACHE = {} EVAL_CACHE = {} EMBEDDINGS_CACHE = None RAW_SEARCH_LOGS = [] SUPPORTED_REG_FILE_EXTENSIONS = {".pdf", ".txt", ".csv", ".xlsx", ".xls"} COUNTRY_ORDER = [ "ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "FDA", "JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA", ] 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", "UK": "UK", "์˜๊ตญ": "UK", "EU (FUTURE)": "EU (FUTURE)", "EU_FUTURE": "EU (FUTURE)", "CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO", "SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA", } COUNTRY_FOLDER_ALIASES = { "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", "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] + [ 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 custom_css = """ #country_checks .wrap, #country_checks .checkbox-group { display: flex !important; flex-direction: row !important; flex-wrap: wrap !important; gap: 10px !important; } #country_checks label { display: inline-flex !important; align-items: center !important; width: auto !important; min-width: 110px !important; padding: 8px 12px !important; border: 1px solid #555 !important; border-radius: 10px !important; margin: 4px !important; } """ # ============================================================ # 1. ๋กœ์ปฌ ๊ทœ์น™ # ============================================================ UV_FILTER_RULES = { "octocrylene": { "label": "Octocrylene", "aliases": ["octocrylene", "์˜ฅํ† ํฌ๋ฆด๋ Œ", "6197-30-4"], "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, "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, "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, "formula_text": "๋ฐฐํ•ฉํ•œ๋„: 5%", }, "FDA": { "status": "allowed", "limit": 3, "formula_text": "๋ฐฐํ•ฉํ•œ๋„: 3%", }, "KOREA": { "status": "allowed", "limit": 5, "formula_text": "๋ฐฐํ•ฉํ•œ๋„: 5%", }, }, } PRESERVATIVE_RULES = { "phenoxyethanol": { "label": "Phenoxyethanol", "aliases": ["phenoxyethanol", "ํŽ˜๋…น์‹œ์—ํƒ„์˜ฌ", "122-99-6"], "EU": { "status": "allowed", "limit": 1, "formula_text": "๋ฐฐํ•ฉํ•œ๋„: 1%", }, "KOREA": { "status": "allowed", "limit": 1, "formula_text": "๋ฐฐํ•ฉํ•œ๋„: 1%", }, "JAPAN": { "status": "allowed", "limit": 1, "formula_text": "๋ฐฐํ•ฉํ•œ๋„: 1%", }, }, } FUNCTIONAL_KOREA_RULES = { "niacinamide": { "label": "Niacinamide", "aliases": ["niacinamide", "๋‚˜์ด์•„์‹ ์•„๋งˆ์ด๋“œ", "98-92-0"], "result": "๊ธฐ๋Šฅ์„ฑํ™”์žฅํ’ˆ ๊ฒ€ํ†  / Niacinamide ํ˜„์žฌ ํ•จ๋Ÿ‰ {amount}%, ๋ฏธ๋ฐฑ ๊ธฐ๋Šฅ์„ฑ ํ‘œ์‹œยท๊ด‘๊ณ  ์‹œ ์š”๊ฑด ํ™•์ธ ํ•„์š”", "formula_text": "๊ธฐ๋Šฅ์„ฑ ํ™•์ธ", }, "adenosine": { "label": "Adenosine", "aliases": ["adenosine", "์•„๋ฐ๋…ธ์‹ ", "58-61-7"], "result": "๊ธฐ๋Šฅ์„ฑํ™”์žฅํ’ˆ ๊ฒ€ํ†  / Adenosine ํ˜„์žฌ ํ•จ๋Ÿ‰ {amount}%, ์ฃผ๋ฆ„๊ฐœ์„  ๊ธฐ๋Šฅ์„ฑ ํ‘œ์‹œยท๊ด‘๊ณ  ์‹œ ์š”๊ฑด ํ™•์ธ ํ•„์š”", "formula_text": "๊ธฐ๋Šฅ์„ฑ ํ™•์ธ", }, } FRAGRANCE_ALLERGEN_RULES = { "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, }, } # ============================================================ # 2. ๊ณตํ†ต ์œ ํ‹ธ # ============================================================ def safe_str(x): if pd.isna(x): return "" return str(x).strip() def normalize_text(text): text = safe_str(text).lower() text = text.replace("ฮฑ", "alpha").replace("ฮฒ", "beta") text = re.sub(r"[^a-z0-9๊ฐ€-ํžฃ]+", " ", text) return re.sub(r"\s+", " ", text).strip() def normalize_compact(text): return re.sub(r"\s+", "", normalize_text(text)) def is_total_like_text(text): compact = normalize_compact(text) return compact in ["total", "ํ•ฉ๊ณ„", "์ดํ•ฉ", "sum"] or compact.startswith("total") or compact.startswith("ํ•ฉ๊ณ„") def row_has_total_like(row_values): values = [safe_str(v) for v in row_values if safe_str(v)] for value in values: if is_total_like_text(value): return True row_text = " ".join(values) row_compact = normalize_compact(row_text) if ( row_compact in ["total", "ํ•ฉ๊ณ„", "์ดํ•ฉ", "sum"] or row_compact.startswith("total") or row_compact.startswith("ํ•ฉ๊ณ„") or "total100" in row_compact or "ํ•ฉ๊ณ„100" in row_compact ): return True return False def country_key(country): text = safe_str(country).upper().replace("_", " ").replace("-", " ") text = re.sub(r"\s+", " ", text).strip() mapping = { "ํ•œ๊ตญ": "KOREA", "KOREA": "KOREA", "KR": "KOREA", "EU": "EU", "E.U.": "EU", "EUROPE": "EU", "์œ ๋Ÿฝ": "EU", "EU FUTURE": "EU_FUTURE", "EU (FUTURE)": "EU_FUTURE", "JAPAN": "JAPAN", "JP": "JAPAN", "์ผ๋ณธ": "JAPAN", "CHINA": "CHINA", "CN": "CHINA", "์ค‘๊ตญ": "CHINA", "USA": "FDA", "US": "FDA", "๋ฏธ๊ตญ": "FDA", "FDA": "FDA", "ASEAN": "ASEAN", "์•„์„ธ์•ˆ": "ASEAN", "UK": "UK", "UNITED KINGDOM": "UK", "์˜๊ตญ": "UK", "SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA", } return mapping.get(text, text) def display_country(country): return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), str(country))) def to_number(value): if pd.isna(value): return None text = str(value).strip().replace(",", ".").replace("%", "") if not text: return None try: return float(text) except Exception: return None def is_numeric_like(value): return to_number(value) is not None def format_amount(value, digits=10): num = to_number(value) if num is None: return "" if abs(num) >= 1: text = f"{num:.6f}" else: text = f"{num:.{digits}f}" text = text.rstrip("0").rstrip(".") return text if text else "0" 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() def safe_filename(text): text = safe_str(text) text = re.sub(r"[^a-zA-Z0-9๊ฐ€-ํžฃ._() -]", "_", text) text = text.strip().replace(" ", "_") return text or "unknown" def chunk_list(items, size): for i in range(0, len(items), size): yield items[i:i + size] def get_embeddings(): global EMBEDDINGS_CACHE if EMBEDDINGS_CACHE is None: EMBEDDINGS_CACHE = OpenAIEmbeddings(model="text-embedding-3-small") return EMBEDDINGS_CACHE def get_identity_text(material, component): texts = [ component.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", ""), component.get("INCI Name", ""), material.get("Trade name(๊ตญ๋ฌธ)", ""), material.get("Trade name(์˜๋ฌธ)", ""), ] return normalize_text(" ".join([safe_str(x) for x in texts if safe_str(x)])) def match_rule_key(material, component, rule_dict): identity = get_identity_text(material, component) for key, rule in rule_dict.items(): for alias in rule.get("aliases", []): alias_norm = normalize_text(alias) if alias_norm and alias_norm in identity: return key return None def is_country_result_issue(text): text = safe_str(text) if not text or text in ["-", NO_EVIDENCE_TEXT, "Pass", "PASS", "pass"]: return False keywords = [ "๋ฐฐํ•ฉ๊ธˆ์ง€", "๊ธˆ์ง€", "์ดˆ๊ณผ", "๋ถ€์ ํ•ฉ", "์žฌ๊ฒ€ํ† ", "ํ™•์ธ ํ•„์š”", "์ž๋ฃŒ ํ™•์ธ", "ํ‘œ์‹œ ํ•„์š”", "๋ผ๋ฒจ๋ง", "๋ถˆ๊ฐ€", "์ฃผ์˜", "๊ฒฝ๊ณ ", ] return any(k in text for k in keywords) def log_search_context(target_id, country, component, result_text, source, context): RAW_SEARCH_LOGS.append({ "target_id": target_id, "๊ตญ๊ฐ€/์ฑ„๋„": display_country(country), "์„ฑ๋ถ„๋ช…": safe_str(component.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", "")), "INCI Name": safe_str(component.get("INCI Name", "")), "ํŒ์ •": safe_str(result_text), "์ถœ์ฒ˜": safe_str(source), "๊ฒ€์ƒ‰ ์›๋ฌธ": safe_str(context)[:3000], }) 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 "Pass" lower = text.lower() 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 "ํ•œ๋„ ์ดˆ๊ณผ" if "ํ‘œ์‹œ ํ•„์š”" in text or "๋ผ๋ฒจ" in text or "label" in lower: return "๋ผ๋ฒจ๋ง ํ•„์ˆ˜" limit_match = re.search(r"ํ•œ๋„\s*([0-9]+(?:\.[0-9]+)?\s*%)", text) if limit_match: return "๋ฐฐํ•ฉํ•œ๋„: " + limit_match.group(1).replace(" ", "") 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 text[:120] # ============================================================ # 3. ๊ตญ๊ฐ€ ํด๋” / ๊ทœ์ œ DB # ============================================================ 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 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 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 refresh_country_choices_and_clear_cache(current_values=None): VECTOR_DB_CACHE.clear() EVAL_CACHE.clear() return refresh_country_choices_keep_selection(current_values) 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()) 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): 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) 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}") 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: 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: 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 preview_excel(file): if not file: return None try: return pd.read_excel(file.name) except Exception as e: return pd.DataFrame({"์˜ค๋ฅ˜": [str(e)]}) 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] def find_optional_col(df, keywords, exclude_cols=None): exclude_cols = exclude_cols or [] best = None best_score = 0 for idx, col in enumerate(df.columns): if col in exclude_cols: continue header = str(col).lower() score = 0 for kw in keywords: if kw.lower() in header: score += 30 if score > best_score: best_score = score best = col return best 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_optional_col( df, ["trade name(๊ตญ๋ฌธ)", "trade name ๊ตญ๋ฌธ", "์›๋ฃŒ๋ช…", "์ƒํ’ˆ๋ช…", "๊ตญ๋ฌธ"], exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col, formula_col], ) trade_en_col = find_optional_col( df, ["trade name(์˜๋ฌธ)", "trade name ์˜๋ฌธ", "trade", "raw material", "material", "์˜๋ฌธ"], 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", "no.", "๋ฒˆํ˜ธ", "์ˆœ๋ฒˆ"]: continue if korean_text in ["ํ•œ๊ธ€ ํ‘œ์ค€ํ™” ๋ช…์นญ", "ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", "ํ•œ๊ธ€์„ฑ๋ถ„๋ช…", "๊ตญ๋ฌธ ์„ฑ๋ถ„๋ช…"]: continue if inci_text in ["ingredient name (inci)", "inci", "inci name"]: continue if ( is_total_like_text(no_text) or is_total_like_text(korean_text) or is_total_like_text(inci_text) or row_has_total_like(row_values) ): 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 ( is_total_like_text(no_value) or is_total_like_text(korean_ing) or is_total_like_text(inci_name) or row_has_total_like(row.values) ): continue 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: if item.is_visible(timeout=1000) and item.is_enabled(timeout=1000): item.fill(term, timeout=3000) return True except Exception: continue except Exception: continue return False def mfds_live_click_search(page): for txt in ["๊ฒ€์ƒ‰", "์กฐํšŒ", "Search"]: try: loc = page.get_by_text(txt, exact=True) if loc.count() > 0: loc.first.click(timeout=3000) 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: 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) for i in range(min(rows.count(), 30)): row = rows.nth(i) try: 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: loc.first.click(timeout=3000) page.wait_for_timeout(1500) 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"], "FDA": ["๋ฏธ๊ตญ", "usa", "fda", "united states"], "Korea": ["ํ•œ๊ตญ", "๋Œ€ํ•œ๋ฏผ๊ตญ", "korea"], "์ผ๋ณธ": ["์ผ๋ณธ", "japan"], "์ค‘๊ตญ": ["์ค‘๊ตญ", "china"], "ASEAN": ["asean", "์•„์„ธ์•ˆ"], "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, "CAS.No": "", "๊ตฌ๋ถ„": 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 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", ) 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 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 mfds_row_country_matches(country, row_country): row_country_norm = normalize_compact(row_country) col = display_country(country) aliases = [country, col, country_key(country)] 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 evaluate_mfds_detail_rule(country, material, component, mfds_df): if mfds_df is None or mfds_df.empty: return None 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 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")) parts = [category] if limit: parts.append(f"ํ•œ๋„ {limit}") if regulation: parts.append(regulation[:300]) result_text = " / ".join([p for p in parts if p]) return { "๋Œ€ํ‘œ INCI": safe_str(component.get("INCI Name", "")) or safe_str(row.get("์›๋ฃŒ๋ช…", "")) or "-", "๊ฒฐ๊ณผ": result_text, "ํ‘œ์‹œ๋ฌธ๊ตฌ": normalize_formula_country_text(result_text, display_country(country), component.get("INCI Name", "")), "๋น„๊ณ ": source, } # ============================================================ # 7. ๋กœ์ปฌ ๊ทœ์น™ ํŒ์ • # ============================================================ def evaluate_limit_rule(country, material, component, rule_group, rule_type_name): ckey = country_key(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 label = rule.get("label", key) 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}% / ์žฌ๊ฒ€ํ†  ํ•„์š”", "ํ‘œ์‹œ๋ฌธ๊ตฌ": formula_text or "๋ฐฐํ•ฉ๊ธˆ์ง€", "๋น„๊ณ ": "-", } limit = country_rule.get("limit") if limit is not None: 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, "ํ‘œ์‹œ๋ฌธ๊ตฌ": "Pass", "๋น„๊ณ ": "-", } def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts): ckey = country_key(country) amount = component.get("amount_float") uv_result = evaluate_limit_rule(country, material, component, UV_FILTER_RULES, "UV ํ•„ํ„ฐ") if uv_result is not None: return uv_result preservative_result = evaluate_limit_rule(country, material, component, PRESERVATIVE_RULES, "๋ณด์กด์ œ/์ œํ•œ์„ฑ๋ถ„") if preservative_result is not None: 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("formula_text", "๊ธฐ๋Šฅ์„ฑ ํ™•์ธ"), "๋น„๊ณ ": "๊ธฐ๋Šฅ์„ฑ ํ‘œ์‹œยท๊ด‘๊ณ  ์—ฌ๋ถ€ ํ™•์ธ", } 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 if not matched: continue if ckey not in ["EU", "EU_FUTURE", "UK", "KOREA"]: continue total_amount = ingredient_totals.get(fragrance_key, amount) total_text = format_percent(total_amount) if total_amount is not None else "ํ•จ๋Ÿ‰ ํ™•์ธ ํ•„์š”" result_text = ( f"ํ–ฅ๋ฃŒ ์•Œ๋ ˆ๋ฅด๊ฒ / {rule['label']} ์ด {total_text}%, " f"Leave-on ๊ธฐ์ค€ {format_percent(rule['leave_on'])}%, " f"Wash-off ๊ธฐ์ค€ {format_percent(rule['wash_off'])}% ํ™•์ธ ํ•„์š”" ) return { "๋Œ€ํ‘œ INCI": rule["label"], "๊ฒฐ๊ณผ": result_text, "ํ‘œ์‹œ๋ฌธ๊ตฌ": "ํ‘œ์‹œ๊ธฐ์ค€ ํ™•์ธ", "๋น„๊ณ ": "-", } if amount is None: return { "๋Œ€ํ‘œ INCI": safe_str(component.get("INCI Name", "")) or "-", "๊ฒฐ๊ณผ": "ํ•จ๋Ÿ‰ ์ •๋ณด ์—†์Œ / In formula(w/w %) ํ™•์ธ ํ•„์š”", "ํ‘œ์‹œ๋ฌธ๊ตฌ": "ํ•จ๋Ÿ‰ ํ™•์ธ", "๋น„๊ณ ": "-", } return None # ============================================================ # 8. GPT ๋ณด์กฐ ํŒ์ • # ============================================================ def parse_country_response(text): result = { "๋Œ€ํ‘œ INCI": "-", "๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT, "ํ‘œ์‹œ๋ฌธ๊ตฌ": "Pass", "๋น„๊ณ ": "-", } for line in safe_str(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 "Pass" 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, country_col="", component=None): if not isinstance(parsed, dict): parsed = {} component = component or {} representative = safe_str(parsed.get("๋Œ€ํ‘œ INCI", "")) or safe_str(component.get("INCI Name", "")) or "-" result_text = safe_str(parsed.get("๊ฒฐ๊ณผ", "")) or NO_EVIDENCE_TEXT note = safe_str(parsed.get("๋น„๊ณ ", "")) or "-" display_text = safe_str(parsed.get("ํ‘œ์‹œ๋ฌธ๊ตฌ", "")) if not display_text: display_text = normalize_formula_country_text( result_text, country_col=country_col, inci_name=safe_str(component.get("INCI Name", "")), amount_text=safe_str(component.get("In formula(w/w %)", "")), ) bad_tokens = [ "๊ทœ์ œ๋ช…", "์ด๋Ÿ‰ ๊ณ„์‚ฐ", "๊ทœ์ œ / ์ด๋Ÿ‰", "{๊ทœ์ œ๊ตฐ๋ช…}", "{์„ฑ๋ถ„๋ช…", "{ํ•จ๋Ÿ‰}", "{๊ธฐ์ค€์น˜}", "placeholder", "N/A", "n/a", ] if any(token in result_text for token in bad_tokens): result_text = "ํ™•์ธ ํ•„์š” / ๊ทœ์ œ ์„ธ๋ถ€ ๊ณ„์‚ฐ ์žฌํ™•์ธ ํ•„์š”" display_text = "ํ™•์ธ ํ•„์š”" if note == "-": note = "๊ตฌ์ฒด ํ•œ๋„ ๋˜๋Š” ์ด๋Ÿ‰ ๊ณ„์‚ฐ๊ฐ’ ํ™•์ธ ํ•„์š”" return { "๋Œ€ํ‘œ INCI": representative, "๊ฒฐ๊ณผ": result_text, "ํ‘œ์‹œ๋ฌธ๊ตฌ": display_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) country_col = display_country(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, "ํ‘œ์‹œ๋ฌธ๊ตฌ": "Pass", "๋น„๊ณ ": "-", } 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.get("Trade name(๊ตญ๋ฌธ)", "") trade_en = material.get("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=db, search_text=search_text, ingredient_names=[inci_name, korean_name], k=MEANINGFUL_HIT_K, ) if not has_hit: result = { "๋Œ€ํ‘œ INCI": inci_name or "-", "๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT, "ํ‘œ์‹œ๋ฌธ๊ตฌ": "Pass", "๋น„๊ณ ": "-", } 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}" ํด๋”์—์„œ๋งŒ ๊ฒ€์ƒ‰๋œ ๊ทผ๊ฑฐ๋‹ค. - ์™ธ๋ถ€ ์ง€์‹, ํ•™์Šต ์ง€์‹, ์ผ๋ฐ˜ ๊ทœ์ œ ์ง€์‹์„ ์‚ฌ์šฉํ•˜์ง€ ๋งˆ. - ๋‹ค๋ฅธ ๊ตญ๊ฐ€ ๊ทœ์ •์„ ํ˜„์žฌ ๊ตญ๊ฐ€์— ์ž„์˜ ์ ์šฉํ•˜์ง€ ๋งˆ. - ๊ฒ€์ƒ‰ ์›๋ฌธ์— ๋ช…์‹œ๋˜์ง€ ์•Š์€ ์ œํ•œ, ๋ฐฐํ•ฉ๊ธˆ์ง€, ๋ฐฐํ•ฉํ•œ๋„๋Š” ๋งŒ๋“ค์ง€ ๋งˆ. - ๊ฒ€์ƒ‰ ์›๋ฌธ์— ๋ช…์‹œ๋œ ์ œํ•œ/๊ธˆ์ง€/ํ•œ๋„ ๊ทผ๊ฑฐ๊ฐ€ ์—†์œผ๋ฉด ๊ฒฐ๊ณผ๋Š” ์ •ํ™•ํžˆ "{NO_EVIDENCE_TEXT}"์œผ๋กœ ์ž‘์„ฑํ•ด. [๊ฒ€ํ†  ์„ฑ๋ถ„] ๊ตญ๋ฌธ๋ช…: {korean_name} INCI/CAS: {inci_name} ์ตœ์ข… ์ œํ’ˆ ๋‚ด ํ•จ๋Ÿ‰: {amount_text}% [๊ฒ€์ƒ‰๋œ {country} ๊ทœ์ œ ์›๋ฌธ] {context} ๋ฐ˜๋“œ์‹œ ์•„๋ž˜ ํ˜•์‹์œผ๋กœ๋งŒ ๋‹ต๋ณ€ํ•ด. ๋Œ€ํ‘œ INCI: ๊ฒฐ๊ณผ: ํ‘œ์‹œ๋ฌธ๊ตฌ: ๋น„๊ณ : ํ‘œ์‹œ๋ฌธ๊ตฌ ์ž‘์„ฑ ๊ทœ์น™: - ๋ฌธ์ œ ์—†์œผ๋ฉด "Pass" - ๋ฐฐํ•ฉํ•œ๋„๊ฐ€ ์žˆ์œผ๋ฉด "๋ฐฐํ•ฉํ•œ๋„: 10%"์ฒ˜๋Ÿผ ์งง๊ฒŒ ์ž‘์„ฑ - ์Šคํ”„๋ ˆ์ด/๊ธฐํƒ€์ œํ’ˆ์ฒ˜๋Ÿผ ์กฐ๊ฑด์ด ์žˆ์œผ๋ฉด ์ค„๋ฐ”๊ฟˆ์œผ๋กœ ์ž‘์„ฑ - ๋ผ๋ฒจ ํ‘œ์‹œ๊ฐ€ ํ•„์š”ํ•˜๋ฉด "๋ผ๋ฒจ๋ง ํ•„์ˆ˜" - ์ •ํ™•ํ•œ ํŒ๋‹จ์ด ์–ด๋ ค์šฐ๋ฉด "ํ™•์ธ ํ•„์š”" """ try: response = llm.invoke(prompt).content parsed = parse_country_response(response) parsed = sanitize_country_result(parsed, country_col=country_col, component=component) 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) country_col = display_country(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, "ํ‘œ์‹œ๋ฌธ๊ตฌ": "Pass", "๋น„๊ณ ": "-", } 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) 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=db, search_text=search_text, ingredient_names=[inci_name, korean_name], k=MEANINGFUL_HIT_K, ) if has_hit: filtered_targets.append(item) else: result = { "๋Œ€ํ‘œ INCI": inci_name or "-", "๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT, "ํ‘œ์‹œ๋ฌธ๊ตฌ": "Pass", "๋น„๊ณ ": "-", } 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: 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"], "์„ฑ๋ถ„ ๊ตญ๋ฌธ๋ช…": korean_name, "INCI/CAS": inci_name, "์ตœ์ข… ์ œํ’ˆ ๋‚ด ํ•จ๋Ÿ‰(%)": amount_text, }) search_blocks.append(f"{inci_name} {korean_name} {amount_text}%") search_text = f""" ๊ตญ๊ฐ€/์ฑ„๋„: {country} ๊ฒ€ํ†  ๋Œ€์ƒ ์„ฑ๋ถ„: {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}" ํด๋”์—์„œ๋งŒ ๊ฒ€์ƒ‰๋œ ๊ทผ๊ฑฐ๋‹ค. - ์™ธ๋ถ€ ์ง€์‹, ํ•™์Šต ์ง€์‹, ์ผ๋ฐ˜ ๊ทœ์ œ ์ง€์‹์„ ์‚ฌ์šฉํ•˜์ง€ ๋งˆ. - ๊ฒ€์ƒ‰ ์›๋ฌธ์— ๊ทผ๊ฑฐ๊ฐ€ ์—†์œผ๋ฉด ๊ฒฐ๊ณผ๋Š” ์ •ํ™•ํžˆ "{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} ๋˜๋Š” ๊ทœ์ œ ๋‚ด์šฉ", "ํ‘œ์‹œ๋ฌธ๊ตฌ": "Pass ๋˜๋Š” ๋ฐฐํ•ฉํ•œ๋„/๋ผ๋ฒจ๋ง/ํ™•์ธ ํ•„์š” ๋“ฑ ์งง์€ ๋ฌธ๊ตฌ", "๋น„๊ณ ": "-" }} ] """ 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 not target_id: continue item_comp = None for item in batch: if item["target_id"] == target_id: item_comp = item["component"] break parsed_by_id[target_id] = sanitize_country_result( obj, country_col=country_col, component=item_comp or {}, ) 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=country, material=item["material"], component=item["component"], llm=llm, target_id=target_id, ) except Exception as e: print(f"batch GPT ํŒ์ • ์‹คํŒจ: {country} / {e}") for item in batch: target_id = item["target_id"] if target_id in results: continue results[target_id] = evaluate_component_with_llm( country=country, material=item["material"], component=item["component"], llm=llm, target_id=target_id, ) return results # ============================================================ # 9. ์ถœ๋ ฅ ๋ฐ์ดํ„ฐ ๊ตฌ์„ฑ # ============================================================ 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"] no_value = safe_str(material.get("NO", "")) korean_name = safe_str(comp.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", "")) inci_name = safe_str(comp.get("INCI Name", "")) if ( is_total_like_text(no_value) or is_total_like_text(korean_name) or is_total_like_text(inci_name) ): continue row = { "NO.": no_value, "ํ•œ๊ธ€ ํ‘œ์ค€ํ™” ๋ช…์นญ": korean_name, "INGREDIENT NAME (INCI)": 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 %)", ""), } for country_col in country_cols: raw_text = safe_str(row_data.get(country_col, "")) display_text = safe_str(row_data.get(country_col + "_display", "")) if display_text: row[country_col] = display_text else: row[country_col] = normalize_formula_country_text( raw_text, country_col=country_col, inci_name=inci_name, amount_text=comp.get("In formula(w/w %)", ""), ) 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) 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", "")): 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] def sum_formula_percent(formula_df): total = 0.0 if formula_df is None or formula_df.empty: return total for _, row in formula_df.iterrows(): no_value = safe_str(row.get("NO.", "")) korean_name = safe_str(row.get("ํ•œ๊ธ€ ํ‘œ์ค€ํ™” ๋ช…์นญ", "")) inci_name = safe_str(row.get("INGREDIENT NAME (INCI)", "")) if ( is_total_like_text(no_value) or is_total_like_text(korean_name) or is_total_like_text(inci_name) ): continue num = to_number(row.get("%(w/w)", "")) if num is not None: total += num return total # ============================================================ # 10. ์—‘์…€ ์ €์žฅ / ์Šคํƒ€์ผ # ============================================================ 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=24, 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_font = Font(color="000000", bold=True, size=10) body_font = Font(color="000000", size=10) title_font = Font(color="000000", bold=True, size=24, underline="single") product_font = Font(color="000000", bold=True, size=13) warning_fill = PatternFill(start_color="FCE4D6", end_color="FCE4D6", fill_type="solid") pass_fill = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid") for ws in wb.worksheets: if ws.title == "Formula Ingredients Statement": header_row = 6 ws.sheet_view.showGridLines = False ws.row_dimensions[1].height = 36 ws.row_dimensions[2].height = 20 ws.row_dimensions[3].height = 20 ws.row_dimensions[4].height = 26 ws.row_dimensions[5].height = 18 ws.row_dimensions[6].height = 28 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.font = header_font if row > header_row: value = safe_str(cell.value) if value and value != "Pass" and col >= 8: cell.fill = warning_fill elif value == "Pass": cell.fill = pass_fill 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: 34, 3: 34, 4: 26, 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, 15) 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.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", "๋น„๊ณ "]: ws.column_dimensions[col_letter].width = 45 elif header in ["INCI Name"]: ws.column_dimensions[col_letter].width = 32 else: ws.column_dimensions[col_letter].width = 18 ws.freeze_panes = "A2" wb.save(path) # ============================================================ # 11. ๋ฉ”์ธ ์ฒ˜๋ฆฌ # ============================================================ def build_integrated_result(row_data, country_cols): issue_items = [] for country_col in country_cols: value = safe_str(row_data.get(country_col, "")) if is_country_result_issue(value): issue_items.append(country_col) if not issue_items: return "PASS" return "์žฌ๊ฒ€ํ†  ํ•„์š”: " + ", ".join(issue_items) 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, "โŒ ์—‘์…€์—์„œ ์ „์„ฑ๋ถ„ ์ •๋ณด๋ฅผ ์ฝ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. ์ปฌ๋Ÿผ๋ช…์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”." ingredient_totals = meta["ingredient_totals"] ingredient_amount_parts = meta["ingredient_amount_parts"] llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) row_items = [] for material in grouped_materials: comp = material["Components"][0] target_id = f"row_{len(row_items)}" row_data = { "NO": material.get("NO", ""), "Trade name(๊ตญ๋ฌธ)": material.get("Trade name(๊ตญ๋ฌธ)", ""), "Trade name(์˜๋ฌธ)": material.get("Trade name(์˜๋ฌธ)", ""), "ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…": comp.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", ""), "INCI Name": comp.get("INCI Name", ""), "In formula\n(w/w %)": comp.get("In formula(w/w %)", ""), "Result": "", } row_items.append({ "target_id": target_id, "material": material, "component": comp, "row_data": row_data, "notes": [], }) mfds_df = pd.DataFrame() mfds_live_msg = "์‚ฌ์šฉ ์•ˆ ํ•จ" 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=country, material=item["material"], component=item["component"], ingredient_totals=ingredient_totals, ingredient_amount_parts=ingredient_amount_parts, ) if local_result is not None: item["row_data"][col_name] = local_result.get("๊ฒฐ๊ณผ", "") item["row_data"][col_name + "_display"] = local_result.get("ํ‘œ์‹œ๋ฌธ๊ตฌ", "Pass") 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=country, material=item["material"], component=item["component"], mfds_df=mfds_df, ) if mfds_result is not None: item["row_data"][col_name] = mfds_result.get("๊ฒฐ๊ณผ", "") item["row_data"][col_name + "_display"] = 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_LIVE", note, ) continue gpt_targets.append({ "target_id": item["target_id"], "material": item["material"], "component": item["component"], }) batch_results = evaluate_components_with_llm_batch( country=country, targets=gpt_targets, llm=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("๊ฒฐ๊ณผ", "") item["row_data"][col_name + "_display"] = result.get("ํ‘œ์‹œ๋ฌธ๊ตฌ", "Pass") 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: item["row_data"]["Result"] = build_integrated_result(item["row_data"], country_cols) item["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=out_path, product_name=product_name, formula_df=formula_df, regulatory_df=regulatory_df, raw_df=raw_df, ) 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"- ์žฌ๊ฒ€ํ†  ํ•„์š” ์„ฑ๋ถ„: {len(regulatory_df)}๊ฐœ\n" f"- MFDS ์ƒํƒœ: {mfds_live_msg}\n" "- ๊ฒฐ๊ณผ ํŒŒ์ผ ์‹œํŠธ:\n" " 1) Formula Ingredients Statement\n" " 2) Regulatory Screening Summary\n" " 3) Evidence Log\n" ) 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:]}" # ============================================================ # 12. Gradio UI # ============================================================ with gr.Blocks(css=custom_css) as demo: gr.Markdown("# ๐ŸŒ reBom Regulatory Screening AI") gr.Markdown("### ๊ตญ๊ฐ€๋ณ„ ๊ทœ์ œ ํด๋” ๊ฒ€์ƒ‰ + ์‹์•ฝ์ฒ˜ ์‹ค์‹œ๊ฐ„ ์กฐํšŒ + Formular Ingredients Statement ์ถœ๋ ฅ") 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="์˜ˆ: ๋งˆ๋ฐ์นดํฌ๋ฆผ", ) file = gr.File( label="์ „์„ฑ๋ถ„ ์—‘์…€ ์—…๋กœ๋“œ", file_types=[".xlsx"], ) use_mfds_live = gr.Checkbox( label="์‹์•ฝ์ฒ˜ ์‚ฌ์ดํŠธ ์‹ค์‹œ๊ฐ„ ์กฐํšŒ ์‚ฌ์šฉ", value=False, ) mfds_max_terms = gr.Number( label="์‹์•ฝ์ฒ˜ ์‹ค์‹œ๊ฐ„ ์กฐํšŒ ์ตœ๋Œ€ ๊ฒ€์ƒ‰์–ด ์ˆ˜", value=5, precision=0, ) mfds_headless = gr.Checkbox( label="์‹์•ฝ์ฒ˜ ์กฐํšŒ ๋ธŒ๋ผ์šฐ์ € ์ˆจ๊น€ ๋ชจ๋“œ", value=True, ) btn = gr.Button("๐Ÿš€ ๋ถ„์„ ์‹œ์ž‘", variant="primary") df_out = gr.Dataframe( label="๋ฏธ๋ฆฌ๋ณด๊ธฐ - Formular Ingredients Statement", wrap=True, interactive=False, ) file_out = gr.File(label="๊ฒฐ๊ณผ ๋‹ค์šด๋กœ๋“œ") msg_out = gr.Textbox( label="์ƒํƒœ / ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€", interactive=False, lines=12, ) 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, ], ) # ============================================================ # 13. ๋กœ๊ทธ์ธ ์ธ์ฆ # ============================================================ 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 # ============================================================ # 14. ์•ฑ ์‹คํ–‰ # ============================================================ 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, )
# ============================================================
# reBom Regulatory Screening AI - Fast Grounded Fixed Version
# - ๊ตญ๊ฐ€/์ฑ„๋„ ํด๋” ์ž๋™ ์ธ์‹
# - ๊ทœ์ œ ํŒŒ์ผ ์ž๋™ ๋ณ€๊ฒฝ ๊ฐ์ง€
# - ๊ตญ๊ฐ€๋ณ„ FAISS ๋ฒกํ„ฐ DB ๋””์Šคํฌ ์บ์‹œ
# - ๊ตญ๊ฐ€๋ณ„ ๋ฌธ์„œ ๊ฒฉ๋ฆฌ ๊ฒ€์ƒ‰์œผ๋กœ ํƒ€๊ตญ ๊ทœ์ • ํ™•์‚ฐ ๋ฐฉ์ง€
# - ๋กœ์ปฌ ๊ทœ์น™ ์šฐ์„  ํŒ์ •
# - MFDS ์˜์•ฝํ’ˆ์•ˆ์ „๋‚˜๋ผ ์ƒ์„ธ DB ์—‘์…€ ์—ฐ๋™
# - GPT ํ˜ธ์ถœ ์ „ ์˜๋ฏธ ์žˆ๋Š” ๊ฒ€์ƒ‰๊ฒฐ๊ณผ ํ•„ํ„ฐ๋ง
# - Formula Ingredients Statement ์›๋ณธ ์–‘์‹ ์ถœ๋ ฅ
# - ๋ฌธ์ œ ์„ฑ๋ถ„๋งŒ Regulatory Screening Summary ์ถœ๋ ฅ
# - Raw Search Log ๋ณ„๋„ ์ €์žฅ
# - Gradio ๋กœ๊ทธ์ธ ์ธ์ฆ / public share link ์ ์šฉ
# - MergedCell column_letter ์˜ค๋ฅ˜ ์ˆ˜์ • ์™„๋ฃŒ
# ============================================================
# ============================================================
# reBom Regulatory Screening AI
# - ๊ตญ๊ฐ€๋ณ„ ๊ทœ์ œ ํด๋” ์•ˆ์—์„œ๋งŒ ๊ฒ€์ƒ‰
# - FAISS ๋””์Šคํฌ ์บ์‹œ
# - GPT๋Š” ๊ฒ€์ƒ‰๋œ ์›๋ฌธ ์•ˆ์—์„œ๋งŒ ํŒ์ •
# - ์‹์•ฝ์ฒ˜ ์‚ฌ์ดํŠธ ์‹ค์‹œ๊ฐ„ ์กฐํšŒ ์˜ต์…˜
# - Formular Ingredients Statement ์›๋ณธ ์–‘์‹ ์ถœ๋ ฅ
# - ์›๋ณธ TOTAL ํ–‰ ์ œ๊ฑฐ ํ›„ ์ƒˆ TOTAL ํ–‰ 1๊ฐœ๋งŒ ์ƒ์„ฑ
# ============================================================
import os
import re
import json
import hashlib
import traceback
from pathlib import Path
from collections import defaultdict
import pandas as pd
import pdfplumber
import gradio as gr
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
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
# ============================================================
# 0. ๊ธฐ๋ณธ ์„ค์ •
# ============================================================
api_key = os.getenv("OPENAI_API_KEY")
print("โœ… OPENAI_API_KEY ์ •์ƒ" if api_key else "โŒ OPENAI_API_KEY ์—†์Œ")
BASE_DIR = Path.cwd().resolve()
OUTPUT_DIR = (BASE_DIR / "outputs").resolve()
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
FAISS_CACHE_DIR = ".faiss_cache"
MFDS_LIVE_URL = "https://nedrug.mfds.go.kr/pbp/CCBDF01"
NO_EVIDENCE_TEXT = "ํ•ด๋‹น ์ž๋ฃŒ ๋‚ด ์ œํ•œ ๊ทผ๊ฑฐ ์—†์Œ"
VECTOR_DB_CACHE = {}
EVAL_CACHE = {}
EMBEDDINGS_CACHE = None
RAW_SEARCH_LOGS = []
SUPPORTED_REG_FILE_EXTENSIONS = {".pdf", ".txt", ".csv", ".xlsx", ".xls"}
COUNTRY_ORDER = [
"ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "FDA",
"JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA",
]
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",
"UK": "UK", "์˜๊ตญ": "UK",
"EU (FUTURE)": "EU (FUTURE)", "EU_FUTURE": "EU (FUTURE)",
"CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO",
"SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA",
}
COUNTRY_FOLDER_ALIASES = {