screening / app.py
jin2li's picture
Update app.py
254980b verified
Raw History Blame Contribute Delete
241 kB
# 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"(?<![\d.])(\d+(?:[\.,]\d+)?)\s*%", flat): add_limit(m.group(1)) for m in re.finditer(r"(?<![\d.])(\d+(?:[\.,]\d+)?)\s*g\s*(?:/|per)\s*100\s*g", flat, flags=re.IGNORECASE): add_limit(m.group(1)) if not limits and _v6_has(flat, ["maximum amount", "maximum concentration", "๋ฐฐํ•ฉํ•œ๋„", "์‚ฌ์šฉํ•œ๋„", "ingredient per 100 g", "per 100g"]): for m in re.finditer(r"(?<![\d.])(\d+(?:[\.,]\d+)?)\s*g\b", flat, flags=re.IGNORECASE): add_limit(m.group(1)) 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]) return "; ".join(limits[:3]), " / ".join(condition_lines[:3]) def pick_best_source_record(records): priority = { "legal_prohibited": 100, "legal_restricted": 85, "positive_list": 75, "nonlegal_labeling": 55, "nonlegal_prop65": 50, "nonlegal_retailer": 45, "nonlegal_impurity": 40, "nonlegal_voluntary": 35, "reference_microplastics": 30, "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=""): 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 "-" # V6.2: ์ผ๋ณธ Glycerin์€ ์–ด๋–ค record๊ฐ€ ์žกํ˜€๋„ ๋ฐฐํ•ฉ๊ธˆ์ง€/๋ฐฐํ•ฉํ•œ๋„ ํŒ์ • ํ๋ฆ„์— ํƒœ์šฐ์ง€ ์•Š์Œ. # ์›๋ฌธ Section 5๋Š” DEG ์›๋ฃŒ ๋ถˆ์ˆœ๋ฌผ ๊ธฐ์ค€์ด๋ฏ€๋กœ ๊ฒฐ๊ณผํ‘œ์—์„œ๋Š” Pass๋กœ ๊ณ ์ •ํ•œ๋‹ค. if country_key(country) == "JAPAN" and _v62_is_japan_glycerin_component(material, component): return _v62_japan_glycerin_pass_result(country, material, component, target_id) if not terms: return None records, status = build_country_source_record_index(country) hits = [] for rec in records: if not _v61_row_direct_match(rec, terms): continue rtype = _v61_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}: ๋ฒ•์ • ๊ธˆ์ง€๋ชฉ๋ก identity ํ–‰์—์„œ ์„ฑ๋ถ„ ์ง์ ‘ ํ™•์ธ", "๋ฐฐํ•ฉ๊ธˆ์ง€", src_note, target_id, country, component, "V61_ROW_MATCH_PROHIBITED_IDENTITY", ) if rtype == "legal_restricted": limit_text, condition_text = _v61_extract_limit_condition_from_row(context) formula = f"๋ฐฐํ•ฉํ•œ๋„: {limit_text}" if limit_text else NEED_CHECK_TEXT result_text = f"{cdisp}: ๋ฒ•์ • ์ œํ•œ๋ชฉ๋ก identity ํ–‰์—์„œ ์„ฑ๋ถ„ ์ง์ ‘ ํ™•์ธ" + (f" / ์กฐ๊ฑด: {condition_text}" if condition_text else "") return _v6_result( representative, result_text, formula, src_note, target_id, country, component, "V61_ROW_MATCH_RESTRICTED_IDENTITY", ) if rtype == "positive_list": limit_text, condition_text = _v61_extract_limit_condition_from_row(context) formula = f"๋ฐฐํ•ฉํ•œ๋„: {limit_text}" if limit_text else "ํ—ˆ์šฉ๋ชฉ๋ก ๋“ฑ์žฌ / ํ•œ๋„ ํ™•์ธ ํ•„์š”" result_text = f"{cdisp}: ํ—ˆ์šฉ๋ชฉ๋ก identity ํ–‰์—์„œ ์„ฑ๋ถ„ ์ง์ ‘ ํ™•์ธ" + (f" / ์กฐ๊ฑด: {condition_text}" if condition_text else "") source_tag = "V61_ROW_MATCH_POSITIVE_LIST_LIMIT_IDENTITY" if limit_text else "V61_ROW_MATCH_POSITIVE_LIST_IDENTITY" 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"]: # ํƒœ๊ทธ๋Š” V6_nonlegal_result ๋‚ด๋ถ€ V6 ํƒœ๊ทธ ๋Œ€์‹  V61 ๊ตฌ๋ถ„์„ ์œ„ํ•ด wrapper context์— ์ถ”๊ฐ€ result = _v6_nonlegal_result(country, material, component, best, rtype, target_id) return result return _v6_result( representative, NO_EVIDENCE_TEXT, "Pass", src_note + " / V6.1: identity ์˜์—ญ ๋ฐ– ๋˜๋Š” ํŒŒ์ผ ์œ ํ˜• ๋ฏธ๋ถ„๋ฅ˜๋กœ ๋ฒ•์ • ๊ธˆ์ง€ยทํ•œ๋„ ์ž๋™ํŒ์ • ์ œ์™ธ", target_id, country, component, "V61_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", "V6.1: ์—…๋กœ๋“œ๋œ ๊ตญ๊ฐ€๋ณ„ ํŒŒ์ผ์˜ identity ํ–‰/์„ฑ๋ถ„๋ช…ยทCAS ์ง์ ‘ ๊ทผ๊ฑฐ ์—†์Œ", target_id, country, component, "V61_NO_IDENTITY_ROW_MATCH_PASS / V62_JP_GLYCERIN_HARD_GUARD_PASS_NOT_PROHIBITED", ) def _v61_country_issue_from_rowdata(rd, cc): return is_country_result_issue(rd.get(cc, "")) or is_country_result_issue(rd.get(cc + "_display", "")) def build_integrated_result(rd, country_cols): issues = [cc for cc in country_cols if _v61_country_issue_from_rowdata(rd, cc)] return "PASS" if not issues else "์žฌ๊ฒ€ํ†  ํ•„์š”: " + ", ".join(issues) 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: if _v61_country_issue_from_rowdata(rd, cc): row[cc] = rd.get(cc + "_display", "") or rd.get(cc, "") else: row[cc] = "-" row["๋น„๊ณ "] = rd.get("๋น„๊ณ ", "-") rows.append(row) cols = ["ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", "INCI Name", "In formula(w/w %)", "Result"] + country_cols + ["๋น„๊ณ "] return pd.DataFrame(rows, columns=cols) def is_country_result_issue(text): text = safe_str(text) if not text or text in ["-", NO_EVIDENCE_TEXT, "Pass", "PASS", "pass"]: return False # ํ—ˆ์šฉ๋ชฉ๋ก ์ž์ฒด๋Š” ์ด์Šˆ๊ฐ€ ์•„๋‹ˆ์ง€๋งŒ, ํ•œ๋„/์กฐ๊ฑด/ํ™•์ธ์ด ์žˆ์œผ๋ฉด Summary์— ๋ฐ˜์˜ if "ํ—ˆ์šฉ๋ชฉ๋ก" in text and not _v6_has(text, ["๋ฐฐํ•ฉํ•œ๋„", "ํ•œ๋„", "์กฐ๊ฑด", "ํ™•์ธ ํ•„์š”"]): return False return _v6_has(text, [ "๋ฐฐํ•ฉ๊ธˆ์ง€", "๋ฐฐํ•ฉํ•œ๋„", "ํ•œ๋„", "ํ™•์ธ ํ•„์š”", "๊ฒฝ๊ณ ํ‘œ์‹œ", "Clean ๊ธฐ์ค€", "๋ถˆ์ˆœ๋ฌผ", "์˜ค์—ผ๋ฌผ์งˆ", "์ž์œจ๊ธฐ์ค€", "ํ‘œ์‹œ๊ธฐ์ค€", "๋ถ€์ ํ•ฉ", "์žฌ๊ฒ€ํ† ", "์‚ฌ์šฉ ๋ถˆ๊ฐ€", "์‚ฌ์šฉ๋ถˆ๊ฐ€", "Microplastics", "ํ—ˆ์šฉ๋ชฉ๋ก ๋“ฑ์žฌ / ํ•œ๋„ ํ™•์ธ ํ•„์š”", ]) # ============================================================ # END SOURCE TABLE ROW ENGINE PATCH V6.1 # ============================================================ # ============================================================ # USER PATCH 2026-06-15 # 1) Output country/channel display names forced to English # - Japan / China no longer appear as Korean in Excel headers or result text # 2) global_index folder is hidden from country/channel checkbox UI # - If a ./global_index folder exists, it is automatically searched together # with every selected country/channel. # - It is not shown as a selectable channel and does not create a separate # Excel output column. # ============================================================ HIDDEN_ALWAYS_INCLUDED_FOLDERS = ["global_index"] COUNTRY_DISPLAY.update({ "JAPAN": "Japan", "์ผ๋ณธ": "Japan", "JP": "Japan", "CHINA": "China", "์ค‘๊ตญ": "China", "CN": "China", "KOREA": "Korea", "ํ•œ๊ตญ": "Korea", "KR": "Korea", "US": "US", "USA": "US", "FDA": "US", "๋ฏธ๊ตญ": "US", }) COUNTRY_FOLDER_ALIASES.update({ "GLOBAL_INDEX": "global_index", "GLOBAL INDEX": "global_index", "global index": "global_index", "global_index": "global_index", }) def _hidden_folder_key(value): return safe_str(value).strip().lower().replace("-", "_").replace(" ", "_") def _is_hidden_always_folder(value): return _hidden_folder_key(value) in {_hidden_folder_key(v) for v in HIDDEN_ALWAYS_INCLUDED_FOLDERS} # Final display override. This is intentionally placed after all prior patches # because older patch blocks redefine display_country multiple times. def display_country(country): c = country_key(country) if c == "US": return "US" if c == "KOREA": return "Korea" if c == "JAPAN": return "Japan" if c == "CHINA": return "China" return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), c)) _ORIGINAL_get_country_folders = get_country_folders def get_country_folders(): """Return only user-selectable folders. global_index is hidden but still used.""" return [c for c in _ORIGINAL_get_country_folders() if not _is_hidden_always_folder(c)] _ORIGINAL_refresh_country_choices_keep_selection = refresh_country_choices_keep_selection 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) _ORIGINAL_get_country_section_index_cached = get_country_section_index_cached def get_country_section_index_cached(country): """ Load selected country/channel sections and automatically append global_index sections when the folder exists. This lets global_index act like a hidden, always-on reference source without exposing it in the UI or Excel columns. """ sections, status = _ORIGINAL_get_country_section_index_cached(country) extra_sections = [] extra_statuses = [] for hidden in HIDDEN_ALWAYS_INCLUDED_FOLDERS: if _is_hidden_always_folder(country): continue hidden_folder = resolve_country_folder(hidden) if not hidden_folder or not os.path.isdir(hidden_folder): continue try: hs, hstatus = _ORIGINAL_get_country_section_index_cached(hidden) if hs: extra_sections.extend(hs) extra_statuses.append(f"{hidden}={hstatus}/{len(hs)} sections") except Exception as e: extra_statuses.append(f"{hidden}=index error: {e}") if extra_sections: status = f"{status} + hidden({'; '.join(extra_statuses)})" return list(sections or []) + extra_sections, status with gr.Blocks(css=custom_css) as demo: current_user = gr.State({}) gr.Markdown("# ๐ŸŒ reBom") gr.HTML(""" <script> (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); })(); </script> """) 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, )
# 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)]