Spaces:
Sleeping
Sleeping
Download app.py from reBom/screening: direct link, hf CLI and curl.
- Browser
- Download file 241 kB
-
https://huggingface.co/spaces/reBom/screening/resolve/main/app.py
- Command line
-
hf download hf://spaces/reBom/screening/app.py
-
curl -L -o app.py https://huggingface.co/spaces/reBom/screening/resolve/main/app.py
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)]