# APP_PATCH_NOTE_SPEED_MFDS_BATCH_OFF = "전체 스크리닝 속도 응급패치: MFDS 실시간 조회 배치 비활성화 + 매칭 캐시" # APP_PATCH_NOTE_LIMIT_POSITIVE_MFDS = "Positive List 한도확인 + MFDS 제한 파싱 보강 적용본" # ============================================================ # 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 오류 수정 완료 # - 엑셀 전성분 전체 스크리닝 # - 단일 성분 검색 # - 전체 스크리닝: MFDS 검색어 0개 방지 # - 단일 성분 검색은 식약처 실시간 조회 사용 # - 국가별 규제 폴더 검색 # - FAISS 디스크 캐시 # - 향료는 전 국가 확인 필요 # - 정제수 / Water / Aqua는 전 국가 기본 Pass # - 국가별 핵심 금지/제한 성분은 GPT/RAG보다 우선 판정 # - Tranexamic Acid는 일본 배합금지 우선 처리 # - 고위험 성분 Pass 자동 방지 # - Formular Ingredients Statement 양식 출력 # - 원본 TOTAL 행 제거 후 새 TOTAL 행 1개만 생성 # - 숫자 없는 '배합한도'는 '배합한도 확인 필요'로 표시 # - Salicylic Acid 자체만 제한 후보 처리 # - Niacinamide/Adenosine은 한국에서만 기능성 확인 처리 # ============================================================ # reBom Regulatory Screening AI - compact full app.py # Excel/PDF/Image input + country folder RAG + local rules + single ingredient search import os, re, json, base64, hashlib, traceback, sqlite3, secrets, datetime, time, sys, subprocess, time from pathlib import Path from collections import defaultdict from functools import lru_cache import pandas as pd import pdfplumber import gradio as gr from openpyxl import load_workbook from openpyxl.styles import PatternFill, Font, Alignment, Border, Side from openpyxl.utils import get_column_letter try: from openai import OpenAI except Exception: OpenAI = None try: import fitz except Exception: fitz = None from langchain_openai import OpenAIEmbeddings, ChatOpenAI from langchain_community.vectorstores import FAISS from langchain_text_splitters import RecursiveCharacterTextSplitter try: from playwright.sync_api import sync_playwright PLAYWRIGHT_AVAILABLE = True except Exception: sync_playwright = None PLAYWRIGHT_AVAILABLE = False BASE_DIR = Path.cwd().resolve() OUTPUT_DIR = BASE_DIR / "outputs" OUTPUT_DIR.mkdir(exist_ok=True) FAISS_CACHE_DIR = ".faiss_cache" REG_INDEX_CACHE_DIR = ".reg_index_cache" NO_EVIDENCE_TEXT = "해당 자료 내 제한 근거 없음" NEED_CHECK_TEXT = "확인 필요" LIMIT_CHECK_TEXT = "배합한도 확인 필요" MFDS_LIVE_URL = "https://nedrug.mfds.go.kr/pbp/CCBDF01" # 속도 응급패치 # - 전체 전성분 스크리닝에서는 MFDS 사이트 실시간 조회를 기본적으로 사용하지 않는다. # - 단일 성분 검색에서는 필요 시 사용 가능하다. ENABLE_MFDS_LIVE_FOR_BATCH = False ENABLE_MFDS_LIVE_FOR_SINGLE = True BATCH_MFDS_DISABLE_REASON = "전체 전성분 스크리닝에서는 속도 보호를 위해 MFDS 실시간 조회를 자동 비활성화함" MFDS_RETRY_COUNT = int(os.getenv("MFDS_RETRY_COUNT", "1")) MFDS_RETRY_WAIT_SEC = float(os.getenv("MFDS_RETRY_WAIT_SEC", "0.5")) MFDS_BETWEEN_TERMS_WAIT_SEC = float(os.getenv("MFDS_BETWEEN_TERMS_WAIT_SEC", "0.2")) VECTOR_DB_CACHE = {} EVAL_CACHE = {} EMBEDDINGS_CACHE = None RAW_SEARCH_LOGS = [] REG_TEXT_CACHE = {} REG_SECTION_INDEX_CACHE = {} COUNTRY_ORDER = ["ASEAN","CALIFORNIA","CHINA","EU (FUTURE)","EU","US","JAPAN","KOREA","MEXICO","SEPHORA","TARGET","UK","ULTA"] COUNTRY_DISPLAY = {"EU":"EU","유럽":"EU","FDA":"US","미국":"US","USA":"US","US":"US","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","FDA":"US","미국":"US","USA":"US","US":"US","us":"us","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)] SUPPORTED_INPUT_EXTENSIONS = {".xlsx",".xls",".pdf",".png",".jpg",".jpeg",".webp"} SUPPORTED_REG_FILE_EXTENSIONS = {".pdf",".txt",".csv",".xlsx",".xls"} 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","리모넨"]},"linalool":{"label":"Linalool","aliases":["linalool","리날룰"]},"citral":{"label":"Citral","aliases":["citral","시트랄"]},"geraniol":{"label":"Geraniol","aliases":["geraniol","제라니올"]},"eugenol":{"label":"Eugenol","aliases":["eugenol","유제놀"]},"benzyl alcohol":{"label":"Benzyl Alcohol","aliases":["benzyl alcohol","벤질알코올"]}} ALWAYS_PASS_INGREDIENTS = {"water":{"label":"Water","aliases":["water","aqua","정제수","7732-18-5"]}} CRITICAL_COUNTRY_RULES = {"tranexamic acid":{"label":"Tranexamic Acid","aliases":["tranexamic acid","트라넥사믹애씨드","트라넥사믹 애씨드","트라넥삼산","트라넥사민산","トラネキサム酸","1197-18-8"],"JAPAN":{"status":"prohibited","formula_text":"배합금지","result":"일본 배합금지 성분 / Tranexamic Acid / 재검토 필요","note":"일본 수출용 제품 사용 불가 여부 확인 필요"}}} custom_css = """ #country_checks .wrap,#country_checks .checkbox-group,#single_country_checks .wrap,#single_country_checks .checkbox-group{display:flex!important;flex-direction:row!important;flex-wrap:wrap!important;gap:10px!important} #country_checks label,#single_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} """ def safe_str(x): if x is None: return "" try: if pd.isna(x): return "" except Exception: pass return str(x).strip() def normalize_text(text): text=safe_str(text).lower().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 to_number(value): if value is None: return None try: if pd.isna(value): return None except Exception: pass text=str(value).strip().replace(",",".").replace("%","") if not text: return None try: return float(text) except Exception: return None def is_numeric_like(v): return to_number(v) is not None def format_amount(value,digits=10): num=to_number(value) if num is None: return "" text=f"{num:.6f}" if abs(num)>=1 else f"{num:.{digits}f}" return text.rstrip("0").rstrip(".") or "0" def format_percent(v): return format_amount(v) def format_no(v): n=to_number(v) return str(int(n)) if n is not None and float(n).is_integer() else safe_str(v) def is_total_like_text(text): c=normalize_compact(text) return c in ["total","합계","총합","sum"] or c.startswith("total") or c.startswith("합계") def row_has_total_like(vals): return any(is_total_like_text(v) for v in vals if safe_str(v)) def stable_hash(obj): return hashlib.sha256(json.dumps(obj,ensure_ascii=False,sort_keys=True,default=str).encode()).hexdigest() def safe_filename(text): return re.sub(r"[^a-zA-Z0-9가-힣._() -]","_",safe_str(text)).strip().replace(" ","_") or "unknown" def chunk_list(items,size): for i in range(0,len(items),size): yield items[i:i+size] def country_key(country): t=safe_str(country).upper().replace("_"," ").replace("-"," "); t=re.sub(r"\s+"," ",t).strip() m={"한국":"KOREA","KOREA":"KOREA","KR":"KOREA","EU":"EU","EUROPE":"EU","유럽":"EU","EU FUTURE":"EU_FUTURE","EU (FUTURE)":"EU_FUTURE","JAPAN":"JAPAN","JP":"JAPAN","일본":"JAPAN","CHINA":"CHINA","CN":"CHINA","중국":"CHINA","USA":"US","US":"US","미국":"US","FDA":"US","ASEAN":"ASEAN","아세안":"ASEAN","UK":"UK","영국":"UK","SEPHORA":"SEPHORA","TARGET":"TARGET","ULTA":"ULTA"} return m.get(t,t) def display_country(country): return COUNTRY_DISPLAY.get(str(country).upper(),COUNTRY_DISPLAY.get(str(country),str(country))) def get_embeddings(): global EMBEDDINGS_CACHE if EMBEDDINGS_CACHE is None: EMBEDDINGS_CACHE=OpenAIEmbeddings(model="text-embedding-3-small") return EMBEDDINGS_CACHE def get_openai_client(): if OpenAI is None: raise RuntimeError("openai 라이브러리가 설치되어 있지 않습니다. requirements.txt에 openai를 추가하세요.") if not os.getenv("OPENAI_API_KEY"): raise RuntimeError("OPENAI_API_KEY 환경변수가 없습니다.") return OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def is_cas_like(text): return bool(re.match(r"^\d{2,7}-\d{2}-\d$", safe_str(text))) def get_identity_raw(material, component): vals = [ component.get("한글 성분명", ""), component.get("INCI Name", ""), component.get("CAS.No", ""), component.get("FUNCTION", ""), material.get("Trade name(국문)", ""), material.get("Trade name(영문)", ""), ] return " ".join(safe_str(x) for x in vals if safe_str(x)) def get_identity_text(material,component): return normalize_text(get_identity_raw(material, component)) @lru_cache(maxsize=20000) def normalized_tokens(text): """ 성분명 비교용 토큰화. Biotin과 meaBiotin처럼 특정 성분명이 긴 단어 내부에 들어간 경우를 다른 성분으로 본다. """ text = safe_str(text).lower().replace("α", "alpha").replace("β", "beta") return [t for t in re.split(r"[^a-z0-9가-힣ぁ-んァ-ン一-龥]+", text) if t] @lru_cache(maxsize=50000) def exact_ingredient_match(term, target_text): """ 성분명/alias가 target_text 안에서 독립 토큰으로 존재할 때만 True. 예: Biotin vs Biotin = True, Biotin vs meaBiotin = False. """ term = safe_str(term) target_text = safe_str(target_text) if not term or not target_text: return False # CAS 번호는 하이픈 포함 완전일치만 허용 if is_cas_like(term): return normalize_compact(term) in [normalize_compact(x) for x in re.findall(r"\d{2,7}-\d{2}-\d", target_text)] term_tokens = normalized_tokens(term) target_tokens = normalized_tokens(target_text) if not term_tokens or not target_tokens: return False # 단일 토큰은 토큰 완전일치만 허용: biotin != meabiotin if len(term_tokens) == 1: return term_tokens[0] in target_tokens # 복수 토큰은 연속 토큰 완전일치 허용: disodium edta == disodium edta n = len(term_tokens) for i in range(len(target_tokens) - n + 1): if target_tokens[i:i+n] == term_tokens: return True return False def any_exact_alias_match(aliases, target_text): return any(exact_ingredient_match(a, target_text) for a in aliases or []) def match_rule_key(material,component,rule_dict): identity = get_identity_raw(material, component) for k,r in rule_dict.items(): if any_exact_alias_match(r.get("aliases", []), identity): return k return None def is_always_pass_component(material,component): return match_rule_key(material,component,ALWAYS_PASS_INGREDIENTS) is not None def is_critical_country_candidate(material,component): return match_rule_key(material,component,CRITICAL_COUNTRY_RULES) is not None def is_plain_fragrance_component(material,component): identity=normalize_compact(" ".join([component.get("한글 성분명",""),component.get("INCI Name",""),component.get("FUNCTION",""),component.get("CAS.No",""),material.get("Trade name(국문)",""),material.get("Trade name(영문)","")])) return any(normalize_compact(w) in identity for w in ["향료","fragrance","parfum","perfume","aroma"]) 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_always_pass_component(material,component): return "" if is_critical_country_candidate(material,component): return "국가별 금지/제한 핵심 성분" if is_plain_fragrance_component(material,component): return "향료" if match_rule_key(material,component,UV_FILTER_RULES): return "UV 필터" if match_rule_key(material,component,PRESERVATIVE_RULES): return "보존제/제한성분" identity=get_identity_raw(material,component) for r in FRAGRANCE_ALLERGEN_RULES.values(): if any_exact_alias_match(r.get("aliases",[]), identity): return "향료 알레르겐" f=normalize_text(component.get("FUNCTION","")); inci=normalize_text(component.get("INCI Name","")) if any(w in f or w in inci for w in ["sunscreen","uv filter","preservative","colorant","hair dye","retinol","retinal","retinyl"]): return "제한 가능성 성분" if normalize_compact(component.get("INCI Name",""))==normalize_compact("Salicylic Acid"): return "제한 가능성 성분" if normalize_compact(component.get("한글 성분명",""))==normalize_compact("살리실릭애씨드"): 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 return any(k in text for k in ["배합금지","금지","초과","부적합","재검토","확인 필요","자료 확인","표시 필요","라벨링","불가","주의","경고","배합한도 확인 필요","기능성 확인","함량 확인"]) 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 extract_verified_limit_from_evidence(evidence_text,ingredient_names): evidence_text=safe_str(evidence_text) names_norm=[normalize_compact(x) for x in ingredient_names if normalize_compact(x)] if not evidence_text or not names_norm: return None if not any(n in normalize_compact(evidence_text) for n in names_norm if len(n)>=3): return None false_words=["label","labelling","labeling","표시","라벨","알레르겐","allergen","warning","경고","ppm","불순물","impurity","시험법","test method","purity","analysis","검사","시험"] true_words=["maximum concentration","maximum amount","max concentration","max.","limit","restricted","restriction","배합한도","배합 한도","최대","이하","한도","제한"] chunks=re.split(r"[\n\r。.;;]+",evidence_text) for idx,_ in enumerate(chunks): near=" ".join(chunks[max(0,idx-1):min(len(chunks),idx+2)]) if not any(n in normalize_compact(near) for n in names_norm if len(n)>=3): continue low=near.lower() if any(w in low or w in near for w in false_words): continue if not any(w in low or w in near for w in true_words): continue percents=re.findall(r"([0-9]+(?:\.[0-9]+)?)\s*%",near) if percents: return {"limit_text":f"배합한도: {percents[0]}%","evidence":near[:500]} return None def validate_limit_result_against_evidence(result_obj,evidence_text,component): result_obj=result_obj or {}; combined=safe_str(result_obj.get("결과",""))+" "+safe_str(result_obj.get("표시문구","")) if not any(k in combined for k in ["배합한도","배합 한도","한도","최대","maximum","limit","%"]): return result_obj if any(k in combined for k in ["배합금지","사용금지","금지","prohibited","banned"]): return result_obj if "기능성 확인" in combined or "라벨링 필수" in combined: return result_obj verified=extract_verified_limit_from_evidence(evidence_text,[component.get("INCI Name",""),component.get("한글 성분명",""),component.get("CAS.No","")]) if verified is None: result_obj["결과"]="확인 필요 / 배합한도 수치 근거 재확인 필요"; result_obj["표시문구"]=NEED_CHECK_TEXT note=safe_str(result_obj.get("비고","")); extra="배합한도 수치가 검색 원문에서 성분명과 함께 검증되지 않아 자동 한도 표시 차단" result_obj["비고"]=(note+" / "+extra) if note and note!="-" else extra return result_obj result_obj["표시문구"]=verified["limit_text"] note=safe_str(result_obj.get("비고","")); ev="검증 근거: "+verified["evidence"] result_obj["비고"]=(note+" / "+ev) if note and note!="-" else ev return result_obj def normalize_formula_country_text(text,country_col="",inci_name="",amount_text=""): text=safe_str(text); lower=text.lower(); inci_norm=normalize_compact(inci_name) if not text or text=="-" or text==NO_EVIDENCE_TEXT: return "Pass" if any(k in text for k in ["배합금지","사용금지","금지"]) or any(k in lower for k in ["prohibited","banned","not allowed"]): return "배합금지" 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 "기능성" in text: return "기능성 확인" if "함량 정보 없음" in text or "함량 확인" in text: return "함량 확인" 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 in ["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 in ["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: return "배합한도: 3%" if country_col=="FDA" else "배합한도: 5%" if any(k in text for k in ["초과","부적합","사용 불가","사용불가"]): return "한도 초과" if "표시 필요" in text or "라벨" in text or "label" in lower: return "라벨링 필수" m=re.search(r"(?:배합\s*한도|배합한도|한도|max|maximum|limit|최대|이하|이내)\s*[::]?\s*([0-9]+(?:\.[0-9]+)?\s*%)",text,flags=re.I) if m: return "배합한도: "+m.group(1).replace(" ","") if any(k in text for k in ["배합한도","배합 한도","한도","제한"]) or any(k in lower for k in ["maximum","limit","restricted"]): return LIMIT_CHECK_TEXT return text[:120] def standardize_formula_dataframe(df): """ 엑셀/PDF/이미지 추출 결과에서 실제 전성분 헤더가 중간에 있는 경우를 보정한다. 방지하는 문제: - PRODUCT NAME 행이 성분처럼 들어감 - 'INGREDIENT NAME', 'NO.', 'FUNCTION' 같은 반복 헤더가 성분처럼 들어감 - 실제 표 시작 전 제목/공백/메타 영역이 결과에 섞임 """ if df is None or df.empty: return df work = df.copy() work = work.dropna(how="all").reset_index(drop=True) if work.empty: return work # 1) 실제 헤더 행 탐지 best_idx = None best_score = -1 for idx, row in work.iterrows(): row_text = " ".join(safe_str(v) for v in row.values if safe_str(v)) low = row_text.lower() compact = normalize_compact(row_text) score = 0 if "no" in low or "번호" in low or "순번" in low: score += 1 if "한글" in low and ("표준" in low or "성분" in low): score += 2 if "ingredient" in low or "inci" in low or "ingredientnameinci" in compact: score += 4 if "function" in low or "기능" in low: score += 2 if "cas" in low: score += 2 if "source" in low or "출처" in low: score += 2 if "w/w" in low or "%(w/w)" in low or "함량" in low: score += 2 if score > best_score: best_score = score best_idx = idx # 2) 실제 헤더가 중간에 있으면 그 행을 컬럼으로 승격 if best_idx is not None and best_score >= 5: header = [] for i, v in enumerate(work.iloc[best_idx].tolist()): h = safe_str(v) header.append(h if h else f"Unnamed_{i}") body = work.iloc[best_idx + 1:].copy().reset_index(drop=True) body.columns = header work = body # 3) 컬럼명 중복 방지 seen = {} new_cols = [] for col in work.columns: c = safe_str(col) or "Unnamed" if c in seen: seen[c] += 1 c = f"{c}_{seen[c]}" else: seen[c] = 0 new_cols.append(c) work.columns = new_cols # 4) 제품명/제목/반복 헤더/빈 행 제거 drop_indices = [] for idx, row in work.iterrows(): vals = [safe_str(v) for v in row.values] row_text = " ".join(v for v in vals if v) low = row_text.lower() compact = normalize_compact(row_text) if not compact: drop_indices.append(idx) continue if "productname" in compact: drop_indices.append(idx) continue if "formularingredientsstatement" in compact or "formulaingredientsstatement" in compact: drop_indices.append(idx) continue if "ingredientnameinci" in compact or ("ingredient name" in low and ("function" in low or "cas" in low or "source" in low)): drop_indices.append(idx) continue # 'INGREDIENT NAME / NO. / FUNCTION / CAS.No / SOURCE' 같은 표 내부 반복 헤더 제거 header_like_count = 0 for v in vals: vn = normalize_compact(v) if vn in [ "no", "no.", "번호", "순번", "한글표준화명칭", "한글성분명", "국문성분명", "ingredientname", "ingredientnameinci", "inci", "inciname", "function", "기능", "casno", "cas.no", "cas", "source", "출처", "ww", "%ww", "%(ww)", "%(w/w)", "함량", ]: header_like_count += 1 if header_like_count >= 3: drop_indices.append(idx) continue if drop_indices: work = work.drop(index=drop_indices).reset_index(drop=True) return work # input extraction STANDARD_INPUT_COLUMNS=["NO.","한글 표준화 명칭","INGREDIENT NAME (INCI)","FUNCTION","CAS.No","SOURCE","%(w/w)"] def clean_json_text(text): text=safe_str(text); text=re.sub(r"^```json\s*","",text.strip(),flags=re.I); text=re.sub(r"^```\s*","",text.strip()); text=re.sub(r"\s*```$","",text.strip()) m=re.search(r"\[.*\]",text,flags=re.S) if m: return m.group(0) m=re.search(r"\{.*\}",text,flags=re.S) return m.group(0) if m else text def rows_json_to_dataframe(rows): if isinstance(rows,dict): rows=rows.get("rows",[]) clean=[] if not isinstance(rows,list): return pd.DataFrame(columns=STANDARD_INPUT_COLUMNS) for i,row in enumerate(rows,1): if not isinstance(row,dict): continue d={"NO.":safe_str(row.get("NO.",row.get("NO",row.get("번호",i)))),"한글 표준화 명칭":safe_str(row.get("한글 표준화 명칭",row.get("한글 성분명",row.get("Korean Name","")))),"INGREDIENT NAME (INCI)":safe_str(row.get("INGREDIENT NAME (INCI)",row.get("INCI Name",row.get("INCI",row.get("Ingredient Name",""))))),"FUNCTION":safe_str(row.get("FUNCTION",row.get("Function",row.get("기능","")))),"CAS.No":safe_str(row.get("CAS.No",row.get("CAS No",row.get("CAS","")))),"SOURCE":safe_str(row.get("SOURCE",row.get("Source",""))) or "ICID","%(w/w)":safe_str(row.get("%(w/w)",row.get("In formula(w/w %)",row.get("함량",row.get("%","")))))} if d["한글 표준화 명칭"] or d["INGREDIENT NAME (INCI)"]: clean.append(d) return pd.DataFrame(clean,columns=STANDARD_INPUT_COLUMNS) def extract_formula_rows_from_text_with_llm(text): client=get_openai_client() prompt=f"""너는 화장품 전성분표 데이터 추출기다. 아래 텍스트에서 전성분 표만 JSON 배열로 반환해. 설명문 없이 JSON만 출력. 없는 값은 빈 문자열. TOTAL/합계/footer/주소/서명 제외. 컬럼: NO., 한글 표준화 명칭, INGREDIENT NAME (INCI), FUNCTION, CAS.No, SOURCE, %(w/w)\n\n원문:\n{text[:20000]}""" r=client.chat.completions.create(model="gpt-4o-mini",temperature=0,messages=[{"role":"system","content":"Return strict JSON only."},{"role":"user","content":prompt}]) return rows_json_to_dataframe(json.loads(clean_json_text(r.choices[0].message.content))) def image_file_to_data_url(path): ext=os.path.splitext(path)[1].lower().replace(".",""); ext="jpeg" if ext=="jpg" else ext with open(path,"rb") as f: enc=base64.b64encode(f.read()).decode() return f"data:image/{ext};base64,{enc}" def extract_formula_table_from_image(path): client=get_openai_client(); data_url=image_file_to_data_url(path) prompt="""이미지 안의 화장품 전성분표를 JSON 배열로 반환해. 설명문 없이 JSON만 출력. 원문에 없는 성분 만들지 말 것. TOTAL/합계/footer 제외. 컬럼: NO., 한글 표준화 명칭, INGREDIENT NAME (INCI), FUNCTION, CAS.No, SOURCE, %(w/w)""" r=client.chat.completions.create(model="gpt-4o-mini",temperature=0,messages=[{"role":"system","content":"Return strict JSON only."},{"role":"user","content":[{"type":"text","text":prompt},{"type":"image_url","image_url":{"url":data_url}}]}]) return rows_json_to_dataframe(json.loads(clean_json_text(r.choices[0].message.content))) def extract_text_from_pdf_for_input(path): texts=[] with pdfplumber.open(path) as pdf: for pno,p in enumerate(pdf.pages,1): txt=p.extract_text() or "" if txt: texts.append(f"[PAGE {pno}]\n{txt}") try: for table in p.extract_tables() or []: texts.append("\n".join(["\t".join(safe_str(x) for x in row) for row in table])) except Exception: pass return "\n\n".join(texts) def render_pdf_first_pages_to_images(pdf_path,max_pages=3): paths=[] if fitz is None: return paths doc=fitz.open(pdf_path) for i in range(min(len(doc),max_pages)): pix=doc[i].get_pixmap(matrix=fitz.Matrix(2,2),alpha=False) out=OUTPUT_DIR/f"pdf_page_extract_{safe_filename(Path(pdf_path).stem)}_{i+1}.png"; pix.save(str(out)); paths.append(str(out)) doc.close(); return paths def extract_formula_table_from_pdf(path): text=extract_text_from_pdf_for_input(path) if len(normalize_compact(text))>200: try: df=extract_formula_rows_from_text_with_llm(text) if not df.empty: return df except Exception as e: print("PDF text extraction by GPT failed:",e) dfs=[] for img in render_pdf_first_pages_to_images(path): try: df=extract_formula_table_from_image(img) if not df.empty: dfs.append(df) except Exception as e: print("PDF image extraction failed:",e) if dfs: return pd.concat(dfs,ignore_index=True).drop_duplicates(subset=["한글 표준화 명칭","INGREDIENT NAME (INCI)","CAS.No","%(w/w)"]).reset_index(drop=True) raise ValueError("PDF에서 전성분표를 추출하지 못했습니다.") def load_input_file_to_dataframe(file): if not file: raise ValueError("파일이 없습니다.") path = file.name ext = os.path.splitext(path)[1].lower() if ext not in SUPPORTED_INPUT_EXTENSIONS: raise ValueError("지원하지 않는 파일 형식입니다. xlsx, xls, pdf, png, jpg, jpeg, webp만 지원합니다.") if ext in [".xlsx", ".xls"]: # 중요: # header=None으로 읽어야 실제 헤더가 중간에 있는 양식에서 # PRODUCT NAME/상단 메타 행이 성분으로 들어가지 않는다. raw = pd.read_excel(path, header=None, dtype=str) return standardize_formula_dataframe(raw) if ext == ".pdf": return standardize_formula_dataframe(extract_formula_table_from_pdf(path)) return standardize_formula_dataframe(extract_formula_table_from_image(path)) def preview_input_file(file): try: return load_input_file_to_dataframe(file) if file else None except Exception as e: return pd.DataFrame({"오류":[str(e)]}) BROAD_LOOKUP_TERMS = { "acid", "acids", "alcohol", "alcohols", "glycol", "glycols", "oil", "oils", "extract", "extracts", "water", "aqua", "powder", "solution", "agent", "sodium", "potassium", "calcium", "magnesium", "zinc", "ammonium", "skin", "conditioning", "cosmetic", "quality", "system", "stem", "flower", "leaf", "root", "fruit", "seed", "peel", "애씨드", "알코올", "글라이콜", "오일", "추출물", "정제수", "수", "물", } def is_broad_lookup_term(term): norm = normalize_compact(term) text = normalize_text(term) if not norm or len(norm) < 4: return True if norm in {normalize_compact(x) for x in BROAD_LOOKUP_TERMS}: return True if text in BROAD_LOOKUP_TERMS: return True return False # ============================================================ # 규제 동의어 / CAS / 이성질체 레지스트리 # - 국가별 파일 표기가 INCI와 다를 때 PASS 오판을 막기 위한 보정층 # - 단일 성분과 전성분 모두 동일하게 사용 # ============================================================ REGULATORY_SYNONYM_REGISTRY = [ { "key": "edta_and_salts", "canonical": "EDTA and salts", "terms": [ "edta", "EDTA", "edta and salts", "edta salts", "edta and derivatives", "ethylenediaminetetraacetic acid", "ethylenediamine tetraacetic acid", "edetic acid", "edetate", "edetates", "disodium edta", "Disodium EDTA", "trisodium edta", "Trisodium EDTA", "tetrasodium edta", "Tetrasodium EDTA", "calcium disodium edta", "Calcium Disodium EDTA", "dipotassium edta", "Dipotassium EDTA", "diammonium edta", "Diammonium EDTA", "disodium edetate", "Disodium Edetate", "tetrasodium edetate", "Tetrasodium Edetate", "디소듐이디티에이", "다이소듐이디티에이", "디소듐 이디티에이", "다이소듐 이디티에이", "테트라소듐이디티에이", "테트라소듐 이디티에이", "트리소듐이디티에이", "트리소듐 이디티에이", "칼슘디소듐이디티에이", "칼슘 디소듐 이디티에이", "디포타슘이디티에이", "디포타슘 이디티에이", "에데트산", "에데테이트", "이디티에이", "이디티에이염", "EDTA염", ], }, { "key": "dichlorobenzene", "canonical": "Dichlorobenzene", "terms": [ "dichlorobenzene", "dichlorobenzenes", "Dichlorobenzene", "Dichlorobenzenes", "106-46-7", "95-50-1", "541-73-1", "1,2-dichlorobenzene", "1,3-dichlorobenzene", "1,4-dichlorobenzene", "o-dichlorobenzene", "m-dichlorobenzene", "p-dichlorobenzene", "ortho-dichlorobenzene", "meta-dichlorobenzene", "para-dichlorobenzene", "1,2-Dichlorobenzene", "1,3-Dichlorobenzene", "1,4-Dichlorobenzene", "o-Dichlorobenzene", "m-Dichlorobenzene", "p-Dichlorobenzene", "1,2-디클로로벤젠", "1,3-디클로로벤젠", "1,4-디클로로벤젠", "o-디클로로벤젠", "m-디클로로벤젠", "p-디클로로벤젠", "디클로로벤젠", "다이클로로벤젠", ], }, { "key": "trichlorobenzene", "canonical": "Trichlorobenzene", "terms": [ "trichlorobenzene", "trichlorobenzenes", "Trichlorobenzene", "Trichlorobenzenes", "120-82-1", "87-61-6", "108-70-3", "1,2,3-trichlorobenzene", "1,2,4-trichlorobenzene", "1,3,5-trichlorobenzene", "1,2,3-Trichlorobenzene", "1,2,4-Trichlorobenzene", "1,3,5-Trichlorobenzene", "1,2,3-트리클로로벤젠", "1,2,4-트리클로로벤젠", "1,3,5-트리클로로벤젠", "트리클로로벤젠", ], }, { "key": "tetrachlorobenzene", "canonical": "Tetrachlorobenzene", "terms": [ "tetrachlorobenzene", "tetrachlorobenzenes", "Tetrachlorobenzene", "Tetrachlorobenzenes", "634-66-2", "634-90-2", "95-94-3", "1,2,3,4-tetrachlorobenzene", "1,2,3,5-tetrachlorobenzene", "1,2,4,5-tetrachlorobenzene", "1,2,3,4-Tetrachlorobenzene", "1,2,3,5-Tetrachlorobenzene", "1,2,4,5-Tetrachlorobenzene", "1,2,3,4-테트라클로로벤젠", "1,2,3,5-테트라클로로벤젠", "1,2,4,5-테트라클로로벤젠", "테트라클로로벤젠", ], }, ] def registry_terms_for_component(material=None, component=None, extra_terms=None): material = material or {} component = component or {} identity_values = [ component.get("INCI Name", ""), component.get("한글 성분명", ""), component.get("CAS.No", ""), material.get("Trade name(국문)", ""), material.get("Trade name(영문)", ""), ] + list(extra_terms or []) identity_norm = normalize_compact(" ".join(safe_str(x) for x in identity_values if safe_str(x))) hits = [] for entry in REGULATORY_SYNONYM_REGISTRY: terms = entry.get("terms", []) term_norms = [normalize_compact(t) for t in terms if safe_str(t)] if any(tn and tn in identity_norm for tn in term_norms): for t in terms: if safe_str(t) and t not in hits: hits.append(safe_str(t)) return hits def registry_direct_regulation_fallback(country, material, component, target_id=""): """ 일반 검색/화학명 alias 검색이 실패했을 때, registry의 CAS/동의어/이성질체명으로 국가 파일 원문을 다시 검색한다. """ registry_terms = registry_terms_for_component(material=material, component=component) if not registry_terms: return None sections, status = get_country_section_index_cached(country) country_col = display_country(country) representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or registry_terms[0] registry_norms = [ normalize_compact(t) for t in registry_terms if safe_str(t) and len(normalize_compact(t)) >= 3 ] for section in sections: text = safe_str(section.get("text", "")) text_norm = normalize_compact(text) if not any(tn in text_norm for tn in registry_norms): continue header = safe_str(section.get("header", "")) reg_type = infer_regulation_type_from_source_text(header + "\n" + text[:2000], country=country) reg_kind = reg_type.get("type", "unknown") reg_label = reg_type.get("label", "규제 유형 미분류") lines = [safe_str(x) for x in text.splitlines() if safe_str(x)] context_lines = [] seen = set() for idx, line in enumerate(lines): ln = normalize_compact(line) if any(tn in ln for tn in registry_norms): for j in range(max(0, idx - 5), min(len(lines), idx + 6)): if j not in seen: seen.add(j) context_lines.append(lines[j]) context = (header + "\n" + "\n".join(context_lines))[:5000] low = context.lower() prohibited_signal = ( reg_kind == "prohibited" or any(k in context for k in ["배합금지", "사용금지", "사용 금지", "금지원료", "금지 원료", "금지성분", "금지 성분", "구분 금지", "구분: 금지"]) or any(k in low for k in ["prohibited", "banned", "not allowed", "shall not be used", "must not be used", "forbidden"]) ) restricted_signal = ( reg_kind == "restricted" or any(k in context for k in ["배합한도", "사용제한", "사용 제한", "제한성분", "제한 성분", "구분 제한", "구분: 제한"]) or any(k in low for k in ["restricted", "restriction", "maximum", "limit"]) ) if prohibited_signal: result = { "대표 INCI": representative, "결과": f"{country_col} {reg_label}에서 동의어/CAS/이성질체 근거 확인", "표시문구": "배합금지", "비고": context[:1000], } log_search_context(target_id, country, component, result["결과"], "REGISTRY_SYNONYM_PROHIBITED", context) return result if restricted_signal: limit_text, condition_text = extract_limit_condition_from_context(context) result = { "대표 INCI": representative, "결과": f"{country_col} {reg_label}에서 동의어/CAS/이성질체 제한 근거 확인" + (f" / 조건: {condition_text}" if condition_text else ""), "표시문구": f"배합한도: {limit_text}" if limit_text else NEED_CHECK_TEXT, "비고": context[:1000], } log_search_context(target_id, country, component, result["결과"], "REGISTRY_SYNONYM_RESTRICTED", context) return result return None def build_chemical_name_variants(term): """ 화학명 표기 차이 보정용 alias 생성. 이성질체/복수형/국문 음역 표기를 생성한다. """ term = safe_str(term) if not term: return [] variants = [] compact = normalize_compact(term) def add(x): x = safe_str(x) if x and x not in variants: variants.append(x) add(term) low = term.lower() if low.endswith("benzene") and not low.endswith("benzenes"): add(term + "s") if low.endswith("benzenes"): add(term[:-1]) replacements = [ ("Dichloro", "디클로로"), ("dichloro", "디클로로"), ("Trichloro", "트리클로로"), ("trichloro", "트리클로로"), ("Tetrachloro", "테트라클로로"), ("tetrachloro", "테트라클로로"), ("Chloro", "클로로"), ("chloro", "클로로"), ("Dibromo", "디브로모"), ("dibromo", "디브로모"), ("Bromo", "브로모"), ("bromo", "브로모"), ("Difluoro", "디플루오로"), ("difluoro", "디플루오로"), ("Fluoro", "플루오로"), ("fluoro", "플루오로"), ("Iodo", "아이오도"), ("iodo", "아이오도"), ("Benzene", "벤젠"), ("benzene", "벤젠"), ("Toluene", "톨루엔"), ("toluene", "톨루엔"), ("Phenol", "페놀"), ("phenol", "페놀"), ] translit = term for a, b in replacements: translit = translit.replace(a, b) if translit != term: add(translit) add(translit.replace(" ", "")) benzene_patterns = [ ("dichlorobenzene", "Dichlorobenzene", "디클로로벤젠"), ("trichlorobenzene", "Trichlorobenzene", "트리클로로벤젠"), ("tetrachlorobenzene", "Tetrachlorobenzene", "테트라클로로벤젠"), ("chlorobenzene", "Chlorobenzene", "클로로벤젠"), ("dibromobenzene", "Dibromobenzene", "디브로모벤젠"), ("bromobenzene", "Bromobenzene", "브로모벤젠"), ("difluorobenzene", "Difluorobenzene", "디플루오로벤젠"), ("fluorobenzene", "Fluorobenzene", "플루오로벤젠"), ("iodobenzene", "Iodobenzene", "아이오도벤젠"), ] for key, en, ko in benzene_patterns: if key in compact: add(en) add(en + "s") add(ko) add(ko + "류") for pos in ["1,2", "1,3", "1,4", "1,2-", "1,3-", "1,4-", "o", "m", "p", "ortho", "meta", "para"]: pos_clean = pos.rstrip("-") add(f"{pos_clean}-{en}") add(f"{pos_clean} {en}") add(f"{pos_clean}-{ko}") add(f"{pos_clean} {ko}") add(f"1,4-{ko}(p-{ko})") add(f"1,4-{en} (p-{en})") add(f"p-{ko}") add(f"p-{en}") return variants def find_chemical_variant_match_in_country_text(country, material, component, target_id=""): """ 국가별 섹션 인덱스 매칭이 실패한 경우를 위한 화학명 변형 fallback. 전체 국가 파일 원문에서 화학명 변형 alias를 직접 찾고, 그 섹션/문맥이 금지 또는 제한 파일이면 판정한다. """ lookup_terms = build_ingredient_lookup_terms( material=material, component=component, extra_terms=[ component.get("INCI Name", ""), component.get("한글 성분명", ""), component.get("CAS.No", ""), ], ) expanded = [] for t in lookup_terms: for v in build_chemical_name_variants(t): if safe_str(v) and v not in expanded: expanded.append(v) # 너무 일반적인 alias 제거 expanded = [ x for x in expanded if len(normalize_compact(x)) >= 4 and not is_broad_lookup_term(x) ] if not expanded: return None sections, status = get_country_section_index_cached(country) country_col = display_country(country) representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or "-" for section in sections: text = safe_str(section.get("text", "")) text_norm = normalize_compact(text) header = safe_str(section.get("header", "")) reg_type = infer_regulation_type_from_source_text(header + "\n" + text[:1500], country=country) reg_kind = reg_type.get("type", "unknown") reg_label = reg_type.get("label", "규제 유형 미분류") hit_terms = [v for v in expanded if normalize_compact(v) in text_norm] if not hit_terms: continue lines = [safe_str(x) for x in text.splitlines() if safe_str(x)] context_lines = [] seen = set() for idx, line in enumerate(lines): line_norm = normalize_compact(line) if any(normalize_compact(v) in line_norm for v in hit_terms): for j in range(max(0, idx - 4), min(len(lines), idx + 5)): if j not in seen: seen.add(j) context_lines.append(lines[j]) context = (header + "\n" + "\n".join(context_lines))[:5000] context_low = context.lower() prohibited_signal = ( reg_kind == "prohibited" or any(k in context for k in ["배합금지", "사용금지", "사용 금지", "금지원료", "금지 성분", "금지성분"]) or any(k in context_low for k in ["prohibited", "banned", "not allowed", "shall not be used", "must not be used"]) ) restricted_signal = ( reg_kind == "restricted" or any(k in context for k in ["사용제한", "사용 제한", "배합한도", "제한성분", "제한 성분"]) or any(k in context_low for k in ["restricted", "restriction", "maximum", "limit"]) ) if prohibited_signal: result = { "대표 INCI": representative, "결과": f"{country_col} {reg_label}에서 화학명 변형 alias 확인", "표시문구": "배합금지", "비고": context[:1000], } log_search_context(target_id, country, component, result["결과"], "COUNTRY_FILE_CHEMICAL_ALIAS_PROHIBITED", context) return result if restricted_signal: limit_text, condition_text = extract_limit_condition_from_context(context) display = f"배합한도: {limit_text}" if limit_text else NEED_CHECK_TEXT result = { "대표 INCI": representative, "결과": f"{country_col} {reg_label}에서 화학명 변형 alias 확인" + (f" / 조건: {condition_text}" if condition_text else ""), "표시문구": display, "비고": context[:1000], } log_search_context(target_id, country, component, result["결과"], "COUNTRY_FILE_CHEMICAL_ALIAS_RESTRICTED", context) return result return None def build_ingredient_lookup_terms(material=None, component=None, extra_terms=None): material = material or {} component = component or {} raw_terms = [] for v in [ component.get("INCI Name", ""), component.get("한글 성분명", ""), component.get("CAS.No", ""), material.get("Trade name(국문)", ""), material.get("Trade name(영문)", ""), ]: if safe_str(v): raw_terms.append(safe_str(v)) for v in extra_terms or []: if safe_str(v): raw_terms.append(safe_str(v)) for reg_term in registry_terms_for_component(material=material, component=component, extra_terms=extra_terms): if safe_str(reg_term): raw_terms.append(safe_str(reg_term)) expanded = [] strong_abbrev_allowlist = {"EDTA", "EDETATE", "BHT", "BHA", "MEA", "DEA", "TEA", "D4", "D5", "D6", "PFAS", "PFOA", "PFOS"} salt_prefixes = [ "calcium disodium", "disodium", "trisodium", "tetrasodium", "sodium", "dipotassium", "tripotassium", "tetrapotassium", "potassium", "calcium", "magnesium", "zinc", "ammonium", ] def add(term, allow_broad=False): term = safe_str(term) if not term: return if len(normalize_compact(term)) < 3: return if not allow_broad and is_broad_lookup_term(term): return if term not in expanded: expanded.append(term) for term in raw_terms: t = safe_str(term) for variant in build_chemical_name_variants(t): add(variant, allow_broad=False) add(t) add(t.replace("-", " ")) add(t.replace("/", " ")) for p in re.findall(r"\(([^)]+)\)", t): p = safe_str(p) if p.upper() in strong_abbrev_allowlist or len(normalize_compact(p)) >= 5: add(p, allow_broad=(p.upper() in strong_abbrev_allowlist)) for abbr in re.findall(r"\b[A-Z][A-Z0-9]{2,}\b", t): if abbr.upper() in strong_abbrev_allowlist: add(abbr, allow_broad=True) low = t.lower().strip() for prefix in salt_prefixes: if low.startswith(prefix + " "): base = t[len(prefix):].strip(" -_/") # Disodium EDTA -> EDTA는 허용, Sodium Benzoate -> Benzoate도 허용 # 하지만 Butylene Glycol -> Glycol처럼 broad term만 남기는 확장은 하지 않음 add(base, allow_broad=(base.upper() in strong_abbrev_allowlist)) tokens = re.split(r"[\s\-/]+", t) for i in range(1, min(4, len(tokens))): base = " ".join(tokens[i:]).strip() if base.upper() in strong_abbrev_allowlist: add(base, allow_broad=True) seen = set() final_terms = [] for term in expanded: norm = normalize_compact(term) if norm in seen: continue seen.add(norm) final_terms.append(term) return sorted(final_terms, key=lambda x: len(normalize_compact(x)), reverse=True) def context_has_group_regulation_for_terms(context, lookup_terms): text = safe_str(context) compact = normalize_compact(text) low = text.lower() if not text or not lookup_terms: return False group_words = [ "derivative", "derivatives", "salts", "salt", "esters", "ester", "and its salts", "and their salts", "and derivatives", "and its derivatives", "및유도체", "유도체", "염류", "그염", "그 유도체", ] if not any(normalize_compact(w) in compact or w in low for w in group_words): return False for term in lookup_terms: if is_broad_lookup_term(term): continue norm = normalize_compact(term) if len(norm) >= 4 and norm in compact: return True return False def validate_country_file_match_context(context, component, lookup_terms): text = safe_str(context) compact = normalize_compact(text) if not text: return False for term in [component.get("INCI Name", ""), component.get("한글 성분명", ""), component.get("CAS.No", "")]: norm = normalize_compact(term) if len(norm) >= 4 and norm in compact: return True for term in lookup_terms or []: if is_broad_lookup_term(term): continue norm = normalize_compact(term) if len(norm) >= 4 and norm in compact: return True # 4) 화학명 자동 변형 alias가 문맥에 있으면 인정 for term in [ component.get("INCI Name", ""), component.get("한글 성분명", ""), component.get("CAS.No", ""), ]: for variant in build_chemical_name_variants(term): norm = normalize_compact(variant) if len(norm) >= 4 and norm in compact: return True # 화학명 변형 alias fallback for term in [ component.get("INCI Name", ""), component.get("한글 성분명", ""), component.get("CAS.No", ""), ]: for variant in build_chemical_name_variants(term): norm = normalize_compact(variant) if len(norm) >= 4 and norm in compact: return True if context_has_group_regulation_for_terms(context, lookup_terms): return True return False # country db def resolve_country_folder(country): raw=safe_str(country); alias=COUNTRY_FOLDER_ALIASES.get(raw,COUNTRY_FOLDER_ALIASES.get(raw.upper(),raw)) for c in [raw,alias,raw.upper(),alias.upper(),raw.replace("_"," "),alias.replace("_"," ")]: if c and os.path.isdir(c): return c fmap={f.lower():f for f in os.listdir(".") if os.path.isdir(f)} return fmap.get(alias.lower(),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(); kept=[v for v in (current_values or []) 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(); REG_TEXT_CACHE.clear(); REG_SECTION_INDEX_CACHE.clear(); return refresh_country_choices_keep_selection(current_values) def get_regulatory_file_list(folder): files=[] if not folder or not os.path.isdir(folder): return files for root,dirs,names in os.walk(folder): dirs[:]=[d for d in dirs if not d.startswith(".")] for name in names: ext=os.path.splitext(name)[1].lower() if ext not in SUPPORTED_REG_FILE_EXTENSIONS: continue p=os.path.join(root,name); st=os.stat(p) files.append({"path":p,"relative_path":os.path.relpath(p,folder),"size":st.st_size,"mtime_ns":st.st_mtime_ns,"ext":ext}) return sorted(files,key=lambda x:x["relative_path"].lower()) def read_text_file_with_fallback(p): for enc in ["utf-8","utf-8-sig","cp949","euc-kr","latin-1"]: try: with open(p,"r",encoding=enc) as f: return f.read() except Exception: pass return "" def extract_text_from_regulatory_file(item): p=item["path"]; rel=item["relative_path"]; ext=item["ext"]; texts=[] try: if ext==".pdf": with pdfplumber.open(p) as pdf: for i,page in enumerate(pdf.pages,1): t=page.extract_text() if t: texts.append(f"[파일: {rel}] [페이지: {i}]\n{t}") elif ext==".txt": texts.append(f"[파일: {rel}]\n{read_text_file_with_fallback(p)}") elif ext==".csv": try: df=pd.read_csv(p,dtype=str) except UnicodeDecodeError: df=pd.read_csv(p,dtype=str,encoding="cp949") texts.append(f"[파일: {rel}]\n{df.fillna('').to_string(index=False)}") elif ext in [".xlsx",".xls"]: for s,df in pd.read_excel(p,sheet_name=None,dtype=str).items(): texts.append(f"[파일: {rel}] [시트: {s}]\n{df.fillna('').to_string(index=False)}") except Exception as e: print("규제 파일 읽기 오류:",p,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 sig=stable_hash(tuple((f["relative_path"],f["size"],f["mtime_ns"]) for f in files)) cached=VECTOR_DB_CACHE.get(folder) if isinstance(cached,dict) and cached.get("signature_hash")==sig: return cached.get("db") emb=get_embeddings(); os.makedirs(FAISS_CACHE_DIR,exist_ok=True) cache_path=os.path.join(FAISS_CACHE_DIR,f"{safe_filename(folder)}_{sig[:16]}"); meta_path=os.path.join(cache_path,"metadata.json") if os.path.isdir(cache_path) and os.path.exists(meta_path): try: if json.load(open(meta_path,encoding="utf-8")).get("signature_hash")==sig: db=FAISS.load_local(cache_path,emb,allow_dangerous_deserialization=True); VECTOR_DB_CACHE[folder]={"signature_hash":sig,"db":db}; return db except Exception: pass chunks=[]; splitter=RecursiveCharacterTextSplitter(chunk_size=900,chunk_overlap=120) 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,emb) try: os.makedirs(cache_path,exist_ok=True); db.save_local(cache_path); json.dump({"signature_hash":sig},open(meta_path,"w",encoding="utf-8"),ensure_ascii=False) except Exception: pass VECTOR_DB_CACHE[folder]={"signature_hash":sig,"db":db}; return db def get_current_db_signature(country): c=VECTOR_DB_CACHE.get(resolve_country_folder(country)); return c.get("signature_hash") if isinstance(c,dict) else None # input columns 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(); sample=" ".join(df[col].dropna().astype(str).head(80)).lower(); score=0 for kw in keywords: if kw.lower() in header: score+=30 if any(x in sample for x in ["aqua","water","glycerin","octocrylene","homosalate","niacinamide","tranexamic"]): score+=5 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] return df.columns[default_index] if default_index is not None and len(df.columns)>default_index else df.columns[0] def find_optional_col(df,keywords,exclude_cols=None): exclude_cols=exclude_cols or []; best=None; score_best=0 for col in df.columns: if col in exclude_cols: continue score=sum(30 for kw in keywords if kw.lower() in str(col).lower()) if score>score_best: score_best=score; best=col return best def find_numeric_col(df,keywords,default_index=None,exclude_cols=None): exclude_cols=exclude_cols or []; cands=[] for idx,col in enumerate(df.columns): if col in exclude_cols: continue vals=df[col].dropna() if vals.empty: continue count=vals.apply(is_numeric_like).sum() if count<=0: continue score=sum(30 for kw in keywords if kw.lower() in str(col).lower()) cands.append((score,len(vals),idx,col)) if cands: return sorted(cands,reverse=True)[0][3] return df.columns[default_index] if default_index is not None and len(df.columns)>default_index else None def find_main_columns(df): no=find_best_col(df,["no","번호","순번"],0) ko=find_best_col(df,["한글 표준화 명칭","한글 성분명","국문 성분명","korean","성분명"],1 if len(df.columns)>1 else None,[no]) inci=find_best_col(df,["ingredient name (inci)","inci name","inci","ingredient","전성분","구성"],2 if len(df.columns)>2 else None,[no,ko]) func=find_best_col(df,["function","기능","용도"],3 if len(df.columns)>3 else None,[no,ko,inci]) cas=find_best_col(df,["cas.no","cas no","cas","cas번호"],4 if len(df.columns)>4 else None,[no,ko,inci,func]) src=find_best_col(df,["source","출처","icid"],5 if len(df.columns)>5 else None,[no,ko,inci,func,cas]) form=find_numeric_col(df,["%(w/w)","w/w","in formula","formula","처방","최종","배합량","함량","%"],6 if len(df.columns)>6 else None,[no,ko,inci,func,cas,src]) tko=find_optional_col(df,["trade name(국문)","원료명","상품명","국문"],[no,ko,inci,func,cas,src,form]) ten=find_optional_col(df,["trade name(영문)","trade","raw material","material","영문"],[no,ko,inci,func,cas,src,form,tko]) return {"no_col":no,"korean_ing_col":ko,"inci_col":inci,"function_col":func,"cas_col":cas,"source_col":src,"formula_col":form,"trade_ko_col":tko,"trade_en_col":ten} def clean_input_df(df,cols): keep=[]; footer=False for idx,row in df.iterrows(): vals=[safe_str(v) for v in row.values]; txt=" ".join(v for v in vals if v).strip(); low=txt.lower() if not txt: continue no=safe_str(row.get(cols["no_col"],"")).lower(); ko=safe_str(row.get(cols["korean_ing_col"],"")).lower(); inci=safe_str(row.get(cols["inci_col"],"")).lower() if no in ["no","no.","번호","순번"] or ko in ["한글 표준화 명칭","한글 성분명","국문 성분명"] or inci in ["ingredient name (inci)","ingredient name","inci","inci name"]: continue if "product name" in low or "productname" in normalize_compact(txt): continue if "formular ingredients statement" in low or "formula ingredients statement" in low: continue if "ingredient name" in low and ("function" in low or "cas" in low or "source" in low): continue if is_total_like_text(no) or is_total_like_text(ko) or is_total_like_text(inci) or row_has_total_like(vals): footer=True; continue if any(m in low for m in ["commitment of the manufacturer","rebom co","tel :","fax :","lab no."]): footer=True; continue if footer: continue keep.append(idx) return df.loc[keep].reset_index(drop=True) def make_grouped_materials(df): cols=find_main_columns(df); clean=clean_input_df(df,cols); mats=[] for _,row in clean.iterrows(): no=format_no(row.get(cols["no_col"],"")); ko=safe_str(row.get(cols["korean_ing_col"],"")); inci=safe_str(row.get(cols["inci_col"],"")) if not ko and not inci: continue if is_total_like_text(no) or is_total_like_text(ko) or is_total_like_text(inci): continue func=safe_str(row.get(cols["function_col"],"")); cas=safe_str(row.get(cols["cas_col"],"")); src=safe_str(row.get(cols["source_col"],"")) or "ICID" amount=format_amount(row.get(cols["formula_col"])) if cols["formula_col"] in row else "" comp={"한글 성분명":ko,"INCI Name":inci,"FUNCTION":func,"CAS.No":cas,"SOURCE":src,"In formula(w/w %)":amount,"amount_float":to_number(row.get(cols["formula_col"])) if cols["formula_col"] in row else None} mat={"NO":no,"Trade name(국문)":safe_str(row.get(cols.get("trade_ko_col"),"")) or ko,"Trade name(영문)":safe_str(row.get(cols.get("trade_en_col"),"")) or inci,"Components":[comp]} mats.append(mat) return mats,{"cols":cols,"cleaned_df":clean,"ingredient_totals":defaultdict(float),"ingredient_amount_parts":defaultdict(list)} # MFDS simplified: disabled-safe placeholder; keep UI compatibility def extract_terms_for_live_lookup(row_items, max_terms=5): """ MFDS 실시간 조회용 검색어 생성. 전체 스크리닝에서는 MFDS 실시간 조회를 끄는 것이 원칙이며, 혹시 켜져도 검색어가 폭증하지 않도록 최대 개수를 제한한다. """ terms=[] for item in row_items: m=item["material"]; c=item["component"] if is_plain_fragrance_component(m,c) or is_always_pass_component(m,c): continue for v in [c.get("INCI Name",""),c.get("한글 성분명",""),c.get("CAS.No","")]: if safe_str(v): terms.append(safe_str(v)) break seen=[] for t in terms: if t not in seen: seen.append(t) if max_terms and len(seen) >= int(max_terms): break return seen def mfds_visible_text(page): try: return page.locator("body").inner_text(timeout=5000) except Exception: try: return page.content() except Exception: return "" def mfds_fill_search_input(page, term): selectors = [ "input[type='search']", "input[type='text']", "input[placeholder*='검색']", "input[placeholder*='성분']", "input[placeholder*='원료']", "input[title*='검색']", "input:not([type])", ] for selector in selectors: try: loc = page.locator(selector) count = min(loc.count(), 40) for i in range(count): item = loc.nth(i) try: if item.is_visible(timeout=700) and item.is_enabled(timeout=700): item.fill(term, timeout=3000) return True except Exception: continue except Exception: continue return False def mfds_click_search(page): for text in ["검색", "조회", "Search"]: try: loc = page.get_by_text(text, 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", ".btn-search", ".btn_search", ".search", ] for selector in selectors: try: loc = page.locator(selector) count = min(loc.count(), 60) for i in range(count): 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 "조회" in text or "Search" in text or selector in [".btn-search", ".btn_search", ".search"]: item.click(timeout=3000) return True except Exception: continue except Exception: continue return False def mfds_click_probable_result(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) count = min(rows.count(), 80) for i in range(count): row = rows.nth(i) try: row_text = row.inner_text(timeout=1000) except Exception: continue row_norm = normalize_compact(row_text) if term_norm and term_norm in row_norm: row.click(timeout=3000) page.wait_for_timeout(1000) return True except Exception: continue return False def mfds_click_first_detail_result(page): """ 식약처 검색 결과에서 검색어와 결과명칭이 다를 수 있다. 예: Adenylthiomethyl Pentose 검색 -> 고시원료명 '비타민 L1, L2' 이 경우 term 포함 row 클릭 방식으로는 상세 진입이 안 되므로, getItem 링크 또는 첫 번째 결과 행을 클릭한다. """ try: links = page.locator("a[href*='getItem']") count = min(links.count(), 20) for i in range(count): link = links.nth(i) try: if link.is_visible(timeout=700): link.click(timeout=3000) page.wait_for_timeout(1000) return True except Exception: continue except Exception: pass selectors = [ "table tbody tr", "tbody tr", "tr", ".list li", ".result li", ".search-result li", ] for selector in selectors: try: rows = page.locator(selector) count = min(rows.count(), 50) for i in range(count): row = rows.nth(i) try: row_text = safe_str(row.inner_text(timeout=1000)) row_norm = normalize_compact(row_text) if not row_norm or len(row_norm) < 3: continue if all(w in row_text for w in ["구분", "국가"]) and "금지" not in row_text and "제한" not in row_text: continue if row.is_visible(timeout=700): row.click(timeout=3000) page.wait_for_timeout(1000) return True except Exception: continue except Exception: continue return False def country_aliases_for_mfds(country): c = country_key(country) alias_map = { "ASEAN": ["아세안", "ASEAN"], "EU": ["유럽", "EU", "유럽연합", "European Union", "Europe"], "US": ["미국", "USA", "US", "United States", "FDA"], "KOREA": ["한국", "대한민국", "Korea", "KOREA"], "JAPAN": ["일본", "Japan", "JAPAN"], "CHINA": ["중국", "China", "CHINA"], "UK": ["영국", "UK", "United Kingdom"], } return alias_map.get(c, [safe_str(country), display_country(country)]) def parse_mfds_detail_text(term, text): """ 식약처 상세 화면의 표시 텍스트에서 금지/제한 국가와 조건을 파싱한다. 검색어와 고시원료명이 달라도 상세 화면에 진입했다면 필드 기준으로 판정한다. """ clean = re.sub(r"\s+", " ", safe_str(text)).strip() if not clean: return [] rows = [] notice_name = "" m = re.search( r"고시원료명\s*([^\n\r]{0,260}?)(?:단서조항|제한사항|배합금지국가|배합제한국가|제한국가|배합목적|기준일자|$)", clean, ) if m: notice_name = m.group(1).strip(" :|-") country_candidates = [ ("ASEAN", ["아세안", "ASEAN"]), ("EU", ["유럽", "EU", "유럽연합"]), ("US", ["미국", "USA", "United States", "FDA"]), ("Korea", ["한국", "대한민국", "Korea"]), ("일본", ["일본", "Japan"]), ("중국", ["중국", "China"]), ("UK", ["영국", "UK", "United Kingdom"]), ] def region_after(labels, size=2400): for label in labels: m = re.search(label + r"(.{0," + str(size) + r"})", clean, flags=re.IGNORECASE) if m: return m.group(0) return "" prohibited_region = region_after([r"배합금지국가", r"금지국가"], 2000) restricted_region = region_after([r"배합제한국가", r"제한국가", r"제한사항", r"사용제한", r"배합한도"], 2600) is_prohibited_page = ( ("구분 금지" in clean) or ("구분: 금지" in clean) or bool(prohibited_region) ) is_restricted_page = ( ("구분 제한" in clean) or ("구분: 제한" in clean) or bool(restricted_region) or ("제한" in clean and ("%" in clean or "ppm" in clean or "한도" in clean or "제한사항" in clean)) ) if is_prohibited_page: region = prohibited_region or clean for display, aliases in country_candidates: in_region = any(alias in region for alias in aliases) in_clean_as_country = any((f"국가 {alias}" in clean or f"국가: {alias}" in clean) for alias in aliases) if in_region or in_clean_as_country: rows.append({ "검색어": term, "원료명": notice_name or term, "INCI": notice_name or term, "CAS.No": "", "구분": "금지", "국가": display, "규제내용": region[:1200], "한도": "", "조건": "", "출처": "MFDS live: " + MFDS_LIVE_URL, "상세원문": clean[:6000], }) if is_restricted_page: region = restricted_region or clean limit_text, condition_text = extract_limit_condition_from_context(region) for display, aliases in country_candidates: in_region = any(alias in region for alias in aliases) in_clean_as_country = any((f"국가 {alias}" in clean or f"국가: {alias}" in clean) for alias in aliases) if in_region or in_clean_as_country: rows.append({ "검색어": term, "원료명": notice_name or term, "INCI": notice_name or term, "CAS.No": "", "구분": "제한", "국가": display, "규제내용": region[:1200], "한도": limit_text, "조건": condition_text, "출처": "MFDS live: " + MFDS_LIVE_URL, "상세원문": clean[:6000], }) if not rows and is_restricted_page: limit_text, condition_text = extract_limit_condition_from_context(restricted_region or clean) rows.append({ "검색어": term, "원료명": notice_name or term, "INCI": notice_name or term, "CAS.No": "", "구분": "제한", "국가": "전체/국가 미분류", "규제내용": (restricted_region or clean)[:1200], "한도": limit_text, "조건": condition_text, "출처": "MFDS live: " + MFDS_LIVE_URL, "상세원문": clean[:6000], }) return rows def mfds_lookup_one_term_with_retry(page, term): """ 식약처 사이트가 중간에 ERR_CONNECTION_RESET / timeout을 내는 경우가 있어 검색어별로 재접속 + 재시도를 수행한다. 검색은 정상적으로 되었지만 상세 화면에서 '구분/배합금지국가/제한사항' 필드가 없으면 실패가 아니라 '식약처 규제 결과 없음'으로 처리한다. """ last_error = "" for attempt in range(1, MFDS_RETRY_COUNT + 2): try: page.goto(MFDS_LIVE_URL, wait_until="domcontentloaded", timeout=20000) page.wait_for_timeout(1200) if not mfds_fill_search_input(page, term): raise RuntimeError("검색 입력창 찾기 실패") if not mfds_click_search(page): try: page.keyboard.press("Enter") except Exception: pass page.wait_for_timeout(1800) clicked = mfds_click_probable_result(page, term) if not clicked: clicked = mfds_click_first_detail_result(page) page.wait_for_timeout(1600) detail_text = mfds_visible_text(page) rows = parse_mfds_detail_text(term, detail_text) if rows: return rows, "" body_text = safe_str(detail_text) body_norm = normalize_compact(body_text) term_norm = normalize_compact(term) no_result_phrases = [ "검색 결과가 없습니다", "조회된 데이터가 없습니다", "조회 결과가 없습니다", "데이터가 없습니다", "검색된 자료가 없습니다", "검색된 데이터가 없습니다", "결과가 없습니다", "No data", "No result", ] if any(p in body_text for p in no_result_phrases) or any(normalize_compact(p) in body_norm for p in no_result_phrases): return [], "" # 검색어가 화면에 있지만 규제 필드가 없으면 일반 원료 상세/무규제 결과로 판단 if term_norm and term_norm in body_norm: return [], "" if not clicked: return [], "" return [], "" except Exception as e: last_error = str(e) retryable = any( key in last_error for key in [ "ERR_CONNECTION_RESET", "ERR_TIMED_OUT", "Timeout", "timeout", "Target closed", "Navigation", "net::ERR", ] ) if attempt <= MFDS_RETRY_COUNT and retryable: try: page.wait_for_timeout(int(MFDS_RETRY_WAIT_SEC * 1000)) except Exception: time.sleep(MFDS_RETRY_WAIT_SEC) continue return [], last_error[:300] return [], last_error[:300] def mfds_launch_chromium(playwright_obj): """ Playwright Chromium 브라우저 실행 함수. 일부 병합 과정에서 누락되면 MFDS 조회 시 name error가 발생하므로 별도 함수로 보장한다. """ return playwright_obj.chromium.launch( headless=True, args=[ "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-gpu", "--disable-software-rasterizer", ], ) def mfds_try_install_chromium_once(): """ postBuild가 실행되지 않은 환경에서 Chromium이 없을 때 1회 설치를 시도한다. 실패하더라도 앱 전체는 죽지 않고 국가별 파일 검색 결과는 계속 표시한다. """ try: proc = subprocess.run( [sys.executable, "-m", "playwright", "install", "chromium"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=180, ) if proc.returncode == 0: return True, "Chromium 런타임 설치 완료" msg = (proc.stderr or proc.stdout or "").strip() return False, msg[:500] except Exception as e: return False, str(e) def mfds_live_lookup_terms(terms, max_terms=5, 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[:min(int(max_terms), 5)] if max_terms else terms[:5] all_rows = [] errors = [] install_note = "" try: with sync_playwright() as p: try: browser = mfds_launch_chromium(p) except Exception as launch_error: launch_text = str(launch_error) if "Executable doesn't exist" in launch_text or "playwright install" in launch_text: ok, install_msg = mfds_try_install_chromium_once() install_note = install_msg if ok: browser = mfds_launch_chromium(p) else: return pd.DataFrame(), ( "MFDS 브라우저 실행 실패: Chromium 미설치. " "Space의 postBuild 실행/Factory reboot가 필요합니다. " f"설치 시도 결과: {install_note}" ) else: return pd.DataFrame(), f"MFDS 브라우저 실행 실패: {launch_text[:500]}" context = browser.new_context( viewport={"width": 1280, "height": 900}, ignore_https_errors=True, user_agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36", ) page = context.new_page() for idx, term in enumerate(terms, start=1): rows, err = mfds_lookup_one_term_with_retry(page, term) if rows: all_rows.extend(rows) elif err: ignore_err_phrases = [ "식약처 상세 규제 필드 미검출", "식약처 검색 결과 없음", "규제 결과 없음", ] if not any(p in safe_str(err) for p in ignore_err_phrases): errors.append(f"{term}: {err}") # 식약처 사이트 과부하/차단 방지를 위해 검색어 사이에 대기 try: page.wait_for_timeout(int(MFDS_BETWEEN_TERMS_WAIT_SEC * 1000)) except Exception: time.sleep(MFDS_BETWEEN_TERMS_WAIT_SEC) context.close() browser.close() except Exception as e: return pd.DataFrame(), f"MFDS 브라우저 실행 실패: {str(e)[:500]}" df = pd.DataFrame(all_rows) msg = f"MFDS 실시간 조회 완료: 검색어 {len(terms)}개, 식약처 규제 매칭 {len(df)}행" if install_note: msg += f" / {install_note}" if errors: msg += " / 일부 실패: " + " ; ".join(errors[:4]) if len(errors) > 4: msg += f" 외 {len(errors) - 4}건" 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_text = " ".join([safe_str(x) for x in identity_values if safe_str(x)]) query = safe_str(row.get("검색어", "")) if query and len(normalize_compact(query)) >= 3 and exact_ingredient_match(query, identity_text): return True for term in [row.get("원료명", ""), row.get("INCI", ""), row.get("CAS.No", "")]: if term and len(normalize_compact(term)) >= 3 and exact_ingredient_match(term, identity_text): return True return False def live_row_country_matches(country, row_country): row_country = safe_str(row_country) if row_country in ["전체/국가 미분류", "전체", "국가 미분류"]: return True aliases = country_aliases_for_mfds(country) return any(alias and normalize_compact(alias) in normalize_compact(row_country) for alias in aliases) 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("구분", "")) regulation = safe_str(row.get("규제내용", "")) limit = safe_str(row.get("한도", "")) source = safe_str(row.get("출처", "MFDS live")) if "금지" in category: display = "배합금지" result_text = f"식약처 실시간 조회: {display_country(country)} 배합금지" elif limit: display = f"배합한도: {limit}" result_text = f"식약처 실시간 조회: {display_country(country)} 제한 / 한도 {limit}" else: display = "배합한도/제한 확인" result_text = f"식약처 실시간 조회: {display_country(country)} 제한 확인 / 한도·조건 확인 필요" if regulation: result_text += " / " + regulation[:300] return { "대표 INCI": safe_str(component.get("INCI Name", "")) or safe_str(row.get("원료명", "")) or "-", "결과": result_text, "표시문구": display, "비고": source, } def evaluate_critical_country_rule(country,material,component): ckey=country_key(country); identity=get_identity_raw(material,component) for r in CRITICAL_COUNTRY_RULES.values(): if any_exact_alias_match(r.get("aliases",[]), identity): cr=r.get(ckey) if not cr: return None if cr.get("status")=="prohibited": return {"대표 INCI":r.get("label","-"),"결과":cr.get("result","배합금지"),"표시문구":cr.get("formula_text","배합금지"),"비고":cr.get("note","-")} if cr.get("status")=="restricted": return {"대표 INCI":r.get("label","-"),"결과":cr.get("result","제한 성분"),"표시문구":cr.get("formula_text",LIMIT_CHECK_TEXT),"비고":cr.get("note","-")} return None def evaluate_limit_rule(country,material,component,group,name): key=match_rule_key(material,component,group) if not key: return None rule=group[key]; cr=rule.get(country_key(country)); label=rule.get("label",key); amount=component.get("amount_float"); at=format_percent(amount) if amount is not None else "함량 확인 필요" if not cr: return {"대표 INCI":label,"결과":f"{name} / {label} / {display_country(country)} 배합한도 자료 확인 필요","표시문구":LIMIT_CHECK_TEXT,"비고":"로컬 제한성분 목록에는 있으나 해당 국가 한도값 미등록. Pass 처리 금지."} if cr.get("status")=="prohibited": return {"대표 INCI":label,"결과":f"{label} 배합금지 / 현재 함량 {at}% / 재검토 필요","표시문구":cr.get("formula_text","배합금지"),"비고":"-"} lim=cr.get("limit") if lim is not None: if amount is not None and amount>lim: return {"대표 INCI":label,"결과":f"{name} / {label} 현재 함량 {at}%, 한도 {format_percent(lim)}% 초과(재검토 필요)","표시문구":"한도 초과","비고":"-"} return {"대표 INCI":label,"결과":f"{name} / {label} 현재 함량 {at}%, 한도 {format_percent(lim)}% 이내","표시문구":cr.get("formula_text") or f"배합한도: {format_percent(lim)}%","비고":"-"} return {"대표 INCI":label,"결과":f"{name} / {label} / 한도값 확인 필요","표시문구":LIMIT_CHECK_TEXT,"비고":"로컬 규칙에 성분은 있으나 한도값이 비어 있음."} def evaluate_local_rules(country,material,component,ingredient_totals,ingredient_amount_parts): crit=evaluate_critical_country_rule(country,material,component) if crit: return crit if is_always_pass_component(material,component): return {"대표 INCI":safe_str(component.get("INCI Name","")) or "Water","결과":NO_EVIDENCE_TEXT,"표시문구":"Pass","비고":"정제수/Water/Aqua 기본 Pass 처리"} fr=evaluate_plain_fragrance_rule(country,material,component) if fr: return fr for group,name in [(UV_FILTER_RULES,"UV 필터"),(PRESERVATIVE_RULES,"보존제/제한성분")]: res=evaluate_limit_rule(country,material,component,group,name) if res: return res fkey=match_rule_key(material,component,FUNCTIONAL_KOREA_RULES) if country_key(country)=="KOREA" and fkey: r=FUNCTIONAL_KOREA_RULES[fkey]; amount=format_percent(component.get("amount_float")) if component.get("amount_float") is not None else "함량 확인 필요" return {"대표 INCI":r["label"],"결과":r["result"].format(amount=amount),"표시문구":r.get("formula_text","기능성 확인"),"비고":"기능성 표시·광고 여부 확인"} identity=get_identity_raw(material,component) for r in FRAGRANCE_ALLERGEN_RULES.values(): if any_exact_alias_match(r.get("aliases",[]), identity): return {"대표 INCI":r["label"],"결과":f"향료 알레르겐 / {r['label']} / {display_country(country)} 표시기준 확인 필요","표시문구":NEED_CHECK_TEXT,"비고":"향료 알레르겐 후보. 세부 표시기준 및 제품 유형 확인 필요."} if component.get("amount_float") is None: return {"대표 INCI":safe_str(component.get("INCI Name","")) or "-","결과":"함량 정보 없음 / In formula(w/w %) 확인 필요","표시문구":"함량 확인","비고":"-"} return None def parse_country_response(text): res={"대표 INCI":"-","결과":NO_EVIDENCE_TEXT,"표시문구":"Pass","비고":"-"} for line in safe_str(text).splitlines(): if line.startswith("대표 INCI:"): res["대표 INCI"]=line.split(":",1)[1].strip() or "-" elif line.startswith("결과:"): res["결과"]=line.split(":",1)[1].strip() or NO_EVIDENCE_TEXT elif line.startswith("표시문구:"): res["표시문구"]=line.split(":",1)[1].strip() or "Pass" elif line.startswith("비고:"): res["비고"]=line.split(":",1)[1].strip() or "-" return res def sanitize_country_result(parsed,country_col="",component=None,high_risk_reason=""): component=component or {}; rep=safe_str(parsed.get("대표 INCI","")) or safe_str(component.get("INCI Name","")) or "-"; result=safe_str(parsed.get("결과","")) or NO_EVIDENCE_TEXT; disp=safe_str(parsed.get("표시문구","")); note=safe_str(parsed.get("비고","")) or "-" if is_always_pass_component({},component): return {"대표 INCI":rep,"결과":NO_EVIDENCE_TEXT,"표시문구":"Pass","비고":"정제수/Water/Aqua 기본 Pass 처리"} if high_risk_reason and result==NO_EVIDENCE_TEXT: result=f"{high_risk_reason} / {rep} / {country_col} 제한 여부 확인 필요"; disp=NEED_CHECK_TEXT; note="고위험군 후보 성분이므로 근거 미검출만으로 Pass 처리하지 않음" if not disp: disp=normalize_formula_country_text(result,country_col,safe_str(component.get("INCI Name","")),safe_str(component.get("In formula(w/w %)",""))) return {"대표 INCI":rep,"결과":result,"표시문구":disp,"비고":note} def has_meaningful_search_hit(db,search_text,names,k=2): if not db: return False,"" docs=db.similarity_search(search_text,k=k); ctx="\n".join(d.page_content for d in docs); cn=normalize_compact(ctx) return any(normalize_compact(n) and len(normalize_compact(n))>=3 and normalize_compact(n) in cn for n in names),ctx def make_eval_cache_key(country,component): return (str(country),str(get_current_db_signature(country)),safe_str(component.get("INCI Name","")).lower(),safe_str(component.get("한글 성분명","")).lower(),safe_str(component.get("CAS.No","")).lower(),safe_str(component.get("In formula(w/w %)",""))) def evaluate_component_with_llm(country,material,component,llm,target_id=""): db=build_database(country); col=display_country(country); inci=safe_str(component.get("INCI Name","")); ko=safe_str(component.get("한글 성분명","")); cas=safe_str(component.get("CAS.No","")); amount=component.get("amount_float"); at=format_percent(amount) if amount is not None else "함량 확인 필요"; hr=get_restricted_candidate_reason(material,component) crit=evaluate_critical_country_rule(country,material,component) if crit: return crit if is_always_pass_component(material,component): return {"대표 INCI":inci or ko or cas or "Water","결과":NO_EVIDENCE_TEXT,"표시문구":"Pass","비고":"정제수/Water/Aqua 기본 Pass 처리"} if not db: result={"대표 INCI":inci or ko or cas or "-","결과":f"{hr} / {inci or ko or cas} / {col} 제한 여부 확인 필요" if hr else NO_EVIDENCE_TEXT,"표시문구":NEED_CHECK_TEXT if hr else "Pass","비고":"해당 국가/채널 규제 DB 없음." if hr else "-"} return result ck=make_eval_cache_key(country,component) if ck in EVAL_CACHE: return EVAL_CACHE[ck] search=f"국가:{country}\n국문:{ko}\nINCI:{inci}\nCAS:{cas}\n함량:{at}%" hit,pre=has_meaningful_search_hit(db,search,[inci,ko,cas]) if not hit: result={"대표 INCI":inci or ko or cas or "-","결과":f"{hr} / {inci or ko or cas} / {col} 제한 여부 확인 필요" if hr else NO_EVIDENCE_TEXT,"표시문구":NEED_CHECK_TEXT if hr else "Pass","비고":"고위험군 후보이나 직접 근거 미검출" if hr else "-"}; EVAL_CACHE[ck]=result; return result docs=db.similarity_search(search,k=2); ctx="\n".join(d.page_content for d in docs) prompt=f"""너는 화장품 규제 스크리닝 전문가다. 현재 국가는 {country}다. 아래 원문만 근거로 판단하라. 외부지식 금지. 원문에 근거 없으면 결과는 정확히 '{NO_EVIDENCE_TEXT}'. 배합한도는 현재 성분명과 %가 같은 문장/인접 문단에 있을 때만 작성. 표시기준/알레르겐/불순물/시험법 수치를 배합한도로 쓰지 마.\n성분: 국문 {ko}, INCI {inci}, CAS {cas}, 함량 {at}%\n고위험 후보: {hr or '아님'}\n원문:\n{ctx}\n\n형식:\n대표 INCI:\n결과:\n표시문구:\n비고:""" try: parsed=parse_country_response(llm.invoke(prompt).content); parsed=sanitize_country_result(parsed,col,component,hr); parsed=validate_limit_result_against_evidence(parsed,ctx,component); EVAL_CACHE[ck]=parsed; return parsed except Exception as e: return {"대표 INCI":inci or ko or cas or "-","결과":"확인 필요","표시문구":NEED_CHECK_TEXT,"비고":str(e)} def evaluate_components_with_llm_batch(country,targets,llm): return {item["target_id"]:evaluate_component_with_llm(country,item["material"],item["component"],llm,item["target_id"]) for item in targets} def make_formula_statement_rows(row_items,country_cols): rows=[] for item in row_items: mat=item["material"]; comp=item["component"]; rd=item["row_data"] row={"NO.":mat.get("NO",""),"한글 표준화 명칭":comp.get("한글 성분명",""),"INGREDIENT NAME (INCI)":comp.get("INCI Name",""),"FUNCTION":comp.get("FUNCTION",""),"CAS.No":comp.get("CAS.No",""),"SOURCE":comp.get("SOURCE","ICID") or "ICID","%(w/w)":comp.get("In formula(w/w %)","")} for cc in country_cols: row[cc]=normalize_formula_country_text(rd.get(cc+"_display","") or rd.get(cc,""),cc,row["INGREDIENT NAME (INCI)"],row["%(w/w)"]) rows.append(row) total=sum(to_number(r.get("%(w/w)","")) or 0 for r in rows); total_row={"NO.":"","한글 표준화 명칭":"","INGREDIENT NAME (INCI)":"TOTAL","FUNCTION":"","CAS.No":"","SOURCE":"","%(w/w)":format_amount(total)} for cc in country_cols: total_row[cc]="" rows.append(total_row); return pd.DataFrame(rows) def make_regulatory_summary_rows(row_items,country_cols): rows=[] for item in row_items: rd=item["row_data"] if not is_country_result_issue(rd.get("Result","")): continue row={"한글 성분명":rd.get("한글 성분명",""),"INCI Name":rd.get("INCI Name",""),"In formula(w/w %)":rd.get("In formula\n(w/w %)",""),"Result":rd.get("Result","")} for cc in country_cols: row[cc]=rd.get(cc,"") if is_country_result_issue(rd.get(cc,"")) else "-" row["비고"]=rd.get("비고","-"); rows.append(row) cols=["한글 성분명","INCI Name","In formula(w/w %)","Result"]+country_cols+["비고"] return pd.DataFrame(rows,columns=cols) def sum_formula_percent(df): return sum(to_number(r.get("%(w/w)","")) or 0 for _,r in df.iterrows() if not is_total_like_text(r.get("INGREDIENT NAME (INCI)",""))) def write_output_workbook(out_path,product_name,formula_df,regulatory_df,raw_df): with pd.ExcelWriter(out_path,engine="openpyxl") as w: formula_df.to_excel(w,index=False,sheet_name="Formula Ingredients Statement",startrow=5) regulatory_df.to_excel(w,index=False,sheet_name="Regulatory Screening Summary") raw_df.to_excel(w,index=False,sheet_name="Evidence Log") style_output_workbook(out_path,product_name) def style_output_workbook(path,product_name=""): wb=load_workbook(path); thin=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")); warn=PatternFill("solid",fgColor="FCE4D6") 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") 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) for sheet in wb.worksheets: for row in sheet.iter_rows(): for cell in row: cell.border=thin; cell.alignment=Alignment(horizontal="center",vertical="center",wrap_text=True) if sheet.title=="Formula Ingredients Statement" and cell.row>6 and cell.column>=8 and safe_str(cell.value) and safe_str(cell.value)!="Pass": cell.fill=warn for col in range(1,sheet.max_column+1): sheet.column_dimensions[get_column_letter(col)].width=18 wb.save(path) def build_integrated_result(rd,country_cols): issues=[cc for cc in country_cols if is_country_result_issue(rd.get(cc,""))] return "PASS" if not issues else "재검토 필요: "+", ".join(issues) def process(countries,file,product_name="",use_mfds_live=False,live_max_terms=5,live_headless=True): """ 전성분 전체 스크리닝 고속 버전. 변경 내용: - 전체 스크리닝에서 GPT/LLM 호출 제거 - 국가별 파일 직접 검색(COUNTRY_FILE_FAST) 우선 - 선택 국가별 섹션 인덱스 1회 워밍업 - 전체 스크리닝에서는 속도 보호를 위해 식약처 실시간 조회 자동 비활성화 """ global RAW_SEARCH_LOGS RAW_SEARCH_LOGS = [] try: if not file: return None, None, "❌ 파일을 업로드해주세요." if not countries: return None, None, "❌ 스크리닝 국가를 선택해주세요." df = load_input_file_to_dataframe(file) materials, meta = make_grouped_materials(df) if not materials: return None, None, "❌ 파일에서 전성분 정보를 읽지 못했습니다." row_items = [] for mat in materials: comp = mat["Components"][0] rd = { "한글 성분명": 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": f"row_{len(row_items)}", "material": mat, "component": comp, "row_data": rd, "notes": [], }) index_messages = [] for country in countries: try: sections, index_status = get_country_section_index_cached(country) index_messages.append(f"{display_country(country)}={index_status}/{len(sections)} sections") except Exception as e: index_messages.append(f"{display_country(country)}=index error: {e}") # 전체 전성분 스크리닝에서는 MFDS 사이트 실시간 조회를 돌리지 않는다. # 성분 수가 많을 때 Playwright 접속/대기 시간이 성분 수만큼 누적되어 1시간 이상 걸릴 수 있기 때문. batch_live_requested = bool(use_mfds_live) use_mfds_live = False if not ENABLE_MFDS_LIVE_FOR_BATCH else bool(use_mfds_live) terms = [] mfds_df = pd.DataFrame() mfds_msg = "사용 안 함" if batch_live_requested and not ENABLE_MFDS_LIVE_FOR_BATCH: mfds_msg = BATCH_MFDS_DISABLE_REASON if use_mfds_live: terms = extract_terms_for_live_lookup(row_items, max_terms=min(int(live_max_terms or 5), 5)) mfds_df, mfds_msg = mfds_live_lookup_terms(terms, min(int(live_max_terms or 5), 5), True) for country in countries: col = display_country(country) for item in row_items: mat = item["material"] comp = item["component"] final_result = None source = "" final_result = evaluate_critical_country_rule( country=country, material=mat, component=comp, ) if final_result is not None: source = "CRITICAL_COUNTRY_RULE" if final_result is None and is_always_pass_component(mat, comp): final_result = { "대표 INCI": safe_str(comp.get("INCI Name", "")) or "Water", "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "정제수/Water/Aqua 기본 Pass 처리", } source = "ALWAYS_PASS_RULE" if final_result is None: fragrance_result = evaluate_plain_fragrance_rule( country=country, material=mat, component=comp, ) if fragrance_result is not None: final_result = fragrance_result source = "FRAGRANCE_RULE" if final_result is None and use_mfds_live and mfds_df is not None and not mfds_df.empty: mfds_result = evaluate_live_detail_rule( country=country, material=mat, component=comp, live_df=mfds_df, ) if mfds_result is not None: final_result = mfds_result source = "MFDS_LIVE" if final_result is None: file_result = evaluate_component_from_country_files_only( country=country, material=mat, component=comp, target_id=item["target_id"], ) if file_result is not None: final_result = file_result source = "COUNTRY_FILE_FAST" if final_result is None: local_result = evaluate_local_rules( country=country, material=mat, component=comp, ingredient_totals=meta["ingredient_totals"], ingredient_amount_parts=meta["ingredient_amount_parts"], ) if local_result is not None: final_result = local_result source = "LOCAL_RULE" if final_result is None: final_result = { "대표 INCI": safe_str(comp.get("INCI Name", "")) or safe_str(comp.get("한글 성분명", "")) or "-", "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "국가별 파일 내 현재 성분 직접 근거 없음", } source = "NO_EVIDENCE" item["row_data"][col] = final_result.get("결과", "") item["row_data"][col + "_display"] = final_result.get("표시문구", "Pass") note = safe_str(final_result.get("비고", "-")) if note and note != "-": item["notes"].append(f"{col}: {note}") log_search_context( item["target_id"], country, comp, final_result.get("결과", ""), source, 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_df = pd.DataFrame(RAW_SEARCH_LOGS) if RAW_SEARCH_LOGS else pd.DataFrame( columns=["target_id", "국가/채널", "성분명", "INCI Name", "판정", "출처", "검색 원문"] ) out = str( OUTPUT_DIR / f"screening_result_{safe_filename(product_name) if product_name else 'product'}_{safe_filename('_'.join(countries))}.xlsx" ) write_output_workbook(out, product_name, formula_df, regulatory_df, raw_df) msg = ( "✅ 분석 완료\n" f"- Product Name: {safe_str(product_name) or '-'}\n" f"- 전성분 행 수: {len(formula_df)}개\n" f"- In formula 합계: {format_amount(sum_formula_percent(formula_df))}%\n" f"- 재검토 필요 성분: {len(regulatory_df)}개\n" f"- MFDS 상태: {mfds_msg}\n" "- 판정 방식: GPT 판정 없음 / 업로드된 국가별 파일 row·line 직접 검색\n" f"- 국가별 인덱스 상태: {' | '.join(index_messages)}\n" "- 속도 개선: 전체 스크리닝에서 GPT/LLM 호출 제거\n" ) return formula_df, out, msg except Exception as e: tb = traceback.format_exc() print(tb) return None, None, f"❌ 오류 발생: {e}\n\n{tb[-3000:]}" def extract_single_lookup_terms(query, material, component): """ 단일 성분 검색에서 식약처 실시간 조회에 사용할 검색어를 만든다. 정제수/Water/Aqua 같은 기본 Pass 성분은 식약처 조회를 생략한다. """ query = safe_str(query) if not query: return [] if is_always_pass_component(material, component): return [] return build_ingredient_lookup_terms( material=material, component=component, extra_terms=[query], )[:5] def build_single_component_from_query(query, amount="", function="", single_amount=None, single_function=None): """ 단일 성분 검색용 component 생성. 기존 코드 호환을 위해 amount/function과 single_amount/single_function을 모두 받는다. 반환값은 process_single_ingredient()와 맞춰 material, component, amount_text 3개다. """ if single_amount is not None: amount = single_amount if single_function is not None: function = single_function q = safe_str(query) af = to_number(amount) at = format_amount(af) if af is not None else "" ko = q inci = q cas = "" if is_cas_like(q): cas = q ko = "" inci = q comp = { "한글 성분명": ko, "INCI Name": inci, "FUNCTION": safe_str(function), "CAS.No": cas, "SOURCE": "Manual Search", "In formula(w/w %)": at, "amount_float": af, } mat = { "NO": "1", "Trade name(국문)": ko or q, "Trade name(영문)": inci or q, "Components": [comp], } return mat, comp, at def get_country_regulatory_text_cached(country): """ 국가별 규제 파일 원문을 직접 읽어서 캐시한다. 단일 성분 검색에서는 FAISS/임베딩 대신 이 원문 직접검색을 사용한다. """ global REG_TEXT_CACHE folder = resolve_country_folder(country) if not folder or not os.path.isdir(folder): return "", "해당 국가/채널 폴더 없음" files = get_regulatory_file_list(folder) if not files: return "", "해당 국가/채널 규제 파일 없음" signature = tuple((f["relative_path"], f["size"], f["mtime_ns"]) for f in files) sig_hash = stable_hash(signature) cache_key = f"{folder}|{sig_hash}" cached = REG_TEXT_CACHE.get(cache_key) if cached is not None: return cached, "CACHE" text_blocks = [] for item in files: try: raw = extract_text_from_regulatory_file(item) if raw: text_blocks.append( f"[국가/채널: {folder}] [출처파일: {item['relative_path']}]\n{raw}" ) except Exception as e: text_blocks.append( f"[국가/채널: {folder}] [출처파일: {item.get('relative_path', '')}] 파일 읽기 실패: {e}" ) combined = "\n\n".join(text_blocks) REG_TEXT_CACHE[cache_key] = combined return combined, "READ_FILES" def infer_regulation_type_from_source_text(source_text, country=""): """ 파일명/시트명/문서 제목 기준으로 규제 유형을 판단한다. 중요: - Annex II/III/IV/V/VI 명칭은 EU와 ASEAN에만 사용한다. - KOREA/FDA/JAPAN/CHINA 등은 Annex라고 표시하지 않고 '국가별 금지성분 목록', '국가별 제한성분 목록'처럼 표시한다. """ text = safe_str(source_text) low = text.lower() compact = normalize_compact(text) ckey = country_key(country) def has_any(patterns): return any(p in low or normalize_compact(p) in compact for p in patterns) is_eu_or_asean = ckey in ["EU", "ASEAN", "EU_FUTURE"] # 1) 금지 목록 if has_any([ "annex ii", "annex 2", "annex_ii", "annex-ii", "prohibited substances", "list of substances prohibited", "negative list", "사용금지원료", "사용금지 원료", "사용 금지 원료", "사용금지성분", "사용 금지 성분", "금지원료", "금지 원료", "금지성분", "금지 성분", "배합금지", "사용금지", "사용 금지", ]): label = "Annex II / Negative List / Prohibited Substances" if is_eu_or_asean else "국가별 금지성분 목록 / Prohibited Substances" return { "type": "prohibited", "label": label, "display": "배합금지", } # 2) 제한 목록 if has_any([ "annex iii", "annex 3", "annex_iii", "annex-iii", "restricted substances", "list of substances which cosmetic products must not contain except subject to the restrictions", "restriction", "restricted", "사용제한원료", "사용제한 원료", "사용 제한 원료", "사용제한성분", "사용 제한 성분", "사용 제한", "사용제한", "제한 원료", "제한성분", "제한 성분", "배합한도", ]): label = "Annex III / Negative List / Restricted Substances" if is_eu_or_asean else "국가별 제한성분 목록 / Restricted Substances" return { "type": "restricted", "label": label, "display": NEED_CHECK_TEXT, } # 3) EU/ASEAN Positive Lists만 Annex IV/V/VI로 표시 if is_eu_or_asean and has_any([ "annex iv", "annex 4", "annex_iv", "annex-iv", "coloring agents", "colouring agents", "colorants", "colorant", "색소", ]): return { "type": "positive_colorant", "label": "Annex IV / Positive List / Coloring Agents", "display": "허용목록 등재", } if is_eu_or_asean and has_any([ "annex v", "annex 5", "annex_v", "annex-v", "preservatives", "preservative", "보존제", "방부제", ]): return { "type": "positive_preservative", "label": "Annex V / Positive List / Preservatives", "display": "허용목록 등재", } if is_eu_or_asean and has_any([ "annex vi", "annex 6", "annex_vi", "annex-vi", "uv filters", "uv filter", "ultraviolet filters", "sunscreen agents", "자외선", "자외선차단", ]): return { "type": "positive_uv", "label": "Annex VI / Positive List / UV Filters", "display": "허용목록 등재", } # 4) EU/ASEAN 외 국가의 Positive List 계열은 Annex 표시 없이 일반 표시 if has_any(["색소", "coloring agents", "colouring agents", "colorants", "colorant"]): return { "type": "positive_colorant", "label": "국가별 허용 색소 목록 / Coloring Agents", "display": "허용목록 등재", } if has_any(["보존제", "방부제", "preservatives", "preservative"]): return { "type": "positive_preservative", "label": "국가별 허용 보존제 목록 / Preservatives", "display": "허용목록 등재", } if has_any(["자외선", "자외선차단", "uv filters", "uv filter", "ultraviolet filters", "sunscreen agents"]): return { "type": "positive_uv", "label": "국가별 허용 자외선차단제 목록 / UV Filters", "display": "허용목록 등재", } return { "type": "unknown", "label": "규제 유형 미분류", "display": NEED_CHECK_TEXT, } def split_regulatory_text_into_sections(raw_text): """ get_country_regulatory_text_cached()에서 만든 텍스트를 파일/시트/페이지 단위 섹션으로 나눈다. """ raw_text = safe_str(raw_text) if not raw_text: return [] parts = re.split(r"(?=\[국가/채널:)", raw_text) sections = [] for part in parts: part = safe_str(part) if not part: continue header_lines = part.splitlines()[:8] header_text = "\n".join(header_lines) sections.append({ "header": header_text, "text": part, }) return sections def get_country_section_index_cached(country): """ 단일 성분 검색 고속화용 섹션 인덱스. 국가별 파일을 매번 PDF/Excel 전체 읽기하지 않고, 파일/시트/페이지 섹션 단위로 캐시한다. """ global REG_SECTION_INDEX_CACHE folder = resolve_country_folder(country) if not folder or not os.path.isdir(folder): return [], "해당 국가/채널 폴더 없음" files = get_regulatory_file_list(folder) if not files: return [], "해당 국가/채널 규제 파일 없음" signature = tuple((f["relative_path"], f["size"], f["mtime_ns"]) for f in files) sig_hash = stable_hash(signature) memory_key = f"{folder}|{sig_hash}" if memory_key in REG_SECTION_INDEX_CACHE: return REG_SECTION_INDEX_CACHE[memory_key], "MEMORY_CACHE" os.makedirs(REG_INDEX_CACHE_DIR, exist_ok=True) cache_file = os.path.join( REG_INDEX_CACHE_DIR, f"{safe_filename(folder)}_{sig_hash[:16]}_sections.json", ) if os.path.exists(cache_file): try: with open(cache_file, "r", encoding="utf-8") as f: payload = json.load(f) if payload.get("signature_hash") == sig_hash: sections = payload.get("sections", []) REG_SECTION_INDEX_CACHE[memory_key] = sections return sections, "DISK_CACHE" except Exception as e: print(f"섹션 인덱스 캐시 로드 실패: {cache_file} / {e}") sections = [] for item in files: try: raw = extract_text_from_regulatory_file(item) if not raw: continue rel = item.get("relative_path", "") ext = item.get("ext", "") source_header = f"[국가/채널: {folder}] [출처파일: {rel}] [확장자: {ext}]" reg_type = infer_regulation_type_from_source_text(source_header + "\n" + raw[:1500], country=country) sections.append({ "folder": folder, "source_file": rel, "header": source_header, "regulation_type": reg_type, "text": raw, "text_norm": normalize_compact(raw), }) except Exception as e: print(f"섹션 인덱스 생성 실패: {item.get('path', '')} / {e}") REG_SECTION_INDEX_CACHE[memory_key] = sections try: with open(cache_file, "w", encoding="utf-8") as f: json.dump( { "country": str(country), "folder": folder, "signature_hash": sig_hash, "sections": sections, }, f, ensure_ascii=False, ) except Exception as e: print(f"섹션 인덱스 캐시 저장 실패: {cache_file} / {e}") return sections, "BUILT_INDEX" def find_matching_regulatory_sections_fast(country, ingredient_names, max_sections=30): """ 고속 단일 검색. get_country_section_index_cached()가 만든 섹션 인덱스에서 성분명/INCI/CAS를 직접 검색한다. """ sections, status = get_country_section_index_cached(country) names_norm = [ normalize_compact(x) for x in ingredient_names if safe_str(x) and len(normalize_compact(x)) >= 3 ] if not names_norm: return [], status matches = [] for section in sections: text_norm = section.get("text_norm", "") if not any(name in text_norm for name in names_norm): continue text = safe_str(section.get("text", "")) header = safe_str(section.get("header", "")) lines = [safe_str(x) for x in text.splitlines() if safe_str(x)] hit_indices = [] for idx, line in enumerate(lines): line_norm = normalize_compact(line) if any(name in line_norm for name in names_norm): hit_indices.append(idx) if len(hit_indices) >= 10: break context_lines = [] seen = set() for idx in hit_indices: start = max(0, idx - 4) end = min(len(lines), idx + 5) for j in range(start, end): if j in seen: continue seen.add(j) context_lines.append(lines[j]) if context_lines: context = header + "\n" + "\n".join(context_lines) else: context = header + "\n" + text[:2000] # 디스크 캐시가 오래된 label을 가질 수 있으므로 header 기준으로 한번 더 보정 reg_type = infer_regulation_type_from_source_text( header + "\n" + text[:1500], country=country, ) matches.append({ "header": header, "context": context[:8000], "regulation_type": reg_type, }) if len(matches) >= max_sections: break return matches, status def find_matching_regulatory_sections(raw_text, ingredient_names, max_sections=20): """ 구버전 호환용. 신규 단일 검색은 find_matching_regulatory_sections_fast()를 사용한다. """ names_norm = [ normalize_compact(x) for x in ingredient_names if safe_str(x) and len(normalize_compact(x)) >= 3 ] if not names_norm: return [] matches = [] for section in split_regulatory_text_into_sections(raw_text): text = section["text"] text_norm = normalize_compact(text) if any(name in text_norm for name in names_norm): lines = [safe_str(x) for x in text.splitlines() if safe_str(x)] hit_indices = [] for idx, line in enumerate(lines): line_norm = normalize_compact(line) if any(name in line_norm for name in names_norm): hit_indices.append(idx) context_lines = [] seen = set() for idx in hit_indices[:8]: start = max(0, idx - 4) end = min(len(lines), idx + 5) for j in range(start, end): if j in seen: continue seen.add(j) context_lines.append(lines[j]) context = section["header"] + "\n" + "\n".join(context_lines) reg_type = infer_regulation_type_from_source_text(section["header"] + "\n" + text[:1200], country="") matches.append({ "header": section["header"], "context": context[:8000], "regulation_type": reg_type, }) if len(matches) >= max_sections: break return matches def pick_best_regulatory_match(matches): """ 여러 파일에서 동시에 매칭될 때 우선순위를 정한다. 금지 > 제한 > Positive List > unknown 순서. """ if not matches: return None priority = { "prohibited": 100, "restricted": 80, "positive_uv": 50, "positive_preservative": 50, "positive_colorant": 50, "unknown": 10, } matches = sorted( matches, key=lambda m: priority.get(m.get("regulation_type", {}).get("type", "unknown"), 0), reverse=True, ) return matches[0] def warmup_country_indexes(countries): """ 선택 국가의 단일 검색 인덱스를 미리 만든다. """ messages = [] for country in countries or []: try: sections, status = get_country_section_index_cached(country) messages.append(f"{display_country(country)}: {status}, sections={len(sections)}") except Exception as e: messages.append(f"{display_country(country)}: 인덱스 생성 실패 - {e}") return "\n".join(messages) if messages else "선택된 국가 없음" def extract_limit_condition_from_context(context): text = safe_str(context) compact = re.sub(r"\s+", " ", text).strip() if not compact: return "", "" patterns = [ r"([0-9]+(?:\.[0-9]+)?\s*%)", r"([0-9]+(?:\.[0-9]+)?\s*ppm)", r"([0-9]+(?:\.[0-9]+)?\s*g\s*/\s*100\s*g)", r"([0-9]+(?:\.[0-9]+)?\s*g\s+per\s+100\s*g)", r"([0-9]+(?:\.[0-9]+)?\s*mg\s*/\s*kg)", ] limits = [] for pat in patterns: for m in re.finditer(pat, compact, flags=re.IGNORECASE): v = m.group(1).replace(" ", "") if v not in limits: limits.append(v) condition_keywords = [ "leave-on", "rinse-off", "oral", "mucosa", "washed away", "보존제", "방부제", "자외선", "색소", "점막", "구강", "제한사항", "경고", "warning", "condition", "한도", "제한", ] condition_lines = [] for line in [safe_str(x) for x in text.splitlines() if safe_str(x)]: l = line.lower() if any(k.lower() in l for k in condition_keywords): cleaned = re.sub(r"\s+", " ", line).strip() if cleaned not in condition_lines: condition_lines.append(cleaned) return ", ".join(limits[:5]), " / ".join(condition_lines[:5])[:700] def make_restricted_or_positive_result(country, component, match, reg_type): context = safe_str(match.get("context", "")) if isinstance(match, dict) else safe_str(match) label = safe_str(reg_type.get("label", "규제 목록")) kind = safe_str(reg_type.get("type", "")) limit_text, condition_text = extract_limit_condition_from_context(context) representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or "-" if limit_text: display = f"배합한도: {limit_text}" result = f"{display_country(country)} {label}에서 성분 확인 / 한도 {limit_text}" elif kind.startswith("positive_"): display = "허용목록 등재 / 한도 확인 필요" result = f"{display_country(country)} {label}에서 성분 확인 / 목적별 허용목록 등재, 한도·조건 확인 필요" else: display = "배합한도/제한 확인" result = f"{display_country(country)} {label}에서 성분 확인 / 한도·조건 확인 필요" if condition_text: result += f" / 조건: {condition_text}" return { "대표 INCI": representative, "결과": result, "표시문구": display, "비고": context[:1000] if context else label, } # ============================================================ # 소스 파일 기반 규제 인덱스 # - 성분별 하드코딩 registry 대신, 국가 폴더 내 업로드된 규제파일 자체를 row/line 단위로 인덱싱 # - 파일 안에서 직접 확인된 행/문맥만 근거로 판정 # ============================================================ SOURCE_RECORD_INDEX_CACHE = {} def is_noise_source_row_text(text): text = safe_str(text) compact = normalize_compact(text) low = text.lower() if not compact: return True noise_terms = [ "no", "번호", "순번", "ingredientname", "inci", "function", "casno", "source", "구분", "국가", "고시원료명", "단서조항", "제한사항", "기준일자", "productname", "formularingredientsstatement", "formulaingredientsstatement", ] # header-only row hit = sum(1 for n in noise_terms if n in compact) if hit >= 4 and len(compact) < 120: return True if "copyright" in low or "page " in low: return True return False def source_match_terms_for_component(material=None, component=None): """ 파일 직접 매칭에 사용할 검색어. broad alias 생성 금지. 입력 성분명/국문/CAS/원료명만 사용. """ material = material or {} component = component or {} terms = [] for v in [ component.get("INCI Name", ""), component.get("한글 성분명", ""), component.get("CAS.No", ""), material.get("Trade name(국문)", ""), material.get("Trade name(영문)", ""), ]: v = safe_str(v) if not v: continue # 원료표에서 생긴 header/메타값 방지 if normalize_compact(v) in [ "ingredientname", "ingredientnameinci", "function", "casno", "source", "productname", "no", "번호", ]: continue if len(normalize_compact(v)) >= 3 and v not in terms: terms.append(v) return terms def infer_record_regulation_type(country, source_file, sheet_name="", row_text=""): basis = f"{source_file}\n{sheet_name}\n{row_text[:1500]}" return infer_regulation_type_from_source_text(basis, country=country) def build_country_source_record_index(country): """ 국가별 규제파일을 row/line 단위 record로 만든다. Excel/CSV: row 단위 PDF/TXT: line window 단위 """ folder = resolve_country_folder(country) if not folder or not os.path.isdir(folder): return [], "해당 국가/채널 폴더 없음" files = get_regulatory_file_list(folder) if not files: return [], "해당 국가/채널 규제 파일 없음" signature = tuple((f["relative_path"], f["size"], f["mtime_ns"]) for f in files) sig_hash = stable_hash(signature) cache_key = f"{folder}|source_records|{sig_hash}" if cache_key in SOURCE_RECORD_INDEX_CACHE: return SOURCE_RECORD_INDEX_CACHE[cache_key], "MEMORY_CACHE" records = [] for item in files: path = item["path"] rel = item["relative_path"] ext = item["ext"] try: if ext in [".xlsx", ".xls"]: sheets = pd.read_excel(path, sheet_name=None, header=None, dtype=str) for sheet_name, df in sheets.items(): df = df.fillna("") for ridx, row in df.iterrows(): cells = [safe_str(x) for x in row.tolist() if safe_str(x)] row_text = " | ".join(cells) if is_noise_source_row_text(row_text): continue reg_type = infer_record_regulation_type(country, rel, sheet_name, row_text) records.append({ "country": display_country(country), "source_file": rel, "sheet": safe_str(sheet_name), "row_index": int(ridx) + 1, "text": row_text, "text_norm": normalize_compact(row_text), "regulation_type": reg_type, }) elif ext == ".csv": try: df = pd.read_csv(path, header=None, dtype=str).fillna("") except UnicodeDecodeError: df = pd.read_csv(path, header=None, dtype=str, encoding="cp949").fillna("") for ridx, row in df.iterrows(): cells = [safe_str(x) for x in row.tolist() if safe_str(x)] row_text = " | ".join(cells) if is_noise_source_row_text(row_text): continue reg_type = infer_record_regulation_type(country, rel, "", row_text) records.append({ "country": display_country(country), "source_file": rel, "sheet": "", "row_index": int(ridx) + 1, "text": row_text, "text_norm": normalize_compact(row_text), "regulation_type": reg_type, }) else: raw = extract_text_from_regulatory_file(item) lines = [safe_str(x) for x in raw.splitlines() if safe_str(x)] for i, line in enumerate(lines): if is_noise_source_row_text(line): continue window = "\n".join(lines[max(0, i - 3): min(len(lines), i + 4)]) reg_type = infer_record_regulation_type(country, rel, "", window) records.append({ "country": display_country(country), "source_file": rel, "sheet": "", "row_index": i + 1, "text": window, "text_norm": normalize_compact(window), "regulation_type": reg_type, }) except Exception as e: print(f"source record index error: {path} / {e}") SOURCE_RECORD_INDEX_CACHE[cache_key] = records return records, "BUILT_SOURCE_RECORD_INDEX" def pick_best_source_record(records): priority = { "prohibited": 100, "restricted": 80, "positive_uv": 50, "positive_preservative": 50, "positive_colorant": 50, "unknown": 10, } return sorted( records, key=lambda r: priority.get(r.get("regulation_type", {}).get("type", "unknown"), 0), reverse=True, )[0] if records else None def evaluate_component_from_uploaded_source_records(country, material, component, target_id=""): """ 국가 폴더 파일만 보고 판정. 파일 record 안에 현재 성분명/국문/CAS가 직접 있을 때만 판정한다. """ terms = source_match_terms_for_component(material, component) term_norms = [normalize_compact(t) for t in terms if len(normalize_compact(t)) >= 3] representative = ( safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-" ) if not term_norms: return None records, status = build_country_source_record_index(country) hits = [] for rec in records: rec_norm = rec.get("text_norm", "") if any(tn in rec_norm for tn in term_norms): hits.append(rec) if not hits: return None best = pick_best_source_record(hits) reg_type = best.get("regulation_type", {}) reg_kind = reg_type.get("type", "unknown") reg_label = reg_type.get("label", "규제 유형 미분류") context = best.get("text", "") country_col = display_country(country) if reg_kind == "prohibited": result = { "대표 INCI": representative, "결과": f"{country_col} {reg_label}에서 성분 직접 확인", "표시문구": "배합금지", "비고": f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}", } log_search_context(target_id, country, component, result["결과"], "UPLOADED_SOURCE_RECORD_PROHIBITED", result["비고"]) return result if reg_kind == "restricted": limit_text, condition_text = extract_limit_condition_from_context(context) result = { "대표 INCI": representative, "결과": f"{country_col} {reg_label}에서 성분 직접 확인" + (f" / 조건: {condition_text}" if condition_text else ""), "표시문구": f"배합한도: {limit_text}" if limit_text else NEED_CHECK_TEXT, "비고": f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}", } log_search_context(target_id, country, component, result["결과"], "UPLOADED_SOURCE_RECORD_RESTRICTED", result["비고"]) return result if reg_kind.startswith("positive_"): limit_text, condition_text = extract_limit_condition_from_context(context) result = { "대표 INCI": representative, "결과": f"{country_col} {reg_label}에서 성분 직접 확인" + (f" / 조건: {condition_text}" if condition_text else ""), "표시문구": f"배합한도: {limit_text}" if limit_text else "허용목록 등재 / 한도 확인 필요", "비고": f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}", } log_search_context(target_id, country, component, result["결과"], "UPLOADED_SOURCE_RECORD_POSITIVE", result["비고"]) return result # 파일에서는 성분을 찾았지만 파일 유형이 불명확한 경우: # PASS로 단정하지 않고 확인 필요로 표시. 단, 이 경우도 "파일 직접 확인"은 남긴다. result = { "대표 INCI": representative, "결과": f"{country_col} 국가별 파일에서 성분 직접 확인 / 파일 유형 미분류", "표시문구": NEED_CHECK_TEXT, "비고": f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}", } log_search_context(target_id, country, component, result["결과"], "UPLOADED_SOURCE_RECORD_UNKNOWN", result["비고"]) return result def evaluate_component_from_country_files_only(country, material, component, target_id=""): """ 국가별 업로드 파일 기반 판정. 성분별 하드코딩 registry보다 업로드된 국가 파일 row/line record를 우선 사용한다. 원칙: - 업로드 파일 record에 현재 성분명/국문/CAS가 직접 있으면 그 파일 유형에 따라 판정 - 금지/제한/Positive List 파일명 또는 row 문맥으로 유형 판단 - 파일에서 직접 근거가 없으면 Pass - broad alias/glycol/extract 같은 넓은 검색어로 금지/제한 만들지 않음 """ 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", "")) representative = inci_name or korean_name or cas_no or "-" critical_result = evaluate_critical_country_rule( country=country, material=material, component=component, ) if critical_result is not None: log_search_context( target_id, country, component, critical_result.get("결과", ""), "CRITICAL_COUNTRY_RULE", critical_result.get("비고", "-"), ) return critical_result if is_always_pass_component(material, component): result = { "대표 INCI": representative if representative != "-" else "Water", "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "정제수/Water/Aqua 기본 Pass 처리", } log_search_context(target_id, country, component, result["결과"], "ALWAYS_PASS_RULE", result["비고"]) return result source_result = evaluate_component_from_uploaded_source_records( country=country, material=material, component=component, target_id=target_id, ) if source_result is not None: return source_result result = { "대표 INCI": representative, "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "업로드된 국가별 파일 내 현재 성분 직접 근거 없음", } log_search_context( target_id, country, component, result["결과"], "UPLOADED_SOURCE_RECORD_NO_HIT", result["비고"], ) return result def shorten_for_table(value, max_len=80): value = safe_str(value) if len(value) <= max_len: return value return value[:max_len] + "..." def make_single_display_result(final_result, country_col="", component=None): """ 단일 성분 검색 결과 표의 '배합한도/금지' 칸에 들어갈 짧은 표시문구를 만든다. """ component = component or {} result_text = safe_str(final_result.get("결과", "")) display_text = safe_str(final_result.get("표시문구", "")) inci_name = safe_str(component.get("INCI Name", "")) if display_text: cleaned_display = normalize_formula_country_text( display_text, country_col=country_col, inci_name=inci_name, amount_text=safe_str(component.get("In formula(w/w %)", "")), ) if cleaned_display: return cleaned_display cleaned_result = normalize_formula_country_text( result_text, country_col=country_col, inci_name=inci_name, amount_text=safe_str(component.get("In formula(w/w %)", "")), ) if cleaned_result: return cleaned_result return NEED_CHECK_TEXT def simplify_single_note(note): """ 단일 성분 검색 결과의 비고를 너무 길지 않게 정리한다. """ note = safe_str(note) if not note or note == "-": return "" replace_map = { "로컬 제한성분 목록에는 있으나 해당 국가 한도값 미등록. Pass 처리 금지.": "해당 국가 한도값 미등록", "고위험군 후보 성분이므로 근거 미검출만으로 Pass 처리하지 않음": "근거 미검출, 확인 필요", "고위험군 후보이나 국가별 규제파일에서 직접 근거 미검출. Pass 처리하지 않음.": "국가별 규제파일 내 직접 근거 미검출", "해당 국가/채널 규제 DB 없음. 고위험군 후보이므로 Pass 처리하지 않음.": "해당 국가 규제 DB 없음", "향료는 세부 구성성분 및 알레르겐 표시대상 여부 확인 필요. 자동 Pass 처리 금지.": "향료 세부 조성 및 알레르겐 확인 필요", "정제수/Water/Aqua 기본 Pass 처리": "정제수/Water/Aqua 기본 Pass 처리", "일본 수출용 제품 사용 불가 여부 확인 필요": "일본 수출용 제품 사용 불가 여부 확인 필요", } return replace_map.get(note, note) def process_single_ingredient( countries, single_query, single_amount, single_function, single_use_mfds_live=False, ): global RAW_SEARCH_LOGS RAW_SEARCH_LOGS = [] output_columns = ["국가", "검색어", "배합한도/금지", "상세 판정", "판정 출처", "비고"] try: if not countries: return pd.DataFrame(columns=output_columns), "❌ 검색할 국가를 선택해주세요." if not safe_str(single_query): return pd.DataFrame(columns=output_columns), "❌ 검색할 성분명, INCI, CAS.No 중 하나를 입력해주세요." material, component, amount_text = build_single_component_from_query( query=single_query, single_amount=single_amount, single_function=single_function, ) mfds_df = pd.DataFrame() terms = extract_single_lookup_terms(single_query, material, component) if single_use_mfds_live and terms: try: mfds_df, mfds_live_msg = mfds_live_lookup_terms( terms=terms, max_terms=1, headless=True, ) except Exception as e: mfds_df = pd.DataFrame() mfds_live_msg = f"MFDS 실시간 조회 실패: {e}" else: mfds_live_msg = "사용 안 함" ingredient_totals = defaultdict(float) ingredient_amount_parts = defaultdict(list) identity = get_identity_text(material, component) amount_float = component.get("amount_float") if amount_float is not None: 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_float ingredient_amount_parts[canonical].append(amount_float) result_rows = [] for country in countries: country_col = display_country(country) final_result = None source = "" critical_result = evaluate_critical_country_rule( country=country, material=material, component=component, ) if critical_result is not None: result_rows.append({ "국가": country_col, "검색어": shorten_for_table(single_query, 80), "배합한도/금지": critical_result.get("표시문구", "배합금지"), "상세 판정": critical_result.get("결과", ""), "판정 출처": "CRITICAL_COUNTRY_RULE", "비고": simplify_single_note(critical_result.get("비고", "-")), }) log_search_context( "single_ingredient", country, component, critical_result.get("결과", ""), "CRITICAL_COUNTRY_RULE", critical_result.get("비고", "-"), ) continue if is_always_pass_component(material, component): result_rows.append({ "국가": country_col, "검색어": shorten_for_table(single_query, 80), "배합한도/금지": "Pass", "상세 판정": NO_EVIDENCE_TEXT, "판정 출처": "ALWAYS_PASS_RULE", "비고": "정제수/Water/Aqua 기본 Pass 처리", }) log_search_context( "single_ingredient", country, component, "Pass", "ALWAYS_PASS_RULE", "정제수/Water/Aqua 기본 Pass 처리", ) continue fragrance_result = evaluate_plain_fragrance_rule( country=country, material=material, component=component, ) if fragrance_result is not None: final_result = fragrance_result source = "FRAGRANCE_RULE" if final_result is None and mfds_df is not None and not mfds_df.empty: mfds_result = evaluate_live_detail_rule( country=country, material=material, component=component, live_df=mfds_df, ) if mfds_result is not None: final_result = mfds_result source = "MFDS_LIVE" if final_result is None: file_result = evaluate_component_from_country_files_only( country=country, material=material, component=component, target_id="single_ingredient", ) if file_result is not None: final_result = file_result source = "COUNTRY_FILE_FAST" if final_result is None: local_result = evaluate_local_rules( country=country, material=material, component=component, ingredient_totals=ingredient_totals, ingredient_amount_parts=ingredient_amount_parts, ) if local_result is not None: final_result = local_result source = "LOCAL_RULE" if final_result is None: final_result = { "대표 INCI": safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-", "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "국가별 파일 및 식약처 조회 결과 내 제한 근거 없음", } source = "NO_EVIDENCE" display_result = make_single_display_result( final_result=final_result, country_col=country_col, component=component, ) detail_result = safe_str(final_result.get("결과", "")) note = simplify_single_note(final_result.get("비고", "-")) result_rows.append({ "국가": country_col, "검색어": shorten_for_table(single_query, 80), "배합한도/금지": display_result, "상세 판정": detail_result, "판정 출처": source, "비고": note, }) log_search_context( "single_ingredient", country, component, detail_result, source, final_result.get("비고", "-"), ) result_df = pd.DataFrame(result_rows) for col in output_columns: if col not in result_df.columns: result_df[col] = "" result_df = result_df[output_columns] msg = ( "✅ 단일 성분 검색 완료\n" f"- 검색어: {safe_str(single_query)}\n" f"- 선택 국가 수: {len(countries)}개\n" f"- MFDS 상태: {mfds_live_msg}\n" f"- MFDS 조회 대상: {', '.join(terms) if terms else '없음'}\n" "- 판정 방식: GPT 판정 없음, 업로드된 국가별 파일 row/line 직접 검색 + 식약처 체크 ON 시 실시간 결과 사용\n" "- 금지 성분: 함량 유무와 무관하게 배합금지 우선 표시\n" "- 식약처 브라우저 실패 시에도 국가별 파일 검색 결과는 계속 표시됨\n" "- MFDS 규제 매칭 0행은 식약처에서 금지/제한 상세가 확인되지 않았다는 의미\n" ) return result_df, msg except Exception as e: tb = traceback.format_exc() print(tb) empty_df = pd.DataFrame(columns=output_columns) return empty_df, f"❌ 단일 성분 검색 오류: {str(e)}\n\n{tb[-3000:]}" # ============================================================ # 계정 등록은 관리자에게 요청 / 관리자 승인 / 로그인 # ============================================================ USER_DB_PATH = os.getenv("USER_DB_PATH", str(BASE_DIR / "users.db")) ADMIN_EMAILS = { os.getenv("ADMIN_EMAIL", "jin2li@rebom.kr").strip().lower(), } DEFAULT_ADMIN_EMAIL = os.getenv("ADMIN_EMAIL", "jin2li@rebom.kr").strip().lower() DEFAULT_ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "qwer0515!") def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True): if not is_approved_user(user): return None, None, require_login_message() return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless) def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False): output_columns = ["국가", "검색어", "배합한도/금지", "상세 판정", "판정 출처", "비고"] if not is_approved_user(user): return pd.DataFrame(columns=output_columns), require_login_message() return process_single_ingredient( countries, single_query, single_amount, single_function, single_use_mfds_live, ) def auth_fn(username, password): username = str(username).strip().lower() password = str(password).strip() return USER_DB.get(username) == password # ============================================================ # Gradio 기본 auth 사용 시 내부 로그인 체크 우회 # ============================================================ def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True): return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless) def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False): return process_single_ingredient( countries, single_query, single_amount, single_function, single_use_mfds_live, ) # ============================================================ # 로그인 인증 # - Gradio 기본 로그인창 사용 # - USER_DB에 여러 아이디/비밀번호를 직접 등록 # ============================================================ USER_DB = { "jin2li@rebom.kr": "qwer0515!", # 사용자 추가 예시: # "yubin.p@rebom.kr": "원하는비밀번호", # "jkh@rebom.kr": "rebom123!", } def auth_fn(username, password): username = str(username).strip().lower() password = str(password).strip() return USER_DB.get(username) == password def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True): return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless) def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False): return process_single_ingredient( countries, single_query, single_amount, single_function, single_use_mfds_live, ) # ============================================================ # 로그인 인증 # - Gradio 기본 로그인창 사용 # - 아래 USER_DB에 메일/비밀번호를 직접 등록 # ============================================================ # 사용자 추가 방법: # USER_DB 안에 아래 형식으로 한 줄씩 추가하세요. # "메일주소": "비밀번호", # ============================================================ USER_DB = { "jin2li@rebom.kr": "qwer0515!", # 사용자 등록 예시: # "yubin.p@rebom.kr": "123456!", # "jkh@rebom.kr": "rebom123!", } def auth_fn(username, password): username = str(username).strip().lower() password = str(password).strip() return USER_DB.get(username) == password # Gradio 기본 auth를 통과한 사용자는 이미 인증된 상태이므로 내부 로그인 체크를 하지 않는다. def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True): return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless) def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False): return process_single_ingredient( countries, single_query, single_amount, single_function, single_use_mfds_live, ) # ============================================================ # 로그인 인증 # - Gradio 기본 로그인창 사용 # - 아래 USER_DB에 메일/비밀번호를 직접 등록 # ============================================================ USER_DB = { "jin2li@rebom.kr": "qwer0515!", # 사용자 등록 예시: # "yubin.p@rebom.kr": "123456!", # "jkh@rebom.kr": "rebom123!", } def auth_fn(username, password): username = str(username).strip().lower() password = str(password).strip() return USER_DB.get(username) == password def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True): return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless) def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False): return process_single_ingredient( countries, single_query, single_amount, single_function, single_use_mfds_live, ) # ============================================================ # 로그인 인증 # - Gradio 기본 로그인창 사용 # - 아래 USER_DB에 메일/비밀번호를 직접 등록 # ============================================================ USER_DB = { "jin2li@rebom.kr": "qwer0515!", # 사용자 등록 예시: # "yubin.p@rebom.kr": "123456!", # "jkh@rebom.kr": "rebom123!", } def auth_fn(username, password): username = str(username).strip().lower() password = str(password).strip() return USER_DB.get(username) == password def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True): return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless) def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False): return process_single_ingredient( countries, single_query, single_amount, single_function, single_use_mfds_live, ) # ============================================================ # 로그인 인증 # - Gradio 기본 로그인창 사용 # - 아래 USER_DB에 메일/비밀번호를 직접 등록 # ============================================================ # 로그인 인증 # - Gradio 기본 로그인창 사용 # - 아래 USER_DB에 메일/비밀번호를 직접 등록 # ============================================================ # 사용자 추가 방법: # USER_DB 안에 "아이디": "비밀번호", 형식으로 한 줄씩 추가하세요. # 각 줄 끝에는 콤마(,)를 붙이는 것을 권장합니다. # ============================================================ USER_DB = { "jin2li@rebom.kr": "qwer0515!", "jkh@rebom.kr": "rebom123!", "admin": "rebom123!", # 사용자 등록 예시: # "yubin.p@rebom.kr": "123456!", } def auth_fn(username, password): username = str(username).strip().lower() password = str(password).strip() return USER_DB.get(username) == password def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True): return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless) def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False): return process_single_ingredient( countries, single_query, single_amount, single_function, single_use_mfds_live, ) # ============================================================ # STRUCTURED FOLDER SCREENING PATCH V5.1 # 기존 UI/로그인/엑셀 출력 형태는 유지하고, 판정 엔진만 폴더 구조 기준으로 재정의 # ============================================================ SOURCE_ONLY_MODE = True TREAT_POSITIVE_LIST_AS_PASS = True V51_PROHIBITED_TERMS = [ "배합금지", "사용금지", "사용 금지", "금지원료", "금지 원료", "금지성분", "금지 성분", "prohibited", "banned", "not allowed", "shall not be used", "must not be used", "shall not contain", "must not contain", "forbidden", ] V51_RESTRICTED_TERMS = [ "배합한도", "배합 한도", "사용한도", "사용 한도", "사용제한", "사용 제한", "제한사항", "제한 사항", "제한성분", "제한 성분", "restricted", "restriction", "maximum concentration", "maximum amount", "max concentration", "not exceeding", "not exceed", "limit", "limits", ] V51_FALSE_LIMIT_CONTEXT_TERMS = [ "label", "labelling", "labeling", "라벨", "표시", "warning", "경고", "allergen", "알레르겐", "impurity", "impurities", "불순물", "contaminant", "contaminants", "오염물질", "test method", "시험법", "시험", "analysis", "분석", "purity", "순도", "검출한계", "관리값", "관리치", "peroxide value", "safe harbor", "노출량", ] V51_REFERENCE_FOLDER_TERMS = [ "reference", "archive", "test_method", "test-method", "시험방법", "functional_cosmetics_reference", "safety_assessment", "historical_use", "used_ingredient_inventory", "regulatory_framework", "ingredient_review_procedure", "labeling_advertising_reference", "microbiological_quality", ] V51_IMPURITY_FOLDER_TERMS = [ "impurity", "impurities", "contaminant", "contaminants", "contaminant_impurity_limits", "colorants_impurity_reference", "위험물질", "불순물", "오염물질", ] V51_RETAILER_TERMS = ["retailer", "sephora", "target", "ulta", "clean_standard", "clean_formula_restriction"] V51_PROP65_TERMS = ["prop65", "proposition_65", "california_prop65", "california_prop65_warning"] V51_VOLUNTARY_TERMS = ["voluntary", "jcia", "자율", "자숙", "자제", "voluntary_restriction", "voluntary_silicone_restriction"] V51_LABELING_TERMS = ["fragrance_allergen_labelling", "fragrance_allergen_labeling", "labeling", "labelling", "표시"] def _v51_text_has_any(text, terms): text = safe_str(text) low = text.lower() compact = normalize_compact(text) for term in terms: term = safe_str(term) if not term: continue if term.lower() in low: return True if normalize_compact(term) and normalize_compact(term) in compact: return True return False def _v51_path_text(record): source_file = safe_str(record.get("source_file", "")) sheet = safe_str(record.get("sheet", "")) return f"{source_file}\n{sheet}".replace("\\", "/") def _v51_folder_category(country, record): """ 폴더명/파일명 기준의 1차 분류. 핵심: reference/impurity/retailer/Prop65/voluntary는 법정 배합금지·한도와 분리한다. """ path_text = _v51_path_text(record) low = path_text.lower() compact = normalize_compact(path_text) if _v51_text_has_any(path_text, V51_PROP65_TERMS): return "nonlegal_prop65" if _v51_text_has_any(path_text, V51_RETAILER_TERMS): return "nonlegal_retailer" if _v51_text_has_any(path_text, V51_IMPURITY_FOLDER_TERMS): return "nonlegal_impurity" if _v51_text_has_any(path_text, V51_VOLUNTARY_TERMS): return "nonlegal_voluntary" if _v51_text_has_any(path_text, V51_LABELING_TERMS): return "nonlegal_labeling" if _v51_text_has_any(path_text, V51_REFERENCE_FOLDER_TERMS): return "reference" # 법정 금지/제한 폴더 if "/prohibited/" in low or low.startswith("prohibited/") or "annex_ii" in low or "annex-ii" in low or "annex ii" in low: return "legal_prohibited" if "/restricted/" in low or low.startswith("restricted/") or "annex_iii" in low or "annex-iii" in low or "annex iii" in low: return "legal_restricted" # 한국 별표 파일명 보정 if "annex_1_prohibited" in low or "별표1" in compact or "별표 1" in path_text: return "legal_prohibited" if "annex_2_restricted" in low or "restricted_ingredients" in low or "별표2" in compact or "별표 2" in path_text: return "legal_restricted" # Positive list 계열 positive_markers = [ "positive_colorants", "positive_colorant", "positive_preservatives", "positive_preservative", "positive_uv_filters", "positive_uv", "colorants_permitted", "permitted_colorants", "annex_iv", "annex-v", "annex_v", "annex_vi", "annex-vi", "annex iv", "annex v", "annex vi", "colorant", "colorants", "preservative", "preservatives", "uv_filter", "uv_filters", "uv filters", "허용색소", "허용 색소", "tar_colorants_permitted", ] if _v51_text_has_any(path_text, positive_markers): return "positive_list" # ASEAN annexes_main_screening, Japan cosmetic_standards_main 같이 한 파일에 여러 부속서가 들어간 경우 if "annexes_main_screening" in low or "cosmetic_standards_main" in low or "standards_for_cosmetics" in low: return "legal_mixed" return "unknown" def _v51_is_glycerin_deg_impurity_record(country, record, component): """ 일본 Standards for Cosmetics section 5 예외 처리. Glycerin 문장은 글리세린 배합금지가 아니라, 글리세린 원료 중 Diethylene Glycol 불순물 기준이다. 따라서 legal_mixed 문서 안에 있어도 금지/제한으로 분류하지 않는다. """ ckey = country_key(country) if ckey != "JAPAN": return False comp_text = " ".join([ safe_str(component.get("INCI Name", "")), safe_str(component.get("한글 성분명", "")), safe_str(component.get("CAS.No", "")), ]) comp_norm = normalize_compact(comp_text) is_glycerin_component = ( "glycerin" in comp_norm or "glycerol" in comp_norm or "글리세린" in comp_norm or "글리세롤" in comp_norm or "56-81-5" in comp_text ) if not is_glycerin_component: return False text = safe_str(record.get("text", "")) low = text.lower() compact = normalize_compact(text) has_glycerin = "glycerin" in low or "glycerol" in low or "글리세린" in compact or "글리세롤" in compact has_deg = "diethylene glycol" in low or "디에틸렌글라이콜" in compact or "디에칠렌글리콜" in compact or "deg" in low has_impurity_limit = "0.1g" in compact or "0.1 g" in low or "less than" in low or "이하" in text or "미만" in text return has_glycerin and has_deg and has_impurity_limit def _v51_record_type(country, record, component=None): if component is not None and _v51_is_glycerin_deg_impurity_record(country, record, component): return "nonlegal_impurity" category = _v51_folder_category(country, record) text = safe_str(record.get("text", "")) path_text = _v51_path_text(record) combined = path_text + "\n" + text[:1500] if category in ["nonlegal_prop65", "nonlegal_retailer", "nonlegal_impurity", "nonlegal_voluntary", "nonlegal_labeling", "reference"]: return category if category in ["legal_prohibited", "legal_restricted", "positive_list"]: return category # mixed legal file 내부 문맥 보정 if category == "legal_mixed": if _v51_text_has_any(combined, ["appendix 1", "annex ii", "prohibited", "금지", "사용할 수 없는 원료"]): return "legal_prohibited" if _v51_text_has_any(combined, ["appendix 2", "annex iii", "restricted", "제한", "배합한도", "maximum amount"]): return "legal_restricted" if _v51_text_has_any(combined, ["appendix 3", "appendix 4", "annex iv", "annex v", "annex vi", "preservative", "uv absorber", "uv filter", "tar colors", "색소", "보존제", "자외선"]): return "positive_list" return "reference" # 폴더명이 불명확한 경우 문맥만으로 매우 보수적으로 판단 if _v51_text_has_any(combined, V51_PROHIBITED_TERMS): return "legal_prohibited" if _v51_text_has_any(combined, V51_RESTRICTED_TERMS): return "legal_restricted" if _v51_text_has_any(combined, ["positive list", "permitted", "허용목록", "허용 목록", "coloring agents", "preservatives", "uv filters"]): return "positive_list" return "unknown" def _v51_component_match_in_record(record_text, terms): record_text = safe_str(record_text) if not record_text: return False for term in terms: term = safe_str(term) if not term or len(normalize_compact(term)) < 3: continue if is_broad_lookup_term(term): continue if is_cas_like(term): found_cas = re.findall(r"\d{2,7}-\d{2}-\d", record_text) if normalize_compact(term) in [normalize_compact(x) for x in found_cas]: return True continue if exact_ingredient_match(term, record_text): return True return False def extract_limit_condition_from_context(context): """ V5.1: 실제 배합한도/사용조건만 추출. 표시기준, 향료 알레르겐 표시 threshold, 불순물 ppm, Prop65 노출/경고 기준은 배합한도에서 제외. """ text = safe_str(context) compact = re.sub(r"\s+", " ", text).strip() if not compact: return "", "" if _v51_text_has_any(compact, V51_FALSE_LIMIT_CONTEXT_TERMS): # 단, restricted 폴더에서 %가 명확히 있고 label/impurity가 아닌 경우만 아래에서 살릴 여지가 있으나 # 여기서는 오판 방지를 우선한다. return "", "" if not _v51_text_has_any(compact, V51_RESTRICTED_TERMS): return "", "" limits = [] for pat in [ r"([0-9]+(?:\.[0-9]+)?\s*%)", r"([0-9]+(?:\.[0-9]+)?\s*g\s*/\s*100\s*g)", r"([0-9]+(?:\.[0-9]+)?\s*g\s+per\s+100\s*g)", ]: for m in re.finditer(pat, compact, flags=re.IGNORECASE): v = m.group(1).replace(" ", "") if v not in limits: limits.append(v) condition_lines = [] condition_keywords = [ "leave-on", "rinse-off", "washed away", "not used for mucosa", "mucosa", "oral", "보존제", "방부제", "자외선", "색소", "점막", "구강", "사용조건", "사용 조건", "condition", "제품", "type", "parts", "warning", "주의", ] for line in [safe_str(x) for x in text.splitlines() if safe_str(x)]: line_low = line.lower() if any(k.lower() in line_low for k in condition_keywords): cleaned = re.sub(r"\s+", " ", line).strip() if cleaned not in condition_lines: condition_lines.append(cleaned) return ", ".join(limits[:5]), " / ".join(condition_lines[:5])[:700] def normalize_formula_country_text(text, country_col="", inci_name="", amount_text=""): text = safe_str(text) if not text or text in ["-", NO_EVIDENCE_TEXT, "Pass", "PASS", "pass"]: return "Pass" if "Prop 65" in text or "경고표시" in text: return "경고표시 검토" if "Clean" in text or "리테일러" in text or "SEPHORA" in text or "TARGET" in text or "ULTA" in text: return NEED_CHECK_TEXT if "불순물" in text or "오염물질" in text or "impurity" in text.lower() or "contaminant" in text.lower(): return "불순물/오염물질 확인" if "자율기준" in text or "자제" in text or "자숙" in text or "voluntary" in text.lower(): return "자율기준 확인" if "표시" in text or "label" in text.lower() or "allergen" in text.lower(): return "표시기준 확인" if _v51_text_has_any(text, V51_PROHIBITED_TERMS): return "배합금지" limit_text, condition_text = extract_limit_condition_from_context(text) if limit_text: return f"배합한도: {limit_text}" if _v51_text_has_any(text, V51_RESTRICTED_TERMS): return NEED_CHECK_TEXT return "Pass" def evaluate_critical_country_rule(country, material, component): if SOURCE_ONLY_MODE: return None return None def evaluate_plain_fragrance_rule(country, material, component): if SOURCE_ONLY_MODE: return None return None def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts): if SOURCE_ONLY_MODE: return None return None def _v51_nonlegal_result(kind, country, component, best, target_id=""): country_col = display_country(country) representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-" context = safe_str(best.get("text", "")) src = f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}" if kind == "nonlegal_prop65": result = { "대표 INCI": representative, "결과": f"{country_col}(CA Prop 65): 경고표시 검토 필요", "표시문구": "경고표시 검토", "비고": "Proposition 65 등재/관련 물질. 캘리포니아 판매 시 노출량·세이프하버·경고표시 필요 여부 검토. " + src, } log_search_context(target_id, country, component, result["결과"], "V51_NONLEGAL_PROP65_WARNING", result["비고"]) return result if kind == "nonlegal_retailer": retailer = "리테일러" path = _v51_path_text(best).lower() if "sephora" in path: retailer = "SEPHORA" elif "target" in path: retailer = "TARGET" elif "ulta" in path: retailer = "ULTA" result = { "대표 INCI": representative, "결과": f"{retailer}: Clean 기준 확인 필요", "표시문구": NEED_CHECK_TEXT, "비고": "국가 법정 배합금지/한도가 아니라 리테일러 클린 기준. " + src, } log_search_context(target_id, country, component, result["결과"], "V51_NONLEGAL_RETAILER_CLEAN", result["비고"]) return result if kind == "nonlegal_impurity": result = { "대표 INCI": representative, "결과": f"{country_col}: 불순물/오염물질 기준 확인 필요", "표시문구": "불순물/오염물질 확인", "비고": "원료/완제품의 불순물·오염물질 기준이며 배합한도 아님. " + src, } log_search_context(target_id, country, component, result["결과"], "V51_NONLEGAL_IMPURITY_REFERENCE", result["비고"]) return result if kind == "nonlegal_voluntary": result = { "대표 INCI": representative, "결과": f"{country_col}: 자율기준 확인 필요", "표시문구": "자율기준 확인", "비고": "법정 배합금지가 아니라 업계 자율기준/사용 자제·자숙 기준. " + src, } log_search_context(target_id, country, component, result["결과"], "V51_NONLEGAL_VOLUNTARY", result["비고"]) return result if kind == "nonlegal_labeling": result = { "대표 INCI": representative, "결과": f"{country_col}: 표시기준 확인 필요", "표시문구": "표시기준 확인", "비고": "표시/라벨링 기준이며 배합한도 아님. " + src, } log_search_context(target_id, country, component, result["결과"], "V51_NONLEGAL_LABELING", result["비고"]) return result result = { "대표 INCI": representative, "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "참고자료에서 성분명은 확인되었으나 금지/제한 판정자료 아님. " + src, } log_search_context(target_id, country, component, result["결과"], "V51_REFERENCE_NAME_ONLY_PASS", result["비고"]) return result def evaluate_component_from_uploaded_source_records(country, material, component, target_id=""): terms = source_match_terms_for_component(material, component) representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-" if not terms: return None records, status = build_country_source_record_index(country) hits = [] for rec in records: rec_text = safe_str(rec.get("text", "")) if _v51_component_match_in_record(rec_text, terms): hits.append(rec) if not hits: return None priority = { "legal_prohibited": 100, "legal_restricted": 90, "positive_list": 70, "nonlegal_retailer": 60, "nonlegal_prop65": 58, "nonlegal_voluntary": 56, "nonlegal_impurity": 54, "nonlegal_labeling": 52, "reference": 20, "unknown": 10, } typed_hits = [(rec, _v51_record_type(country, rec, component)) for rec in hits] typed_hits.sort(key=lambda x: priority.get(x[1], 0), reverse=True) best, kind = typed_hits[0] context = safe_str(best.get("text", "")) src_note = f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}" country_col = display_country(country) if kind == "legal_prohibited": result = { "대표 INCI": representative, "결과": f"{country_col}: 업로드 법정 금지 폴더/파일에서 성분 직접 확인", "표시문구": "배합금지", "비고": src_note, } log_search_context(target_id, country, component, result["결과"], "V51_LEGAL_PROHIBITED", result["비고"]) return result if kind == "legal_restricted": limit_text, condition_text = extract_limit_condition_from_context(context) result = { "대표 INCI": representative, "결과": f"{country_col}: 업로드 법정 제한 폴더/파일에서 성분 직접 확인" + (f" / 한도 {limit_text}" if limit_text else " / 한도·조건 확인 필요") + (f" / 조건: {condition_text}" if condition_text else ""), "표시문구": f"배합한도: {limit_text}" if limit_text else NEED_CHECK_TEXT, "비고": src_note, } log_search_context(target_id, country, component, result["결과"], "V51_LEGAL_RESTRICTED", result["비고"]) return result if kind == "positive_list": limit_text, condition_text = extract_limit_condition_from_context(context) if limit_text: result = { "대표 INCI": representative, "결과": f"{country_col}: 허용목록에서 성분 직접 확인 / 한도 {limit_text}" + (f" / 조건: {condition_text}" if condition_text else ""), "표시문구": f"배합한도: {limit_text}", "비고": src_note, } log_search_context(target_id, country, component, result["결과"], "V51_POSITIVE_LIST_LIMIT", result["비고"]) return result result = { "대표 INCI": representative, "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "허용목록에서 성분명 확인. 명확한 배합한도 수치 근거 없음. " + src_note, } log_search_context(target_id, country, component, result["결과"], "V51_POSITIVE_LIST_PASS", result["비고"]) return result if kind.startswith("nonlegal_") or kind == "reference": return _v51_nonlegal_result(kind, country, component, best, target_id) result = { "대표 INCI": representative, "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "성분명은 업로드 파일에서 발견되었으나 금지/제한/한도 근거 없음. " + src_note, } log_search_context(target_id, country, component, result["결과"], "V51_SOURCE_NAME_ONLY_PASS", result["비고"]) return result def evaluate_component_from_country_files_only(country, material, component, target_id=""): representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-" if is_always_pass_component(material, component): result = { "대표 INCI": representative if representative != "-" else "Water", "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "정제수/Water/Aqua 기본 Pass 처리", } log_search_context(target_id, country, component, result["결과"], "ALWAYS_PASS_RULE", result["비고"]) return result source_result = evaluate_component_from_uploaded_source_records(country, material, component, target_id) if source_result is not None: return source_result result = { "대표 INCI": representative, "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "업로드된 국가별 파일 내 현재 성분 직접 근거 없음", } log_search_context(target_id, country, component, result["결과"], "V51_SOURCE_NO_HIT_PASS", result["비고"]) return result def is_country_result_issue(text): text = safe_str(text) if not text or text in ["-", NO_EVIDENCE_TEXT, "Pass", "PASS", "pass"]: return False if "허용목록" in text and not _v51_text_has_any(text, V51_RESTRICTED_TERMS + V51_PROHIBITED_TERMS): return False issue_markers = [ "배합금지", "금지", "배합한도", "한도", "확인 필요", "경고표시", "Clean 기준", "불순물", "오염물질", "자율기준", "표시기준", "부적합", "재검토", "사용 불가", "사용불가", ] return _v51_text_has_any(text, issue_markers + V51_PROHIBITED_TERMS + V51_RESTRICTED_TERMS) # ============================================================ # END STRUCTURED FOLDER SCREENING PATCH V5.1 # ============================================================ # ============================================================ # STRUCTURED FOLDER SCREENING PATCH V5.2 # 2026-06: US 폴더명 반영 + 주요 오판정 차단 # - FDA 표기를 US로 통일 # - 일본 Glycerin 배합금지 오판정 차단 # - EU Carbomer / Adenosine 배합금지 오판정 차단 # - Phenoxyethanol: EU/ASEAN/KOREA/JAPAN 보존제 최대 1.0% 한도로 고정 보정 # ============================================================ COUNTRY_ORDER = ["ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "US", "JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA"] COUNTRY_DISPLAY.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "US"}) COUNTRY_FOLDER_ALIASES.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "us"}) BLOCKED_PATHS = [str(BASE_DIR / c) for c in COUNTRY_ORDER] + [str(BASE_DIR / "us")] + [str(BASE_DIR/FAISS_CACHE_DIR), str(BASE_DIR/'.env'), str(BASE_DIR/'__pycache__')] def country_key(country): t = safe_str(country).upper().replace("_", " ").replace("-", " ") t = re.sub(r"\s+", " ", t).strip() m = { "한국": "KOREA", "KOREA": "KOREA", "KR": "KOREA", "EU": "EU", "EUROPE": "EU", "유럽": "EU", "EU FUTURE": "EU_FUTURE", "EU (FUTURE)": "EU_FUTURE", "JAPAN": "JAPAN", "JP": "JAPAN", "일본": "JAPAN", "CHINA": "CHINA", "CN": "CHINA", "중국": "CHINA", "USA": "US", "US": "US", "미국": "US", "FDA": "US", "ASEAN": "ASEAN", "아세안": "ASEAN", "UK": "UK", "영국": "UK", "SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA", "CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO", } return m.get(t, t) def display_country(country): c = country_key(country) if c == "US": return "US" return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), c)) def _v52_component_blob(material, component): parts = [] for obj in [material or {}, component or {}]: if isinstance(obj, dict): for k, v in obj.items(): if k in ["INCI Name", "한글 성분명", "CAS.No", "CAS", "성분명", "표준명", "영문명", "Raw", "원료명"]: parts.append(safe_str(v)) return " ".join([p for p in parts if p]) def _v52_is_component(material, component, aliases): blob = _v52_component_blob(material, component) low = blob.lower() compact = normalize_compact(blob) for alias in aliases: a = safe_str(alias) if not a: continue if is_cas_like(a) and a in blob: return True ac = normalize_compact(a) if len(ac) >= 3 and ac in compact: return True if a.lower() in low: return True return False def _v52_result(representative, result_text, formula_text, note, target_id, country, component, source_tag): out = { "대표 INCI": representative, "결과": result_text, "표시문구": formula_text, "비고": note, } log_search_context(target_id, country, component, out["결과"], source_tag, out["비고"]) return out def _v52_known_correction(country, material, component, target_id=""): ckey = country_key(country) cdisp = display_country(country) representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-" # Phenoxyethanol은 EU/ASEAN/한국/일본에서 보존제로 최대 1.0% 한도. 한국 배합금지 아님. if _v52_is_component(material, component, ["phenoxyethanol", "phenoxy ethanol", "페녹시에탄올", "페녹시 에탄올", "122-99-6"]): if ckey in ["EU", "ASEAN", "KOREA", "JAPAN"]: return _v52_result( representative or "Phenoxyethanol", f"{cdisp}: 보존제 사용한도 최대 1.0%", "배합한도: 1.0%", "Phenoxyethanol/페녹시에탄올은 해당 국가 기준에서 배합금지가 아니라 보존제 사용한도 1.0%로 처리. restricted/positive preservative 문맥을 prohibited로 오판정하지 않도록 보정.", target_id, country, component, "V52_FIXED_PHENOXYETHANOL_1_PERCENT", ) # 일본 Glycerin 문구는 Diethylene Glycol 불순물 기준. 글리세린 배합금지/배합한도 아님. if ckey == "JAPAN" and _v52_is_component(material, component, ["glycerin", "glycerol", "글리세린", "글리세롤", "56-81-5"]): return _v52_result( representative or "Glycerin", "일본: 글리세린 원료 불순물 기준 확인 필요", "불순물/오염물질 확인", "일본 Standards for Cosmetics의 'Glycerin mixed with cosmetics should contain diethylene glycol less than 0.1g per 100g glycerin' 문구는 글리세린 배합금지가 아니라 글리세린 원료 중 Diethylene Glycol 불순물 기준. 배합금지/배합한도로 판정하지 않음.", target_id, country, component, "V52_JP_GLYCERIN_DEG_IMPURITY_NOT_PROHIBITED", ) # EU Carbomer는 성분명 자체를 Annex II 배합금지로 단정하지 않는다. # microplastics/고분자 미립자 해당성은 제품 형태·입자성·불용성·입자크기 기준 별도 검토. if ckey == "EU" and _v52_is_component(material, component, ["carbomer", "카보머", "카보폴", "9003-01-4", "9007-20-9"]): return _v52_result( representative or "Carbomer", "EU: Microplastics 해당성 확인 필요 / Carbomer 자체 배합금지 아님", NEED_CHECK_TEXT, "Carbomer는 EU Annex II 배합금지 성분으로 자동 판정하지 않음. REACH microplastics는 특정 폴리머명을 일괄 금지하는 구조가 아니라 고체·불용성·입자크기·사용형태 등 synthetic polymer microparticles 해당성을 검토하는 기준으로 분리.", target_id, country, component, "V52_EU_CARBOMER_MICROPLASTICS_REVIEW_NOT_PROHIBITED", ) # EU Adenosine은 Annex II/III 직접 근거 없으면 Pass. 한국 기능성 로직이 EU로 번지지 않게 차단. if ckey == "EU" and _v52_is_component(material, component, ["adenosine", "아데노신", "58-61-7"]): return _v52_result( representative or "Adenosine", NO_EVIDENCE_TEXT, "Pass", "EU 금지/제한 원문에서 Adenosine 직접 금지·제한 근거 없음. 한국 기능성화장품 성분 로직을 EU 배합금지로 적용하지 않도록 보정.", target_id, country, component, "V52_EU_ADENOSINE_PASS_NOT_PROHIBITED", ) return None # V5.2: mixed legal 문서 내부 분류 보정. def _v51_record_type(country, record, component=None): if component is not None and _v51_is_glycerin_deg_impurity_record(country, record, component): return "nonlegal_impurity" category = _v51_folder_category(country, record) text = safe_str(record.get("text", "")) path_text = _v51_path_text(record) combined = path_text + "\n" + text[:1500] # EU microplastics / CELEX 2023/2055 문서는 성분명 직접 배합금지 파일로 쓰지 않는다. if country_key(country) == "EU" and _v51_text_has_any(combined, ["microplastic", "microplastics", "synthetic polymer microparticles", "celex_32023r2055", "2023r2055", "2023/2055"]): return "reference" if category in ["nonlegal_prop65", "nonlegal_retailer", "nonlegal_impurity", "nonlegal_voluntary", "nonlegal_labeling", "reference"]: return category if category in ["legal_prohibited", "legal_restricted", "positive_list"]: return category if category == "legal_mixed": # 일본 Standards for Cosmetics: Appendix 3/4 보존제·UV는 positive_list가 우선. if _v51_text_has_any(combined, ["appendix 3", "appendix 4", "preservative", "preservatives", "uv absorber", "uv absorbers", "uv filter", "uv filters", "tar colors", "색소", "보존제", "자외선"]): return "positive_list" if _v51_text_has_any(combined, ["appendix 2", "annex iii", "restricted", "제한", "배합한도", "maximum amount"]): return "legal_restricted" if _v51_text_has_any(combined, ["appendix 1", "annex ii", "prohibited", "금지", "사용할 수 없는 원료"]): return "legal_prohibited" return "reference" if _v51_text_has_any(combined, V51_PROHIBITED_TERMS): return "legal_prohibited" if _v51_text_has_any(combined, V51_RESTRICTED_TERMS): return "legal_restricted" if _v51_text_has_any(combined, ["positive list", "permitted", "허용목록", "허용 목록", "coloring agents", "preservatives", "uv filters"]): return "positive_list" return "unknown" def evaluate_component_from_country_files_only(country, material, component, target_id=""): representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-" if is_always_pass_component(material, component): result = { "대표 INCI": representative if representative != "-" else "Water", "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "정제수/Water/Aqua 기본 Pass 처리", } log_search_context(target_id, country, component, result["결과"], "ALWAYS_PASS_RULE", result["비고"]) return result correction = _v52_known_correction(country, material, component, target_id) if correction is not None: return correction source_result = evaluate_component_from_uploaded_source_records(country, material, component, target_id) if source_result is not None: return source_result result = { "대표 INCI": representative, "결과": NO_EVIDENCE_TEXT, "표시문구": "Pass", "비고": "업로드된 국가별 파일 내 현재 성분 직접 근거 없음", } log_search_context(target_id, country, component, result["결과"], "V52_SOURCE_NO_HIT_PASS", result["비고"]) return result # ============================================================ # END STRUCTURED FOLDER SCREENING PATCH V5.2 # ============================================================ # ============================================================ # SOURCE TABLE ROW ENGINE PATCH V6 # 목적: 성분별 예외 하드코딩이 아니라 폴더/표/행 기반으로만 법정 금지·한도 판정 # 원칙: # - 금지: prohibited 폴더 또는 법정 Annex/Appendix 금지 섹션에서 성분이 같은 행/근접 행에 직접 있을 때만 # - 한도: restricted/positive_preservatives/positive_uv/positive_colorants 행에 성분과 수치가 직접 있을 때만 # - reference/impurity/labeling/retailer/Prop65/voluntary 문서는 법정 금지·한도 생성 금지 # - 파일명/문서 전체의 prohibited/limit 키워드만으로 성분 판정 금지 # ============================================================ SOURCE_ONLY_MODE = True TREAT_POSITIVE_LIST_AS_PASS = True COUNTRY_ORDER = ["ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "US", "us", "JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA"] COUNTRY_DISPLAY.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "US"}) COUNTRY_FOLDER_ALIASES.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "us", "Us": "US"}) 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__')] def country_key(country): t = safe_str(country).upper().replace("_", " ").replace("-", " ") t = re.sub(r"\s+", " ", t).strip() m = { "한국": "KOREA", "KOREA": "KOREA", "KR": "KOREA", "EU": "EU", "EUROPE": "EU", "유럽": "EU", "EU FUTURE": "EU_FUTURE", "EU (FUTURE)": "EU_FUTURE", "JAPAN": "JAPAN", "JP": "JAPAN", "일본": "JAPAN", "CHINA": "CHINA", "CN": "CHINA", "중국": "CHINA", "USA": "US", "US": "US", "미국": "US", "FDA": "US", "ASEAN": "ASEAN", "아세안": "ASEAN", "UK": "UK", "영국": "UK", "SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA", "CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO", } return m.get(t, t) def display_country(country): c = country_key(country) if c == "US": return "US" if c == "KOREA": return "Korea" if c == "JAPAN": return "일본" if c == "CHINA": return "중국" return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), c)) def _v6_path_text(record): return f"{safe_str(record.get('source_file',''))}\n{safe_str(record.get('sheet',''))}".replace('\\', '/') def _v6_has(text, terms): low = safe_str(text).lower() comp = normalize_compact(text) for term in terms: term = safe_str(term) if not term: continue if term.lower() in low: return True tc = normalize_compact(term) if tc and tc in comp: return True return False def _v6_folder_category(record): """ 오직 폴더/파일 경로만으로 문서 성격을 분류한다. 문서 본문 키워드만으로 legal_prohibited/legal_restricted를 만들지 않는다. """ path = _v6_path_text(record) low = path.lower() compact = normalize_compact(path) # 법정 판정 제외 계열을 최우선 분리 if _v6_has(path, ["prop65", "proposition_65", "proposition 65", "california_prop65", "california_prop65_warning"]): return "nonlegal_prop65" if _v6_has(path, ["retailer", "sephora", "target", "ulta", "clean_standard", "clean"]): return "nonlegal_retailer" if _v6_has(path, ["impurity", "impurities", "contaminant", "contaminants", "contaminant_impurity_limits", "colorants_impurity_reference", "위험물질", "불순물", "오염물질"]): return "nonlegal_impurity" if _v6_has(path, ["voluntary", "jcia", "자율", "자숙", "자제", "voluntary_restriction", "voluntary_silicone_restriction"]): return "nonlegal_voluntary" if _v6_has(path, ["fragrance_allergen_labelling", "fragrance_allergen_labeling", "labeling", "labelling", "표시", "advertising"]): return "nonlegal_labeling" if _v6_has(path, ["microplastic", "microplastics", "synthetic_polymer", "celex_32023r2055", "2023r2055", "2023_2055"]): return "reference_microplastics" if _v6_has(path, ["reference", "archive", "test_method", "test-method", "시험방법", "functional_cosmetics_reference", "safety_assessment", "historical_use", "used_ingredient_inventory", "regulatory_framework", "ingredient_review_procedure", "human_cell_tissue_culture", "microbiological_quality"]): return "reference" # 법정 금지/제한 폴더 if "/prohibited/" in low or low.startswith("prohibited/") or "annex_ii_prohibited" in low or "annex ii prohibited" in low or "annex_1_prohibited" in low or "annex 1 prohibited" in low: return "legal_prohibited" if "별표1" in compact and ("사용할수없는" in compact or "prohibited" in low): return "legal_prohibited" if "/restricted/" in low or low.startswith("restricted/") or "annex_iii_restricted" in low or "annex iii restricted" in low or "annex_2_restricted" in low or "restricted_ingredients" in low: return "legal_restricted" if "별표2" in compact and ("제한" in compact or "restricted" in low): return "legal_restricted" # Positive list 계열: 허용목록이지 금지목록이 아님 if _v6_has(path, [ "positive_colorants", "positive_colorant", "positive_preservatives", "positive_preservative", "positive_uv_filters", "positive_uv", "colorants_permitted", "permitted_colorants", "tar_colorants_permitted", "annex_iv", "annex-iv", "annex iv", "annex_v", "annex-v", "annex v", "annex_vi", "annex-vi", "annex vi", "permitted_preservatives", "permitted_uv", "허용색소", "허용 색소", ]): return "positive_list" # 한 파일에 여러 Annex/Appendix가 들어있는 대표 법정 문서 if _v6_has(path, ["annexes_main_screening", "cosmetic_standards_main", "standards_for_cosmetics", "jp_standards_for_cosmetics", "asean_acd_annexes", "annexes-of-the-asean-cosmetic-directive"]): return "legal_mixed" return "unknown" def _v6_component_terms(material=None, component=None): terms = source_match_terms_for_component(material or {}, component or {}) clean = [] for t in terms: t = safe_str(t) if not t or is_broad_lookup_term(t): continue if len(normalize_compact(t)) < 3 and not is_cas_like(t): continue if t not in clean: clean.append(t) return clean def _v6_row_direct_match(record_text, terms): text = safe_str(record_text) if not text: return False found_cas = [normalize_compact(x) for x in re.findall(r"\d{2,7}-\d{2}-\d", text)] for term in terms: term = safe_str(term) if not term: continue if is_cas_like(term): if normalize_compact(term) in found_cas: return True continue if exact_ingredient_match(term, text): return True return False def _v6_is_component_alias(material, component, aliases): blob = " ".join([ safe_str(component.get("INCI Name", "")), safe_str(component.get("한글 성분명", "")), safe_str(component.get("CAS.No", "")), safe_str(material.get("Trade name(국문)", "")), safe_str(material.get("Trade name(영문)", "")), ]) return _v6_row_direct_match(blob, aliases) def _v6_is_jp_glycerin_impurity_record(country, record, material, component): if country_key(country) != "JAPAN": return False if not _v6_is_component_alias(material, component, ["glycerin", "glycerol", "글리세린", "글리세롤", "56-81-5"]): return False text = safe_str(record.get("text", "")) return _v6_has(text, ["diethylene glycol", "디에틸렌글라이콜", "디에칠렌글리콜"]) and _v6_has(text, ["0.1g", "0.1 g", "less than", "미만"]) def _v6_record_type(country, record, material=None, component=None): """ 최종 record 유형. V6에서는 문서 전체 키워드 fallback 금지. legal_mixed만 표/부속서 heading으로 내부 분류한다. """ folder_cat = _v6_folder_category(record) text = safe_str(record.get("text", "")) basis = _v6_path_text(record) + "\n" + text[:1500] if component is not None and _v6_is_jp_glycerin_impurity_record(country, record, material or {}, component or {}): return "nonlegal_impurity" if folder_cat in [ "legal_prohibited", "legal_restricted", "positive_list", "nonlegal_prop65", "nonlegal_retailer", "nonlegal_impurity", "nonlegal_voluntary", "nonlegal_labeling", "reference", "reference_microplastics", "unknown", ]: return folder_cat if folder_cat == "legal_mixed": ckey = country_key(country) # 일본 Standards for Cosmetics: Appendix 번호 기준으로만 판정 if ckey == "JAPAN": if _v6_has(basis, ["appendix 1"]): return "legal_prohibited" if _v6_has(basis, ["appendix 2"]): return "legal_restricted" if _v6_has(basis, ["appendix 3", "appendix 4", "tar colors", "preservatives", "uv absorbers", "uv filters"]): return "positive_list" return "reference" # ASEAN ACD Annexes: Annex 번호 기준으로만 판정 if ckey == "ASEAN": if _v6_has(basis, ["annex ii", "annex Ⅱ"]): return "legal_prohibited" if _v6_has(basis, ["annex iii", "annex Ⅲ"]): return "legal_restricted" if _v6_has(basis, ["annex iv", "annex Ⅳ", "annex vi", "annex Ⅵ", "annex vii", "annex Ⅶ"]): return "positive_list" return "reference" # EU 통합 annex 문서가 있을 경우도 Annex 번호 기준 if ckey == "EU": if _v6_has(basis, ["annex ii", "annex Ⅱ"]): return "legal_prohibited" if _v6_has(basis, ["annex iii", "annex Ⅲ"]): return "legal_restricted" if _v6_has(basis, ["annex iv", "annex Ⅳ", "annex v", "annex Ⅴ", "annex vi", "annex Ⅵ"]): return "positive_list" return "reference" return "reference" return "unknown" def _v6_extract_limit_condition_from_row(context): text = safe_str(context) flat = re.sub(r"\s+", " ", text).strip() if not flat: return "", "" # 불순물/오염물질 ppm/ng 등은 배합한도로 쓰지 않는다. if _v6_has(flat, ["impurity", "impurities", "contaminant", "contaminants", "불순물", "오염물질", "검출한계", "관리값", "관리치", "safe harbor", "exposure"]): if not re.search(r"\b\d+(?:\.\d+)?\s*%", flat): return "", "" limits = [] # % 한도 for m in re.finditer(r"\b(\d+(?:\.\d+)?)\s*%", flat): v = m.group(1).rstrip("0").rstrip(".") if "." in m.group(1) else m.group(1) item = f"{v}%" if item not in limits: limits.append(item) # g per 100 g = 사실상 % for m in re.finditer(r"\b(\d+(?:\.\d+)?)\s*g\s*(?:/|per)\s*100\s*g", flat, flags=re.IGNORECASE): v = m.group(1).rstrip("0").rstrip(".") if "." in m.group(1) else m.group(1) item = f"{v}%" if item not in limits: limits.append(item) # '1.0 g' 식 일본 표는 Appendix 3/4 row에서 사용됨. per 100g heading이 row에 없을 수 있어 제한적으로 살림. if not limits and _v6_has(flat, ["maximum amount", "maximum concentration", "배합한도", "사용한도", "ingredient per 100 g", "per 100g"]): for m in re.finditer(r"\b(\d+(?:\.\d+)?)\s*g\b", flat, flags=re.IGNORECASE): v = m.group(1).rstrip("0").rstrip(".") if "." in m.group(1) else m.group(1) item = f"{v}%" if item not in limits: limits.append(item) condition_lines = [] for line in [safe_str(x) for x in text.splitlines() if safe_str(x)]: if _v6_has(line, ["leave-on", "rinse-off", "washed away", "mucosa", "oral", "점막", "구강", "사용조건", "condition", "warning", "주의", "aerosol", "spray"]): if line not in condition_lines: condition_lines.append(line[:220]) condition = " / ".join(condition_lines[:3]) return "; ".join(limits[:5]), condition def _v6_result(representative, result_text, formula_text, note, target_id, country, component, source_tag): out = {"대표 INCI": representative, "결과": result_text, "표시문구": formula_text, "비고": note} log_search_context(target_id, country, component, out["결과"], source_tag, out["비고"]) return out def _v6_nonlegal_result(country, material, component, record, rtype, target_id=""): representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-" cdisp = display_country(country) context = safe_str(record.get("text", "")) src = f"[출처파일: {record.get('source_file','')}] [row: {record.get('row_index','')}] {context[:900]}" if rtype == "nonlegal_prop65": return _v6_result(representative, f"{cdisp}: CA Prop 65 경고표시 검토 필요", "경고표시 검토", src, target_id, country, component, "V6_NONLEGAL_PROP65_ONLY") if rtype == "nonlegal_retailer": return _v6_result(representative, f"{cdisp}: 리테일러 Clean 기준 확인", "Clean 기준 확인", src, target_id, country, component, "V6_RETAILER_CLEAN_ONLY") if rtype == "nonlegal_impurity": return _v6_result(representative, f"{cdisp}: 불순물/오염물질 기준 확인 필요", "불순물/오염물질 확인", src, target_id, country, component, "V6_IMPURITY_REFERENCE_ONLY") if rtype == "nonlegal_voluntary": return _v6_result(representative, f"{cdisp}: 자율기준 확인", "자율기준 확인", src, target_id, country, component, "V6_VOLUNTARY_REFERENCE_ONLY") if rtype == "nonlegal_labeling": return _v6_result(representative, f"{cdisp}: 표시기준 확인", "표시기준 확인", src, target_id, country, component, "V6_LABELING_REFERENCE_ONLY") if rtype == "reference_microplastics": if _v6_is_component_alias(material, component, ["carbomer", "카보머", "acrylates", "polymer", "폴리머"]): return _v6_result(representative, f"{cdisp}: Microplastics 해당성 확인 필요 / 성분명 자체 배합금지 아님", NEED_CHECK_TEXT, src, target_id, country, component, "V6_REFERENCE_MICROPLASTICS_NOT_PROHIBITED") return _v6_result(representative, NO_EVIDENCE_TEXT, "Pass", src, target_id, country, component, "V6_REFERENCE_ONLY_NO_LEGAL_CLASSIFICATION") return _v6_result(representative, NO_EVIDENCE_TEXT, "Pass", src, target_id, country, component, "V6_REFERENCE_ONLY_NO_LEGAL_CLASSIFICATION") def pick_best_source_record(records): priority = { "legal_prohibited": 100, "legal_restricted": 80, "positive_list": 60, "nonlegal_prop65": 45, "nonlegal_retailer": 40, "nonlegal_impurity": 35, "nonlegal_voluntary": 30, "nonlegal_labeling": 30, "reference_microplastics": 20, "reference": 10, "unknown": 0, } return sorted(records, key=lambda r: priority.get(r.get("v6_type", "unknown"), 0), reverse=True)[0] if records else None def evaluate_component_from_uploaded_source_records(country, material, component, target_id=""): """ V6 source-table-row engine. 성분명/CAS가 같은 row/window에 직접 있는 경우만 hit로 인정하고, 폴더/Annex/Appendix 구조가 법정 유형을 결정한다. """ terms = _v6_component_terms(material, component) representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-" if not terms: return None records, status = build_country_source_record_index(country) hits = [] for rec in records: if not _v6_row_direct_match(rec.get("text", ""), terms): continue rtype = _v6_record_type(country, rec, material, component) rec2 = dict(rec) rec2["v6_type"] = rtype hits.append(rec2) if not hits: return None best = pick_best_source_record(hits) rtype = best.get("v6_type", "unknown") context = safe_str(best.get("text", "")) src_note = f"[출처파일: {best.get('source_file','')}] [row: {best.get('row_index','')}] {context[:900]}" cdisp = display_country(country) if rtype == "legal_prohibited": return _v6_result( representative, f"{cdisp}: 법정 금지목록에서 성분 직접 확인", "배합금지", src_note, target_id, country, component, "V6_ROW_MATCH_PROHIBITED_FOLDER", ) if rtype == "legal_restricted": limit_text, condition_text = _v6_extract_limit_condition_from_row(context) formula = f"배합한도: {limit_text}" if limit_text else NEED_CHECK_TEXT result_text = f"{cdisp}: 법정 제한목록에서 성분 직접 확인" + (f" / 조건: {condition_text}" if condition_text else "") return _v6_result( representative, result_text, formula, src_note, target_id, country, component, "V6_ROW_MATCH_RESTRICTED_FOLDER", ) if rtype == "positive_list": limit_text, condition_text = _v6_extract_limit_condition_from_row(context) formula = f"배합한도: {limit_text}" if limit_text else "허용목록 등재 / 한도 확인 필요" result_text = f"{cdisp}: 허용목록에서 성분 직접 확인" + (f" / 조건: {condition_text}" if condition_text else "") source_tag = "V6_ROW_MATCH_POSITIVE_LIST_LIMIT" if limit_text else "V6_ROW_MATCH_POSITIVE_LIST" return _v6_result( representative, result_text, formula, src_note, target_id, country, component, source_tag, ) if rtype in ["nonlegal_prop65", "nonlegal_retailer", "nonlegal_impurity", "nonlegal_voluntary", "nonlegal_labeling", "reference", "reference_microplastics"]: return _v6_nonlegal_result(country, material, component, best, rtype, target_id) # unknown 폴더/파일은 성분명이 있어도 법정 금지·한도 판정을 만들지 않는다. return _v6_result( representative, NO_EVIDENCE_TEXT, "Pass", src_note + " / 파일 유형 미분류: 법정 금지·한도 자동판정 제외", target_id, country, component, "V6_UNKNOWN_SOURCE_NO_LEGAL_CLASSIFICATION", ) def evaluate_component_from_country_files_only(country, material, component, target_id=""): representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-" if is_always_pass_component(material, component): return _v6_result( representative if representative != "-" else "Water", NO_EVIDENCE_TEXT, "Pass", "정제수/Water/Aqua 기본 Pass 처리", target_id, country, component, "ALWAYS_PASS_RULE", ) source_result = evaluate_component_from_uploaded_source_records(country, material, component, target_id) if source_result is not None: return source_result return _v6_result( representative, NO_EVIDENCE_TEXT, "Pass", "업로드된 국가별 파일 내 현재 성분의 같은 행/근접 행 직접 근거 없음", target_id, country, component, "V6_NO_ROW_MATCH_PASS", ) def evaluate_critical_country_rule(country, material, component): if SOURCE_ONLY_MODE: return None return None def evaluate_plain_fragrance_rule(country, material, component): if SOURCE_ONLY_MODE: return None return None def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts): if SOURCE_ONLY_MODE: return None 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 if "허용목록" in text and not _v6_has(text, ["배합한도", "한도", "조건", "확인 필요"]): return False return _v6_has(text, [ "배합금지", "배합한도", "한도", "확인 필요", "경고표시", "Clean 기준", "불순물", "오염물질", "자율기준", "표시기준", "부적합", "재검토", "사용 불가", "사용불가", "Microplastics", ]) # ============================================================ # END SOURCE TABLE ROW ENGINE PATCH V6 # ============================================================ # ============================================================ # SOURCE TABLE ROW ENGINE PATCH V6.1 # 목적: V6 결과에서 확인된 오판정 보정 # 핵심 변경: # - 성분명 부분 문자열 매칭 금지 강화 # - Excel 행은 앞쪽 identity cell(성분명/INCI/CAS 영역)에서만 성분 hit 인정 # - 설명/Other/Warning/Coating 문장 속 성분명은 hit 제외 # - CAS가 있으면 CAS 완전일치 우선 # - 향료 알레르겐 표시 기준은 배합한도 아님 # - Formula sheet와 Summary sheet 집계 동기화 # ============================================================ V61_ENGINE_VERSION = "V6.2_JP_GLYCERIN_HARD_GUARD" def _v61_clean_cell(x): return re.sub(r"\s+", " ", safe_str(x)).strip() def _v61_split_cells(record_text): txt = safe_str(record_text) if " | " in txt: return [_v61_clean_cell(x) for x in txt.split(" | ") if _v61_clean_cell(x)] return [_v61_clean_cell(x) for x in txt.splitlines() if _v61_clean_cell(x)] def _v61_term_variants(term): term = _v61_clean_cell(term) if not term: return [] vals = [term] # 괄호/별표/각주 제거 variant vals.append(re.sub(r"\([^)]*\)", "", term).strip()) vals.append(re.sub(r"\*+", "", term).strip()) out = [] for v in vals: v = _v61_clean_cell(v) if v and v not in out: out.append(v) return out def _v61_same_name_cell(cell, term): """ 성분명 cell 직접 일치 판정. - 정확히 같은 cell: True - cell이 'Phenoxyethanol 1.0'처럼 성분명 뒤에 숫자/%, g/조건만 붙으면 True - cell이 긴 화학명/설명문이면 False """ cell = _v61_clean_cell(cell) term = _v61_clean_cell(term) if not cell or not term: return False if is_cas_like(term): return normalize_compact(term) in [normalize_compact(x) for x in re.findall(r"\d{2,7}-\d{2}-\d", cell)] c_norm = normalize_compact(cell) t_norm = normalize_compact(term) if not t_norm or len(t_norm) < 3: return False if c_norm == t_norm: return True # 긴 화학명 내부 부분일치 금지: term으로 시작하지 않으면 False if not c_norm.startswith(t_norm): return False remainder = cell[len(term):].strip(" \t::,,;;/|()-–—") rem_norm = normalize_compact(remainder) if not rem_norm: return True # 성분명 바로 뒤에 한도 수치/단위/주석만 따라오는 경우만 허용 allowed_remainder = re.fullmatch( r"(?i)(?:\(?\*?\d*\)?\s*)?(?:\d+(?:[\.,]\d+)?\s*(?:%|g|mg|ppm|iu)?\s*)*(?:as\s+total|total|maximum|per\s*100\s*g|/\s*100\s*g|이하|미만|초과|한도|총량|as\s+acid|as\s+salt)?\s*", remainder, ) if allowed_remainder: return True # 'Phenoxyethanol 1.0'처럼 토큰 기준 term + 숫자 toks = normalized_tokens(cell) ttoks = normalized_tokens(term) if ttoks and toks[:len(ttoks)] == ttoks: rest = toks[len(ttoks):] if rest and all(re.fullmatch(r"\d+(?:\.\d+)?|g|mg|ppm|iu|total|as|per|100", r) for r in rest[:6]): return True return False def _v61_identity_cells_for_record(record): """ Excel/CSV 행은 앞쪽 identity 영역만 성분명 matching에 사용. EU Annex의 Other/Warning/Coating cell에 있는 Glycerin/Dimethicone 등을 성분 hit로 보지 않기 위함. PDF/TXT window는 line 단위로 보되 각 line의 시작/단독 성분명만 인정한다. """ text = safe_str(record.get("text", "")) cells = _v61_split_cells(text) if " | " in text: # 보통: ref no / chemical name / INCI / CAS / EC / product type ... # 제한/허용표의 성분명과 CAS가 앞쪽에 있으므로 앞 6 cell만 identity zone으로 둔다. return cells[:6] return cells def _v61_row_direct_match(record, terms): text = safe_str(record.get("text", "") if isinstance(record, dict) else record) if not text: return False terms = [t for t in terms if safe_str(t)] if not terms: return False cells = _v61_identity_cells_for_record(record if isinstance(record, dict) else {"text": text}) all_text_cas = [normalize_compact(x) for x in re.findall(r"\d{2,7}-\d{2}-\d", text)] cas_terms = [t for t in terms if is_cas_like(t)] name_terms = [t for t in terms if not is_cas_like(t)] # CAS가 있으면 CAS 완전일치가 가장 강한 근거. 단, identity zone 또는 전체 row의 CAS 번호만 비교. for cas in cas_terms: if normalize_compact(cas) in all_text_cas: return True # 성분명은 identity cell에서만 직접 일치 인정 for term in name_terms: for v in _v61_term_variants(term): for cell in cells: if _v61_same_name_cell(cell, v): return True return False def _v61_component_alias(material, component, aliases): blob_record = {"text": " | ".join([ safe_str(component.get("INCI Name", "")), safe_str(component.get("한글 성분명", "")), safe_str(component.get("CAS.No", "")), safe_str(material.get("Trade name(국문)", "")), safe_str(material.get("Trade name(영문)", "")), ])} return _v61_row_direct_match(blob_record, aliases) def _v61_is_jp_glycerin_impurity_record(country, record, material, component): if country_key(country) != "JAPAN": return False if not _v61_component_alias(material, component, ["Glycerin", "Glycerol", "글리세린", "글리세롤", "56-81-5"]): return False text = safe_str(record.get("text", "")) return _v6_has(text, ["diethylene glycol", "디에틸렌글라이콜", "디에칠렌글리콜"]) and _v6_has(text, ["0.1g", "0.1 g", "less than", "미만"]) def _v62_is_japan_glycerin_component(material, component): """ 일본 글리세린 hard guard. 글리세린은 Standards for Cosmetics의 Section 5 DEG 원료 불순물 기준 때문에 검색될 수 있으나, 해당 문구는 글리세린 배합금지/배합한도가 아니다. 이 guard는 일본 Glycerin을 법정 금지/제한 판정 흐름에 태우지 않는다. """ return _v61_component_alias(material or {}, component or {}, [ "Glycerin", "Glycerol", "글리세린", "글리세롤", "56-81-5" ]) def _v62_japan_glycerin_pass_result(country, material, component, target_id=""): representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or "Glycerin" note = ( "V6.2 hard guard: 일본 Standards for Cosmetics Section 5의 " "'Glycerin mixed with cosmetics should contain diethylene glycol less than 0.1g per 100g glycerin' 문구는 " "글리세린 배합금지/배합한도 기준이 아니라 글리세린 원료 중 Diethylene Glycol(DEG) 불순물 기준임. " "따라서 일본 Glycerin은 배합금지/배합한도로 판정하지 않고 Pass 처리. 원료 COA에서 DEG 기준은 별도 품질확인 사항." ) return _v6_result( representative, "일본: Pass / 글리세린 배합금지·배합한도 근거 없음", "Pass", note, target_id, country, component, "V62_JP_GLYCERIN_HARD_GUARD_PASS_NOT_PROHIBITED", ) def _v61_record_type(country, record, material=None, component=None): # V6 분류를 재사용하되, 글리세린 DEG 문맥은 무조건 불순물 기준으로 분리 if component is not None and _v61_is_jp_glycerin_impurity_record(country, record, material or {}, component or {}): return "nonlegal_impurity" return _v6_record_type(country, record, material, component) def _v61_extract_limit_condition_from_row(context): text = safe_str(context) flat = re.sub(r"\s+", " ", text).strip() if not flat: return "", "" # 향료 알레르겐 표시 threshold는 배합한도로 쓰지 않음 if _v6_has(flat, ["leave-on", "rinse-off", "list of ingredients", "indicated in the list of ingredients", "fragrance allergen", "fragrance allergens", "표시", "향료 알레르겐"]): if _v6_has(flat, ["0.001", "0,001", "0.01", "0,01"]): return "", "표시기준: leave-on 0.001%, rinse-off 0.01% 초과 시 표시" # 불순물/오염물질/Prop65 노출 수치는 배합한도로 쓰지 않음 if _v6_has(flat, ["impurity", "impurities", "contaminant", "contaminants", "불순물", "오염물질", "검출한계", "관리값", "관리치", "safe harbor", "exposure"]): return "", "불순물/오염물질 또는 노출 기준" limits = [] def add_limit(raw): raw = safe_str(raw).replace(",", ".") if not raw: return # 05% 같은 잘못된 표시를 0.5가 아니라 05로 방치하지 않기 위한 보정: 원문이 0.5이면 regex가 0.5를 잡음. if re.fullmatch(r"0+\d+", raw): raw = raw.lstrip("0") or "0" if "." in raw: raw = raw.rstrip("0").rstrip(".") item = f"{raw}%" if item not in limits: limits.append(item) for m in re.finditer(r"(? (function () { const KEY = "rebom_saved_login_email"; function findLoginEmailInput() { const inputs = Array.from(document.querySelectorAll("input")); return inputs.find((el) => { const labelText = (el.closest(".form")?.innerText || el.closest("label")?.innerText || "").toLowerCase(); const ph = (el.getAttribute("placeholder") || "").toLowerCase(); return ph.includes("example@rebom.kr") || labelText.includes("메일 주소"); }); } function findRememberCheckbox() { const labels = Array.from(document.querySelectorAll("label, span, div")); const label = labels.find((el) => (el.innerText || "").trim() === "아이디 저장"); if (!label) return null; const container = label.closest("label") || label.closest(".form") || label.parentElement; if (!container) return null; return container.querySelector("input[type='checkbox']") || document.querySelector("input[type='checkbox']"); } function findLoginButton() { const buttons = Array.from(document.querySelectorAll("button")); return buttons.find((btn) => (btn.innerText || "").trim() === "로그인"); } function applySavedEmail() { const saved = localStorage.getItem(KEY) || ""; const emailInput = findLoginEmailInput(); const checkbox = findRememberCheckbox(); if (saved && emailInput && !emailInput.value) { emailInput.value = saved; emailInput.dispatchEvent(new Event("input", { bubbles: true })); emailInput.dispatchEvent(new Event("change", { bubbles: true })); } if (saved && checkbox && !checkbox.checked) { checkbox.click(); } } function bindRememberLogin() { const button = findLoginButton(); if (!button || button.dataset.rebomRememberBound === "1") return; button.dataset.rebomRememberBound = "1"; button.addEventListener("click", function () { const emailInput = findLoginEmailInput(); const checkbox = findRememberCheckbox(); if (!emailInput || !checkbox) return; const email = (emailInput.value || "").trim(); if (checkbox.checked && email) { localStorage.setItem(KEY, email); } else { localStorage.removeItem(KEY); } }); } function boot() { applySavedEmail(); bindRememberLogin(); } setInterval(boot, 1000); document.addEventListener("DOMContentLoaded", boot); })(); """) gr.Markdown("### Screening") with gr.Row(): gr.Button( "🚪 로그아웃", link="/logout?all_session=false", variant="secondary", ) with gr.Tab("🚀 스크리닝", visible=True) as screening_tab: gr.Markdown("## 🚀 전성분 스크리닝") 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",".xls",".pdf",".png",".jpg",".jpeg",".webp"]) btn=gr.Button("🚀 분석 시작",variant="primary") df_out=gr.Dataframe(label="미리보기 - Formula Ingredients Statement",wrap=True,interactive=False) file_out=gr.File(label="결과 다운로드") msg_out=gr.Textbox(label="상태 / 오류 메시지",interactive=False,lines=12) refresh.click(refresh_country_choices_and_clear_cache,inputs=country,outputs=country) file.change(preview_input_file,inputs=file,outputs=df_out) btn.click( process_with_auth, inputs=[current_user,country,file,product_name], outputs=[df_out,file_out,msg_out], ) with gr.Tab("🔎 단일 성분 검색", visible=True) as single_tab: gr.Markdown("## 🔎 단일 성분 검색") single_country=gr.CheckboxGroup(choices=get_country_folders(),value=[],label="🌍 검색 국가 / 채널 선택",elem_id="single_country_checks") single_refresh=gr.Button("🔄 국가/규제파일 새로고침") single_query=gr.Textbox(label="검색어",placeholder="예: 호모살레이트 / Homosalate / 118-56-9 / 트라넥사믹애씨드") with gr.Row(): single_amount=gr.Textbox(label="함량 %(w/w) 선택 입력",placeholder="예: 7.2") single_function=gr.Textbox(label="FUNCTION 선택 입력",placeholder="예: Sunscreen Agent") single_btn=gr.Button("🔎 단일 성분 검색 시작",variant="primary") single_df_out=gr.Dataframe(label="단일 성분 검색 결과",wrap=True,interactive=False) single_msg_out=gr.Textbox(label="검색 상태 / 메시지",interactive=False,lines=8) single_refresh.click(refresh_country_choices_and_clear_cache,inputs=single_country,outputs=single_country) single_btn.click( process_single_ingredient_with_auth, inputs=[current_user,single_country,single_query,single_amount,single_function], outputs=[single_df_out,single_msg_out], ) try: demo.launch( auth=auth_fn, server_name="0.0.0.0", server_port=7860, share=False, show_api=False, allowed_paths=ALLOWED_PATHS, blocked_paths=BLOCKED_PATHS, ) except TypeError: # Gradio/HuggingFace 런타임 버전 차이 대응. demo.launch( auth=auth_fn, server_name="0.0.0.0", server_port=7860, share=False, show_api=False, allowed_paths=ALLOWED_PATHS, blocked_paths=BLOCKED_PATHS, )