# ============================================================ # 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는 검색된 원문 안에서만 판정 # - 식약처 사이트 실시간 조회 옵션 # - COOS 제거 # - Water 등 일반 성분은 식약처 조회 후순위/제외 # - 식약처 접속 실패 시 3회 재시도 # - 향료는 국가 상관없이 확인 필요 # - 고위험 성분 Pass 자동 방지 # - Formular Ingredients Statement 양식 출력 # - 원본 TOTAL 행 제거 후 새 TOTAL 행 1개만 생성 # ============================================================ import os import re import json import hashlib import traceback import sys import subprocess 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 = "해당 자료 내 제한 근거 없음" NEED_CHECK_TEXT = "확인 필요" LIMIT_CHECK_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"], "ASEAN": {"status": "allowed", "limit": 10, "formula_text": "배합한도: 10%"}, "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", ""), component.get("CAS.No", ""), component.get("FUNCTION", ""), 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_plain_fragrance_component(material, component): texts = [ component.get("한글 성분명", ""), component.get("INCI Name", ""), component.get("FUNCTION", ""), material.get("Trade name(국문)", ""), material.get("Trade name(영문)", ""), ] compact = normalize_compact(" ".join([safe_str(x) for x in texts if safe_str(x)])) fragrance_words = [ "향료", "fragrance", "parfum", "perfume", "aroma", ] return any(normalize_compact(w) in compact for w in fragrance_words) def evaluate_plain_fragrance_rule(country, material, component): if not is_plain_fragrance_component(material, component): return None return { "대표 INCI": safe_str(component.get("INCI Name", "")) or "Fragrance", "결과": f"향료 / {display_country(country)} 알레르겐 표시성분 및 세부 조성 확인 필요", "표시문구": NEED_CHECK_TEXT, "비고": "향료는 세부 구성성분 및 알레르겐 표시대상 여부 확인 필요. 자동 Pass 처리 금지.", } def get_restricted_candidate_reason(material, component): if is_plain_fragrance_component(material, component): return "향료" uv_key = match_rule_key(material, component, UV_FILTER_RULES) if uv_key: return "UV 필터" preservative_key = match_rule_key(material, component, PRESERVATIVE_RULES) if preservative_key: return "보존제/제한성분" functional_key = match_rule_key(material, component, FUNCTIONAL_KOREA_RULES) if functional_key: return "기능성 성분" identity = get_identity_text(material, component) for _, 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: return "향료 알레르겐" function_text = normalize_text(component.get("FUNCTION", "")) inci_text = normalize_text(component.get("INCI Name", "")) high_risk_words = [ "sunscreen", "uv filter", "preservative", "colorant", "hair dye", "retinol", "retinal", "retinyl", "salicylic acid", ] if any(w in function_text for w in high_risk_words) or any(w in inci_text for w in high_risk_words): return "제한 가능성 성분" return "" 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 LIMIT_CHECK_TEXT in text: return LIMIT_CHECK_TEXT if NEED_CHECK_TEXT in text: return NEED_CHECK_TEXT if "향료" in text or "fragrance" in lower or "parfum" in lower: return NEED_CHECK_TEXT 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 == "ASEAN": return "배합한도: 10%" 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 NEED_CHECK_TEXT 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 install_playwright_chromium_once(): try: print("🔧 Playwright Chromium 설치 시도 중...") result = subprocess.run( [sys.executable, "-m", "playwright", "install", "chromium"], capture_output=True, text=True, timeout=300, ) if result.returncode == 0: print("✅ Playwright Chromium 설치 완료") return True, "Chromium 설치 완료" msg = (result.stdout or "") + "\n" + (result.stderr or "") print("❌ Playwright Chromium 설치 실패:", msg[-1000:]) return False, msg[-1000:] except Exception as e: print("❌ Playwright Chromium 설치 예외:", e) return False, str(e) def extract_terms_for_live_lookup(row_items): """ 식약처 실시간 조회용 검색어 추출. Water, Glycerin 같은 일반 성분은 제외하고, UV 필터/보존제/기능성/제한 가능성 성분을 우선 조회한다. """ skip_words = { "water", "aqua", "정제수", "glycerin", "글리세린", "butylene glycol", "부틸렌글라이콜", "dipropylene glycol", "다이프로필렌글라이콜", "1,2-hexanediol", "1,2-헥산다이올", "xanthan gum", "잔탄검", "cellulose", "셀룰로오스", "silica", "실리카", "arginine", "알지닌", "sodium hyaluronate", "소듐하이알루로네이트", "ethylhexylglycerin", "에틸헥실글리세린", } priority_terms = [] normal_terms = [] for item in row_items: material = item["material"] comp = item["component"] high_risk_reason = get_restricted_candidate_reason(material, comp) if is_plain_fragrance_component(material, comp): continue candidate_values = [ comp.get("INCI Name", ""), comp.get("한글 성분명", ""), comp.get("CAS.No", ""), ] for value in candidate_values: value = safe_str(value) if not value or value == "-": continue key = normalize_compact(value) if len(key) < 3: continue is_skip = any(normalize_compact(w) == key for w in skip_words) if is_skip and not high_risk_reason: continue if high_risk_reason: priority_terms.append(value) else: normal_terms.append(value) merged = priority_terms + normal_terms seen = set() unique = [] for term in merged: key = normalize_compact(term) if key and key not in seen: seen.add(key) unique.append(term) return unique def mfds_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_fill_search_input(page, term): selectors = [ "input[type='search']", "input[type='text']", "input[placeholder*='검색']", "input[placeholder*='성분']", "input[placeholder*='원료']", "input[placeholder*='INCI']", "input:not([type])", ] for selector in selectors: try: loc = page.locator(selector) for i in range(min(loc.count(), 30)): 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_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 selectors = [ "button[type='submit']", "input[type='submit']", "button", "a", ".search", ".btn-search", ".btn_search", ] for selector in selectors: try: loc = page.locator(selector) for i in range(min(loc.count(), 30)): item = loc.nth(i) try: if selector == "input[type='submit']": item.click(timeout=3000) return True text = "" try: text = item.inner_text(timeout=500) except Exception: pass if "검색" in text or "Search" in text or "조회" in text or selector in [".search", ".btn-search", ".btn_search"]: item.click(timeout=3000) return True except Exception: continue except Exception: continue return False def mfds_click_result_row(page, term): term_norm = normalize_compact(term) selectors = [ "table tbody tr", "tbody tr", "tr", ".list li", ".result li", ".search-result li", ".card", "a", ] for selector in selectors: try: rows = page.locator(selector) for i in range(min(rows.count(), 50)): 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(2000) 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(2000) return True except Exception: pass return False def parse_mfds_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 - 500) end = min(len(clean), found_index + 1500) snippet = clean[start:end] snippet_lower = snippet.lower() has_reg_keyword = any( k in snippet_lower for k in [ "금지", "사용금지", "배합금지", "제한", "한도", "배합한도", "최대", "max", "maximum", "limit", "restricted", "prohibited", "banned", "%", ] ) if not has_reg_keyword: continue 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[:800], "한도": limit, "조건": "", "출처": "MFDS live: " + MFDS_LIVE_URL, "상세원문": clean[:6000], }) 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(), "MFDS 조회 실패: playwright 미설치 또는 브라우저 미설치" terms = [safe_str(t) for t in terms if safe_str(t)] terms = terms[:int(max_terms)] if max_terms else terms[:30] def run_browser_lookup(): local_rows = [] local_errors = [] with sync_playwright() as p: browser = p.chromium.launch( headless=True, args=[ "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-gpu", "--disable-software-rasterizer", "--disable-extensions", "--disable-background-networking", "--disable-default-apps", "--disable-sync", "--metrics-recording-only", "--mute-audio", ], ) context = browser.new_context( viewport={"width": 1280, "height": 900}, user_agent=( "Mozilla/5.0 (X11; Linux x86_64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/120.0.0.0 Safari/537.36" ), ignore_https_errors=True, ) page = context.new_page() for idx, term in enumerate(terms, start=1): try: print(f"MFDS 실시간 조회 {idx}/{len(terms)}: {term}") goto_success = False last_goto_error = "" for attempt in range(3): try: page.goto( MFDS_LIVE_URL, wait_until="domcontentloaded", timeout=45000, ) page.wait_for_timeout(3000) goto_success = True break except Exception as e: last_goto_error = str(e) page.wait_for_timeout(3000) if not goto_success: local_errors.append(f"{term}: 식약처 접속 실패: {last_goto_error}") continue if not mfds_fill_search_input(page, term): local_errors.append(f"{term}: 검색 입력창 찾기 실패") continue if not mfds_click_search(page): try: page.keyboard.press("Enter") except Exception: pass page.wait_for_timeout(3000) mfds_click_result_row(page, term) page.wait_for_timeout(2000) text = mfds_visible_text(page) rows = parse_mfds_text(term, text) if rows: local_rows.extend(rows) else: local_errors.append(f"{term}: 국가별 배합한도/제한 정보 미검출") except Exception as e: local_errors.append(f"{term}: {e}") context.close() browser.close() return local_rows, local_errors try: all_rows, errors = run_browser_lookup() except Exception as e: err_text = str(e) if "Executable doesn't exist" in err_text or "playwright install" in err_text.lower(): ok, install_msg = install_playwright_chromium_once() if not ok: return pd.DataFrame(), f"MFDS 브라우저 설치 실패: {install_msg}" try: all_rows, errors = run_browser_lookup() except Exception as e2: return pd.DataFrame(), f"MFDS 브라우저 실행 실패: {e2}" else: 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_live_row(material, component, row): identity_values = [ component.get("한글 성분명", ""), component.get("INCI Name", ""), component.get("CAS.No", ""), 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 live_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"] elif col == "ASEAN": aliases += ["ASEAN", "아세안"] 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_live_detail_rule(country, material, component, live_df): if live_df is None or live_df.empty: return None hits = [] for _, row in live_df.iterrows(): if ingredient_matches_live_row(material, component, row) and live_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) label = rule.get("label", key) amount = component.get("amount_float") amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" if not country_rule: return { "대표 INCI": label, "결과": f"{rule_type_name} / {label} / {display_country(country)} 배합한도 자료 확인 필요", "표시문구": LIMIT_CHECK_TEXT, "비고": "로컬 제한성분 목록에는 있으나 해당 국가 한도값 미등록. Pass 처리 금지.", } 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)}% 초과(재검토 필요)" display_text = "한도 초과" else: result_text = f"{rule_type_name} / {label} 현재 함량 {amount_text}%, 한도 {format_percent(limit)}% 이내" display_text = formula_text or f"배합한도: {format_percent(limit)}%" return { "대표 INCI": label, "결과": result_text, "표시문구": display_text, "비고": "-", } return { "대표 INCI": label, "결과": f"{rule_type_name} / {label} / 한도값 확인 필요", "표시문구": LIMIT_CHECK_TEXT, "비고": "로컬 규칙에 성분은 있으나 한도값이 비어 있음. Pass 처리 금지.", } def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts): ckey = country_key(country) amount = component.get("amount_float") plain_fragrance = evaluate_plain_fragrance_rule(country, material, component) if plain_fragrance is not None: return plain_fragrance 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 return { "대표 INCI": rule["label"], "결과": f"향료 알레르겐 / {rule['label']} / {display_country(country)} 표시기준 확인 필요", "표시문구": NEED_CHECK_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, high_risk_reason=""): 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 high_risk_reason and result_text == NO_EVIDENCE_TEXT: result_text = f"{high_risk_reason} / {representative} / {country_col} 제한 여부 확인 필요" display_text = NEED_CHECK_TEXT note = "고위험군 후보 성분이므로 근거 미검출만으로 Pass 처리하지 않음" 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 = NEED_CHECK_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(), safe_str(component.get("CAS.No", "")).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("한글 성분명", "")) cas_no = safe_str(component.get("CAS.No", "")) amount = component.get("amount_float") amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" high_risk_reason = get_restricted_candidate_reason(material, component) if not inci_name and not korean_name: return {"대표 INCI": "-", "결과": "", "표시문구": "", "비고": "-"} if not db: if high_risk_reason: result = { "대표 INCI": inci_name or korean_name or "-", "결과": f"{high_risk_reason} / {inci_name or korean_name} / {country_col} 제한 여부 확인 필요", "표시문구": NEED_CHECK_TEXT, "비고": "해당 국가/채널 규제 DB 없음. 고위험군 후보이므로 Pass 처리하지 않음.", } else: 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: {inci_name} CAS.No: {cas_no} 최종 제품 내 함량: {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, cas_no], k=MEANINGFUL_HIT_K, ) if not has_hit: if high_risk_reason: result = { "대표 INCI": inci_name or korean_name or "-", "결과": f"{high_risk_reason} / {inci_name or korean_name} / {country_col} 제한 여부 확인 필요", "표시문구": NEED_CHECK_TEXT, "비고": "고위험군 후보이나 국가별 규제파일에서 직접 근거 미검출. Pass 처리하지 않음.", } else: 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}"으로 작성해. - 단, 고위험군 후보 성분이면 Pass라고 단정하지 말고 확인 필요로 판단할 수 있다. [검토 성분] 국문명: {korean_name} INCI: {inci_name} CAS.No: {cas_no} 최종 제품 내 함량: {amount_text}% 고위험군 후보 여부: {high_risk_reason or "아님"} [검색된 {country} 규제 원문] {context} 반드시 아래 형식으로만 답변해. 대표 INCI: 결과: 표시문구: 비고: """ try: response = llm.invoke(prompt).content parsed = parse_country_response(response) parsed = sanitize_country_result( parsed, country_col=country_col, component=component, high_risk_reason=high_risk_reason, ) 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 "-", "결과": "확인 필요", "표시문구": NEED_CHECK_TEXT, "비고": 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"] material = item["material"] inci_name = safe_str(comp.get("INCI Name", "")) korean_name = safe_str(comp.get("한글 성분명", "")) high_risk_reason = get_restricted_candidate_reason(material, comp) if high_risk_reason: result = { "대표 INCI": inci_name or korean_name or "-", "결과": f"{high_risk_reason} / {inci_name or korean_name} / {country_col} 제한 여부 확인 필요", "표시문구": NEED_CHECK_TEXT, "비고": "해당 국가/채널 규제 DB 없음. 고위험군 후보이므로 Pass 처리하지 않음.", } else: result = { "대표 INCI": inci_name or "-", "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "-", } results[item["target_id"]] = result log_search_context(item["target_id"], country, comp, result["결과"], "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("한글 성분명", "")) cas_no = safe_str(comp.get("CAS.No", "")) amount = comp.get("amount_float") amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" high_risk_reason = get_restricted_candidate_reason(material, comp) search_text = f""" 국가/채널: {country} 원료명 국문: {material.get("Trade name(국문)", "")} 원료명 영문: {material.get("Trade name(영문)", "")} 검토 성분 국문: {korean_name} 검토 성분 INCI: {inci_name} CAS.No: {cas_no} 최종 제품 내 함량: {amount_text}% """ has_hit, context = has_meaningful_search_hit( db=db, search_text=search_text, ingredient_names=[inci_name, korean_name, cas_no], k=MEANINGFUL_HIT_K, ) if has_hit: filtered_targets.append(item) else: if high_risk_reason: result = { "대표 INCI": inci_name or korean_name or "-", "결과": f"{high_risk_reason} / {inci_name or korean_name} / {country_col} 제한 여부 확인 필요", "표시문구": NEED_CHECK_TEXT, "비고": "고위험군 후보이나 국가별 규제파일에서 직접 근거 미검출. Pass 처리하지 않음.", } 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"] material = item["material"] inci_name = safe_str(comp.get("INCI Name", "")) korean_name = safe_str(comp.get("한글 성분명", "")) cas_no = safe_str(comp.get("CAS.No", "")) amount = comp.get("amount_float") amount_text = format_percent(amount) if amount is not None else "함량 확인 필요" high_risk_reason = get_restricted_candidate_reason(material, comp) target_payload.append({ "target_id": item["target_id"], "성분 국문명": korean_name, "INCI": inci_name, "CAS.No": cas_no, "최종 제품 내 함량(%)": amount_text, "고위험군 후보": high_risk_reason or "아님", }) search_blocks.append(f"{inci_name} {korean_name} {cas_no} {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}"으로 작성해. - 단, 고위험군 후보 성분이면 Pass라고 단정하지 말고 확인 필요로 판단할 수 있다. [검토 대상 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 item_material = None for item in batch: if item["target_id"] == target_id: item_comp = item["component"] item_material = item["material"] break high_risk_reason = "" if item_comp and item_material: high_risk_reason = get_restricted_candidate_reason(item_material, item_comp) parsed_by_id[target_id] = sanitize_country_result( obj, country_col=country_col, component=item_comp or {}, high_risk_reason=high_risk_reason, ) 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, live_max_terms=30, live_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 = "사용 안 함" terms = extract_terms_for_live_lookup(row_items) if use_mfds_live: try: mfds_df, mfds_live_msg = mfds_live_lookup_terms( terms=terms, max_terms=live_max_terms, headless=live_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: fragrance_result = evaluate_plain_fragrance_rule( country=country, material=item["material"], component=item["component"], ) if fragrance_result is not None: item["row_data"][col_name] = fragrance_result.get("결과", "") item["row_data"][col_name + "_display"] = fragrance_result.get("표시문구", NEED_CHECK_TEXT) note = safe_str(fragrance_result.get("비고", "-")) if note and note != "-": item["notes"].append(f"{col_name}: {note}") log_search_context( item["target_id"], country, item["component"], fragrance_result.get("결과", ""), "FRAGRANCE_RULE", note, ) continue mfds_result = None if use_mfds_live and mfds_df is not None and not mfds_df.empty: mfds_result = evaluate_live_detail_rule( country=country, material=item["material"], component=item["component"], live_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("표시문구", NEED_CHECK_TEXT) 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 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 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 "-", "결과": "확인 필요", "표시문구": NEED_CHECK_TEXT, "비고": "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, ) live_max_terms = gr.Number( label="식약처 실시간 조회 최대 검색어 수", value=5, precision=0, ) live_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, live_max_terms, live_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, )