Spaces:
Sleeping
Sleeping
Download app.py from reBom/screening: direct link, hf CLI and curl.
- Browser
- Download file 88.9 kB
-
https://huggingface.co/spaces/reBom/screening/resolve/refs%2Fpr%2F1/app.py
- Command line
-
hf download hf://spaces/reBom/screening@refs/pr/1/app.py
-
curl -L -o app.py https://huggingface.co/spaces/reBom/screening/resolve/refs%2Fpr%2F1/app.py
88.9 kB
# ============================================================
# reBom Regulatory Screening AI - Fast Grounded Fixed Version
# - ๊ตญ๊ฐ/์ฑ๋ ํด๋ ์๋ ์ธ์
# - ๊ท์ ํ์ผ ์๋ ๋ณ๊ฒฝ ๊ฐ์ง
# - ๊ตญ๊ฐ๋ณ FAISS ๋ฒกํฐ DB ๋์คํฌ ์บ์
# - ๊ตญ๊ฐ๋ณ ๋ฌธ์ ๊ฒฉ๋ฆฌ ๊ฒ์์ผ๋ก ํ๊ตญ ๊ท์ ํ์ฐ ๋ฐฉ์ง
# - ๋ก์ปฌ ๊ท์น ์ฐ์ ํ์
# - MFDS ์์ฝํ์์ ๋๋ผ ์์ธ DB ์์
์ฐ๋
# - GPT ํธ์ถ ์ ์๋ฏธ ์๋ ๊ฒ์๊ฒฐ๊ณผ ํํฐ๋ง
# - Formula Ingredients Statement ์๋ณธ ์์ ์ถ๋ ฅ
# - ๋ฌธ์ ์ฑ๋ถ๋ง Regulatory Screening Summary ์ถ๋ ฅ
# - Raw Search Log ๋ณ๋ ์ ์ฅ
# - Gradio ๋ก๊ทธ์ธ ์ธ์ฆ / public share link ์ ์ฉ
# - MergedCell column_letter ์ค๋ฅ ์์ ์๋ฃ
# ============================================================
# ============================================================
# reBom Regulatory Screening AI
# - ๊ตญ๊ฐ๋ณ ๊ท์ ํด๋ ์์์๋ง ๊ฒ์
# - FAISS ๋์คํฌ ์บ์
# - GPT๋ ๊ฒ์๋ ์๋ฌธ ์์์๋ง ํ์
# - ์์ฝ์ฒ ์ฌ์ดํธ ์ค์๊ฐ ์กฐํ ์ต์
# - Formular Ingredients Statement ์๋ณธ ์์ ์ถ๋ ฅ
# - ์๋ณธ TOTAL ํ ์ ๊ฑฐ ํ ์ TOTAL ํ 1๊ฐ๋ง ์์ฑ
# ============================================================
import os
import re
import json
import hashlib
import traceback
from pathlib import Path
from collections import defaultdict
import pandas as pd
import pdfplumber
import gradio as gr
try:
from bs4 import BeautifulSoup
except Exception:
BeautifulSoup = None
try:
from playwright.sync_api import sync_playwright
PLAYWRIGHT_AVAILABLE = True
except Exception:
sync_playwright = None
PLAYWRIGHT_AVAILABLE = False
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
# ============================================================
# 0. ๊ธฐ๋ณธ ์ค์
# ============================================================
api_key = os.getenv("OPENAI_API_KEY")
print("โ
OPENAI_API_KEY ์ ์" if api_key else "โ OPENAI_API_KEY ์์")
BASE_DIR = Path.cwd().resolve()
OUTPUT_DIR = (BASE_DIR / "outputs").resolve()
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
FAISS_CACHE_DIR = ".faiss_cache"
MFDS_LIVE_URL = "https://nedrug.mfds.go.kr/pbp/CCBDF01"
NO_EVIDENCE_TEXT = "ํด๋น ์๋ฃ ๋ด ์ ํ ๊ทผ๊ฑฐ ์์"
VECTOR_DB_CACHE = {}
EVAL_CACHE = {}
EMBEDDINGS_CACHE = None
RAW_SEARCH_LOGS = []
SUPPORTED_REG_FILE_EXTENSIONS = {".pdf", ".txt", ".csv", ".xlsx", ".xls"}
COUNTRY_ORDER = [
"ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "FDA",
"JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA",
]
COUNTRY_DISPLAY = {
"EU": "EU", "์ ๋ฝ": "EU", "EUROPE": "EU",
"FDA": "FDA", "๋ฏธ๊ตญ": "FDA", "USA": "FDA", "US": "FDA",
"KOREA": "Korea", "ํ๊ตญ": "Korea", "KR": "Korea",
"JAPAN": "์ผ๋ณธ", "์ผ๋ณธ": "์ผ๋ณธ", "JP": "์ผ๋ณธ",
"CHINA": "์ค๊ตญ", "์ค๊ตญ": "์ค๊ตญ", "CN": "์ค๊ตญ",
"ASEAN": "ASEAN", "์์ธ์": "ASEAN",
"UK": "UK", "์๊ตญ": "UK",
"EU (FUTURE)": "EU (FUTURE)", "EU_FUTURE": "EU (FUTURE)",
"CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO",
"SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA",
}
COUNTRY_FOLDER_ALIASES = {
"EU": "EU", "์ ๋ฝ": "EU", "EUROPE": "EU",
"FDA": "FDA", "๋ฏธ๊ตญ": "FDA", "USA": "FDA", "US": "FDA",
"KOREA": "KOREA", "ํ๊ตญ": "KOREA", "KR": "KOREA",
"JAPAN": "JAPAN", "์ผ๋ณธ": "JAPAN", "JP": "JAPAN",
"CHINA": "CHINA", "์ค๊ตญ": "CHINA", "CN": "CHINA",
"ASEAN": "ASEAN", "์์ธ์": "ASEAN",
"UK": "UK", "์๊ตญ": "UK",
"EU (FUTURE)": "EU (FUTURE)",
"EU_FUTURE": "EU (FUTURE)",
"EU FUTURE": "EU (FUTURE)",
"CALIFORNIA": "CALIFORNIA",
"MEXICO": "MEXICO",
"SEPHORA": "SEPHORA",
"TARGET": "TARGET",
"ULTA": "ULTA",
}
BLOCKED_PATHS = [str(BASE_DIR / c) for c in COUNTRY_ORDER] + [
str(BASE_DIR / FAISS_CACHE_DIR),
str(BASE_DIR / ".env"),
str(BASE_DIR / "__pycache__"),
]
ALLOWED_PATHS = [
str(OUTPUT_DIR),
str(BASE_DIR),
]
BATCH_SIZE = 40
RAG_TOP_K_BATCH = 4
RAG_TOP_K_SINGLE = 2
MEANINGFUL_HIT_K = 2
custom_css = """
#country_checks .wrap,
#country_checks .checkbox-group {
display: flex !important;
flex-direction: row !important;
flex-wrap: wrap !important;
gap: 10px !important;
}
#country_checks label {
display: inline-flex !important;
align-items: center !important;
width: auto !important;
min-width: 110px !important;
padding: 8px 12px !important;
border: 1px solid #555 !important;
border-radius: 10px !important;
margin: 4px !important;
}
"""
# ============================================================
# 1. ๋ก์ปฌ ๊ท์น
# ============================================================
UV_FILTER_RULES = {
"octocrylene": {
"label": "Octocrylene",
"aliases": ["octocrylene", "์ฅํ ํฌ๋ฆด๋ ", "6197-30-4"],
"EU": {
"status": "allowed",
"limit": 10,
"formula_text": "๋ฐฐํฉ ํ๋:\n์คํ๋ ์ด: 9% /\n๊ธฐํ์ ํ: 10%",
},
"FDA": {
"status": "allowed",
"limit": 10,
"formula_text": "๋ผ๋ฒจ๋ง ํ์",
},
"KOREA": {
"status": "allowed",
"limit": 10,
"formula_text": "๋ฐฐํฉํ๋: 10%",
},
"JAPAN": {
"status": "allowed",
"limit": 10,
"formula_text": "๋ฐฐํฉํ๋: 10%",
},
"SEPHORA": {
"status": "prohibited",
"formula_text": "๋ฐฐํฉ๊ธ์ง",
},
},
"homosalate": {
"label": "Homosalate",
"aliases": ["homosalate", "ํธ๋ชจ์ด๋ ์ดํธ", "118-56-9"],
"EU": {
"status": "allowed",
"limit": 7.34,
"formula_text": "๋ฐฐํฉํ๋: 7.34%",
},
"FDA": {
"status": "allowed",
"limit": 15,
"formula_text": "๋ฐฐํฉํ๋: 15%",
},
"KOREA": {
"status": "allowed",
"limit": 10,
"formula_text": "๋ฐฐํฉํ๋: 10%",
},
"JAPAN": {
"status": "allowed",
"limit": 10,
"formula_text": "๋ฐฐํฉํ๋: 10%",
},
},
"octisalate": {
"label": "Octisalate / Ethylhexyl Salicylate",
"aliases": ["octisalate", "ethylhexyl salicylate", "์ฅํฐ์ด๋ ์ดํธ", "118-60-5"],
"EU": {
"status": "allowed",
"limit": 5,
"formula_text": "๋ฐฐํฉํ๋: 5%",
},
"FDA": {
"status": "allowed",
"limit": 5,
"formula_text": "๋ฐฐํฉํ๋: 5%",
},
"KOREA": {
"status": "allowed",
"limit": 5,
"formula_text": "๋ฐฐํฉํ๋: 5%",
},
"JAPAN": {
"status": "allowed",
"limit": 5,
"formula_text": "๋ฐฐํฉํ๋: 5%",
},
},
"avobenzone": {
"label": "Avobenzone",
"aliases": ["avobenzone", "butyl methoxydibenzoylmethane", "์๋ณด๋ฒค์กด", "70356-09-1"],
"EU": {
"status": "allowed",
"limit": 5,
"formula_text": "๋ฐฐํฉํ๋: 5%",
},
"FDA": {
"status": "allowed",
"limit": 3,
"formula_text": "๋ฐฐํฉํ๋: 3%",
},
"KOREA": {
"status": "allowed",
"limit": 5,
"formula_text": "๋ฐฐํฉํ๋: 5%",
},
},
}
PRESERVATIVE_RULES = {
"phenoxyethanol": {
"label": "Phenoxyethanol",
"aliases": ["phenoxyethanol", "ํ๋
น์์ํ์ฌ", "122-99-6"],
"EU": {
"status": "allowed",
"limit": 1,
"formula_text": "๋ฐฐํฉํ๋: 1%",
},
"KOREA": {
"status": "allowed",
"limit": 1,
"formula_text": "๋ฐฐํฉํ๋: 1%",
},
"JAPAN": {
"status": "allowed",
"limit": 1,
"formula_text": "๋ฐฐํฉํ๋: 1%",
},
},
}
FUNCTIONAL_KOREA_RULES = {
"niacinamide": {
"label": "Niacinamide",
"aliases": ["niacinamide", "๋์ด์์ ์๋ง์ด๋", "98-92-0"],
"result": "๊ธฐ๋ฅ์ฑํ์ฅํ ๊ฒํ / Niacinamide ํ์ฌ ํจ๋ {amount}%, ๋ฏธ๋ฐฑ ๊ธฐ๋ฅ์ฑ ํ์ยท๊ด๊ณ ์ ์๊ฑด ํ์ธ ํ์",
"formula_text": "๊ธฐ๋ฅ์ฑ ํ์ธ",
},
"adenosine": {
"label": "Adenosine",
"aliases": ["adenosine", "์๋ฐ๋
ธ์ ", "58-61-7"],
"result": "๊ธฐ๋ฅ์ฑํ์ฅํ ๊ฒํ / Adenosine ํ์ฌ ํจ๋ {amount}%, ์ฃผ๋ฆ๊ฐ์ ๊ธฐ๋ฅ์ฑ ํ์ยท๊ด๊ณ ์ ์๊ฑด ํ์ธ ํ์",
"formula_text": "๊ธฐ๋ฅ์ฑ ํ์ธ",
},
}
FRAGRANCE_ALLERGEN_RULES = {
"limonene": {
"label": "Limonene",
"aliases": ["limonene", "๋ฆฌ๋ชจ๋จ"],
"leave_on": 0.001,
"wash_off": 0.01,
},
"linalool": {
"label": "Linalool",
"aliases": ["linalool", "๋ฆฌ๋ ๋ฃฐ"],
"leave_on": 0.001,
"wash_off": 0.01,
},
"citral": {
"label": "Citral",
"aliases": ["citral", "์ํธ๋"],
"leave_on": 0.001,
"wash_off": 0.01,
},
"geraniol": {
"label": "Geraniol",
"aliases": ["geraniol", "์ ๋ผ๋์ฌ"],
"leave_on": 0.001,
"wash_off": 0.01,
},
"eugenol": {
"label": "Eugenol",
"aliases": ["eugenol", "์ ์ ๋"],
"leave_on": 0.001,
"wash_off": 0.01,
},
"benzyl alcohol": {
"label": "Benzyl Alcohol",
"aliases": ["benzyl alcohol", "๋ฒค์ง์์ฝ์ฌ"],
"leave_on": 0.001,
"wash_off": 0.01,
},
}
# ============================================================
# 2. ๊ณตํต ์ ํธ
# ============================================================
def safe_str(x):
if pd.isna(x):
return ""
return str(x).strip()
def normalize_text(text):
text = safe_str(text).lower()
text = text.replace("ฮฑ", "alpha").replace("ฮฒ", "beta")
text = re.sub(r"[^a-z0-9๊ฐ-ํฃ]+", " ", text)
return re.sub(r"\s+", " ", text).strip()
def normalize_compact(text):
return re.sub(r"\s+", "", normalize_text(text))
def is_total_like_text(text):
compact = normalize_compact(text)
return compact in ["total", "ํฉ๊ณ", "์ดํฉ", "sum"] or compact.startswith("total") or compact.startswith("ํฉ๊ณ")
def row_has_total_like(row_values):
values = [safe_str(v) for v in row_values if safe_str(v)]
for value in values:
if is_total_like_text(value):
return True
row_text = " ".join(values)
row_compact = normalize_compact(row_text)
if (
row_compact in ["total", "ํฉ๊ณ", "์ดํฉ", "sum"]
or row_compact.startswith("total")
or row_compact.startswith("ํฉ๊ณ")
or "total100" in row_compact
or "ํฉ๊ณ100" in row_compact
):
return True
return False
def country_key(country):
text = safe_str(country).upper().replace("_", " ").replace("-", " ")
text = re.sub(r"\s+", " ", text).strip()
mapping = {
"ํ๊ตญ": "KOREA",
"KOREA": "KOREA",
"KR": "KOREA",
"EU": "EU",
"E.U.": "EU",
"EUROPE": "EU",
"์ ๋ฝ": "EU",
"EU FUTURE": "EU_FUTURE",
"EU (FUTURE)": "EU_FUTURE",
"JAPAN": "JAPAN",
"JP": "JAPAN",
"์ผ๋ณธ": "JAPAN",
"CHINA": "CHINA",
"CN": "CHINA",
"์ค๊ตญ": "CHINA",
"USA": "FDA",
"US": "FDA",
"๋ฏธ๊ตญ": "FDA",
"FDA": "FDA",
"ASEAN": "ASEAN",
"์์ธ์": "ASEAN",
"UK": "UK",
"UNITED KINGDOM": "UK",
"์๊ตญ": "UK",
"SEPHORA": "SEPHORA",
"TARGET": "TARGET",
"ULTA": "ULTA",
}
return mapping.get(text, text)
def display_country(country):
return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), str(country)))
def to_number(value):
if pd.isna(value):
return None
text = str(value).strip().replace(",", ".").replace("%", "")
if not text:
return None
try:
return float(text)
except Exception:
return None
def is_numeric_like(value):
return to_number(value) is not None
def format_amount(value, digits=10):
num = to_number(value)
if num is None:
return ""
if abs(num) >= 1:
text = f"{num:.6f}"
else:
text = f"{num:.{digits}f}"
text = text.rstrip("0").rstrip(".")
return text if text else "0"
def format_percent(value):
return format_amount(value, digits=10)
def format_no(value):
num = to_number(value)
if num is not None and float(num).is_integer():
return str(int(num))
return safe_str(value)
def stable_hash(obj):
text = json.dumps(obj, ensure_ascii=False, sort_keys=True, default=str)
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def safe_filename(text):
text = safe_str(text)
text = re.sub(r"[^a-zA-Z0-9๊ฐ-ํฃ._() -]", "_", text)
text = text.strip().replace(" ", "_")
return text or "unknown"
def chunk_list(items, size):
for i in range(0, len(items), size):
yield items[i:i + size]
def get_embeddings():
global EMBEDDINGS_CACHE
if EMBEDDINGS_CACHE is None:
EMBEDDINGS_CACHE = OpenAIEmbeddings(model="text-embedding-3-small")
return EMBEDDINGS_CACHE
def get_identity_text(material, component):
texts = [
component.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
component.get("INCI Name", ""),
material.get("Trade name(๊ตญ๋ฌธ)", ""),
material.get("Trade name(์๋ฌธ)", ""),
]
return normalize_text(" ".join([safe_str(x) for x in texts if safe_str(x)]))
def match_rule_key(material, component, rule_dict):
identity = get_identity_text(material, component)
for key, rule in rule_dict.items():
for alias in rule.get("aliases", []):
alias_norm = normalize_text(alias)
if alias_norm and alias_norm in identity:
return key
return None
def is_country_result_issue(text):
text = safe_str(text)
if not text or text in ["-", NO_EVIDENCE_TEXT, "Pass", "PASS", "pass"]:
return False
keywords = [
"๋ฐฐํฉ๊ธ์ง",
"๊ธ์ง",
"์ด๊ณผ",
"๋ถ์ ํฉ",
"์ฌ๊ฒํ ",
"ํ์ธ ํ์",
"์๋ฃ ํ์ธ",
"ํ์ ํ์",
"๋ผ๋ฒจ๋ง",
"๋ถ๊ฐ",
"์ฃผ์",
"๊ฒฝ๊ณ ",
]
return any(k in text for k in keywords)
def log_search_context(target_id, country, component, result_text, source, context):
RAW_SEARCH_LOGS.append({
"target_id": target_id,
"๊ตญ๊ฐ/์ฑ๋": display_country(country),
"์ฑ๋ถ๋ช
": safe_str(component.get("ํ๊ธ ์ฑ๋ถ๋ช
", "")),
"INCI Name": safe_str(component.get("INCI Name", "")),
"ํ์ ": safe_str(result_text),
"์ถ์ฒ": safe_str(source),
"๊ฒ์ ์๋ฌธ": safe_str(context)[:3000],
})
def normalize_formula_country_text(text, country_col="", inci_name="", amount_text=""):
text = safe_str(text)
country_col = safe_str(country_col)
inci_norm = normalize_compact(inci_name)
if not text or text == "-" or text == NO_EVIDENCE_TEXT:
return "Pass"
lower = text.lower()
if "octocrylene" in inci_norm or "์ฅํ ํฌ๋ฆด๋ " in inci_norm:
if country_col == "EU":
return "๋ฐฐํฉ ํ๋:\n์คํ๋ ์ด: 9% /\n๊ธฐํ์ ํ: 10%"
if country_col == "FDA":
return "๋ผ๋ฒจ๋ง ํ์"
if country_col == "Korea":
return "๋ฐฐํฉํ๋: 10%"
if "homosalate" in inci_norm or "ํธ๋ชจ์ด๋ ์ดํธ" in inci_norm:
if country_col == "EU":
return "๋ฐฐํฉํ๋: 7.34%"
if country_col == "FDA":
return "๋ฐฐํฉํ๋: 15%"
if country_col == "Korea":
return "๋ฐฐํฉํ๋: 10%"
if "octisalate" in inci_norm or "ethylhexylsalicylate" in inci_norm or "์ฅํฐ์ด๋ ์ดํธ" in inci_norm:
return "๋ฐฐํฉํ๋: 5%"
if "avobenzone" in inci_norm or "์๋ณด๋ฒค์กด" in inci_norm:
if country_col == "FDA":
return "๋ฐฐํฉํ๋: 3%"
return "๋ฐฐํฉํ๋: 5%"
if "๋ฐฐํฉ๊ธ์ง" in text or "์ฌ์ฉ๊ธ์ง" in text or "๊ธ์ง" in text or "prohibited" in lower:
return "๋ฐฐํฉ๊ธ์ง"
if "์ด๊ณผ" in text or "๋ถ์ ํฉ" in text or "์ฌ์ฉ ๋ถ๊ฐ" in text or "์ฌ์ฉ๋ถ๊ฐ" in text:
return "ํ๋ ์ด๊ณผ"
if "ํ์ ํ์" in text or "๋ผ๋ฒจ" in text or "label" in lower:
return "๋ผ๋ฒจ๋ง ํ์"
limit_match = re.search(r"ํ๋\s*([0-9]+(?:\.[0-9]+)?\s*%)", text)
if limit_match:
return "๋ฐฐํฉํ๋: " + limit_match.group(1).replace(" ", "")
percent_match = re.search(r"([0-9]+(?:\.[0-9]+)?\s*%)", text)
if percent_match and ("ํ๋" in text or "limit" in lower or "max" in lower):
return "๋ฐฐํฉํ๋: " + percent_match.group(1).replace(" ", "")
if "ํ์ธ ํ์" in text or "์๋ฃ ํ์ธ" in text or "์ฌ๊ฒํ " in text or "๊ฒํ ํ์" in text:
return "ํ์ธ ํ์"
if "์ด๋ด" in text or "ํต๊ณผ" in text or "ํ๋ ์ด๋ด" in text:
return "Pass"
return text[:120]
# ============================================================
# 3. ๊ตญ๊ฐ ํด๋ / ๊ท์ DB
# ============================================================
def resolve_country_folder(country):
if not country or country == "ํด๋ ์์":
return None
raw = safe_str(country)
alias = COUNTRY_FOLDER_ALIASES.get(raw, COUNTRY_FOLDER_ALIASES.get(raw.upper(), raw))
candidates = [
raw,
alias,
raw.upper(),
alias.upper(),
raw.replace("_", " "),
raw.replace("-", " "),
raw.replace("EU FUTURE", "EU (FUTURE)"),
raw.replace("EU_FUTURE", "EU (FUTURE)"),
alias.replace("_", " "),
alias.replace("-", " "),
]
seen = []
for item in candidates:
item = safe_str(item)
if item and item not in seen:
seen.append(item)
for item in seen:
if os.path.isdir(item):
return item
folder_map = {
f.lower(): f
for f in os.listdir(".")
if os.path.isdir(f)
}
for item in seen:
matched = folder_map.get(item.lower())
if matched:
return matched
return alias
def get_country_folders():
exclude = [
".git",
".cache",
"__pycache__",
".ipynb_checkpoints",
".venv",
"venv",
"node_modules",
FAISS_CACHE_DIR,
"outputs",
]
folders = [
f for f in os.listdir(".")
if os.path.isdir(f) and f not in exclude
]
existing = set(folders)
ordered = [c for c in COUNTRY_ORDER if c in existing]
extras = sorted([f for f in folders if f not in COUNTRY_ORDER])
return ordered + extras if ordered or extras else COUNTRY_ORDER.copy()
def refresh_country_choices_keep_selection(current_values=None):
choices = get_country_folders()
current_values = current_values or []
kept = [v for v in current_values if v in choices]
return gr.update(choices=choices, value=kept)
def refresh_country_choices_and_clear_cache(current_values=None):
VECTOR_DB_CACHE.clear()
EVAL_CACHE.clear()
return refresh_country_choices_keep_selection(current_values)
def get_regulatory_file_list(country_folder):
files = []
if not country_folder or not os.path.isdir(country_folder):
return files
for root, dirs, filenames in os.walk(country_folder):
dirs[:] = [
d for d in dirs
if not d.startswith(".") and d not in ["__pycache__", ".ipynb_checkpoints"]
]
for filename in filenames:
ext = os.path.splitext(filename)[1].lower()
if ext not in SUPPORTED_REG_FILE_EXTENSIONS:
continue
path = os.path.join(root, filename)
try:
stat = os.stat(path)
except FileNotFoundError:
continue
files.append({
"path": path,
"relative_path": os.path.relpath(path, country_folder),
"size": stat.st_size,
"mtime_ns": stat.st_mtime_ns,
"ext": ext,
})
return sorted(files, key=lambda x: x["relative_path"].lower())
def read_text_file_with_fallback(file_path):
for enc in ["utf-8", "utf-8-sig", "cp949", "euc-kr", "latin-1"]:
try:
with open(file_path, "r", encoding=enc) as f:
return f.read()
except Exception:
continue
return ""
def extract_text_from_regulatory_file(file_item):
path = file_item["path"]
rel = file_item["relative_path"]
ext = file_item["ext"]
texts = []
try:
if ext == ".pdf":
with pdfplumber.open(path) as pdf:
for page_no, page in enumerate(pdf.pages, start=1):
text = page.extract_text()
if text:
texts.append(f"[ํ์ผ: {rel}] [ํ์ด์ง: {page_no}]\n{text}")
elif ext == ".txt":
text = read_text_file_with_fallback(path)
if text:
texts.append(f"[ํ์ผ: {rel}]\n{text}")
elif ext == ".csv":
try:
df = pd.read_csv(path, dtype=str)
except UnicodeDecodeError:
df = pd.read_csv(path, dtype=str, encoding="cp949")
texts.append(f"[ํ์ผ: {rel}]\n{df.fillna('').to_string(index=False)}")
elif ext in [".xlsx", ".xls"]:
sheets = pd.read_excel(path, sheet_name=None, dtype=str)
for sheet_name, sheet_df in sheets.items():
texts.append(f"[ํ์ผ: {rel}] [์ํธ: {sheet_name}]\n{sheet_df.fillna('').to_string(index=False)}")
except Exception as e:
print(f"๊ท์ ํ์ผ ์ฝ๊ธฐ ์ค๋ฅ: {path} / {e}")
return "\n\n".join(texts)
def build_database(country):
folder = resolve_country_folder(country)
if not folder or not os.path.isdir(folder):
return None
files = get_regulatory_file_list(folder)
if not files:
return None
signature = tuple(
(f["relative_path"], f["size"], f["mtime_ns"])
for f in files
)
sig_hash = stable_hash(signature)
cached = VECTOR_DB_CACHE.get(folder)
if isinstance(cached, dict) and cached.get("signature_hash") == sig_hash:
return cached.get("db")
embeddings = get_embeddings()
os.makedirs(FAISS_CACHE_DIR, exist_ok=True)
cache_path = os.path.join(
FAISS_CACHE_DIR,
f"{safe_filename(folder)}_{sig_hash[:16]}",
)
meta_path = os.path.join(cache_path, "metadata.json")
if os.path.isdir(cache_path) and os.path.exists(meta_path):
try:
with open(meta_path, "r", encoding="utf-8") as f:
meta = json.load(f)
if meta.get("signature_hash") == sig_hash:
print(f"โ
FAISS ๋์คํฌ ์บ์ ๋ก๋: {folder}")
db = FAISS.load_local(
cache_path,
embeddings,
allow_dangerous_deserialization=True,
)
VECTOR_DB_CACHE[folder] = {
"signature_hash": sig_hash,
"db": db,
}
return db
except Exception as e:
print(f"FAISS ์บ์ ๋ก๋ ์คํจ: {folder} / {e}")
print(f"๐ ๊ท์ DB ์ฌ์์ธ: {folder} / ํ์ผ {len(files)}๊ฐ")
EVAL_CACHE.clear()
splitter = RecursiveCharacterTextSplitter(
chunk_size=900,
chunk_overlap=120,
)
chunks = []
for item in files:
raw = extract_text_from_regulatory_file(item)
if raw:
chunks.extend(
splitter.split_text(
f"[๊ตญ๊ฐ/์ฑ๋: {folder}] [์ถ์ฒํ์ผ: {item['relative_path']}]\n{raw}"
)
)
if not chunks:
return None
db = FAISS.from_texts(chunks, embeddings)
try:
os.makedirs(cache_path, exist_ok=True)
db.save_local(cache_path)
with open(meta_path, "w", encoding="utf-8") as f:
json.dump(
{
"country_folder": folder,
"signature_hash": sig_hash,
"file_count": len(files),
},
f,
ensure_ascii=False,
indent=2,
)
print(f"โ
FAISS ๋์คํฌ ์บ์ ์ ์ฅ: {cache_path}")
except Exception as e:
print(f"FAISS ์บ์ ์ ์ฅ ์คํจ: {folder} / {e}")
VECTOR_DB_CACHE[folder] = {
"signature_hash": sig_hash,
"db": db,
}
return db
def get_current_db_signature(country):
folder = resolve_country_folder(country)
cached = VECTOR_DB_CACHE.get(folder)
if isinstance(cached, dict):
return cached.get("signature_hash")
return None
# ============================================================
# 4. ์
๋ ฅ ์์
๋ฏธ๋ฆฌ๋ณด๊ธฐ / ์ปฌ๋ผ ์ธ์
# ============================================================
def preview_excel(file):
if not file:
return None
try:
return pd.read_excel(file.name)
except Exception as e:
return pd.DataFrame({"์ค๋ฅ": [str(e)]})
def find_best_col(df, keywords, default_index=None, exclude_cols=None):
exclude_cols = exclude_cols or []
scores = []
for idx, col in enumerate(df.columns):
if col in exclude_cols:
continue
header = str(col).lower()
values = df[col].dropna().astype(str).str.strip()
sample = " ".join(values.head(80).tolist()).lower()
score = 0
for kw in keywords:
if kw.lower() in header:
score += 30
markers = [
"aqua", "water", "glycerin", "octocrylene", "homosalate",
"octisalate", "avobenzone", "niacinamide", "phenoxyethanol",
"limonene", "linalool", "citral", "extract", "acid",
"ceramide", "glycol", "retinol",
]
if any(x in sample for x in markers):
if any(k.lower() in ["inci", "ingredient", "์ฑ๋ถ", "์ ์ฑ๋ถ", "๊ตฌ์ฑ", "inci name"] for k in keywords):
score += 10
scores.append((score, idx, col))
scores = sorted(scores, reverse=True, key=lambda x: (x[0], -x[1]))
if scores and scores[0][0] > 0:
return scores[0][2]
if default_index is not None and len(df.columns) > default_index:
return df.columns[default_index]
return df.columns[0]
def find_optional_col(df, keywords, exclude_cols=None):
exclude_cols = exclude_cols or []
best = None
best_score = 0
for idx, col in enumerate(df.columns):
if col in exclude_cols:
continue
header = str(col).lower()
score = 0
for kw in keywords:
if kw.lower() in header:
score += 30
if score > best_score:
best_score = score
best = col
return best
def find_numeric_col(df, keywords, default_index=None, exclude_cols=None, prefer_many_values=True):
exclude_cols = exclude_cols or []
candidates = []
for idx, col in enumerate(df.columns):
if col in exclude_cols:
continue
header = str(col).lower()
values = df[col].dropna()
if values.empty:
continue
count = values.apply(is_numeric_like).sum()
if count <= 0:
continue
score = 0
for kw in keywords:
if kw.lower() in header:
score += 30
candidates.append({
"col": col,
"idx": idx,
"score": score,
"count": count,
"non_null": len(values),
})
if not candidates:
if default_index is not None and len(df.columns) > default_index:
return df.columns[default_index]
return None
if prefer_many_values:
candidates = sorted(candidates, key=lambda x: (x["score"], x["non_null"], x["idx"]), reverse=True)
else:
candidates = sorted(candidates, key=lambda x: (x["score"], -x["non_null"], -x["idx"]), reverse=True)
return candidates[0]["col"]
def find_main_columns(df):
no_col = find_best_col(df, ["no", "๋ฒํธ", "์๋ฒ"], default_index=0)
korean_ing_col = find_best_col(
df,
["ํ๊ธ ํ์คํ ๋ช
์นญ", "ํ๊ธ ์ฑ๋ถ๋ช
", "๊ตญ๋ฌธ ์ฑ๋ถ๋ช
", "ํ๊ธ์ฑ๋ถ๋ช
", "korean", "๊ตญ๋ฌธinci", "์ฑ๋ถ๋ช
"],
default_index=1 if len(df.columns) > 1 else None,
exclude_cols=[no_col],
)
inci_col = find_best_col(
df,
["ingredient name (inci)", "inci name", "inci", "ingredient", "์ ์ฑ๋ถ", "๊ตฌ์ฑ"],
default_index=2 if len(df.columns) > 2 else None,
exclude_cols=[no_col, korean_ing_col],
)
function_col = find_best_col(
df,
["function", "๊ธฐ๋ฅ", "์ฉ๋"],
default_index=3 if len(df.columns) > 3 else None,
exclude_cols=[no_col, korean_ing_col, inci_col],
)
cas_col = find_best_col(
df,
["cas.no", "cas no", "cas", "cas๋ฒํธ", "cas no."],
default_index=4 if len(df.columns) > 4 else None,
exclude_cols=[no_col, korean_ing_col, inci_col, function_col],
)
source_col = find_best_col(
df,
["source", "์ถ์ฒ", "icid"],
default_index=5 if len(df.columns) > 5 else None,
exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col],
)
formula_col = find_numeric_col(
df,
["%(w/w)", "w/w", "in formula", "formula", "์ฒ๋ฐฉ", "์ต์ข
", "์ ํ ๋ด", "์ ํ๋ด", "๋ฐฐํฉ๋", "ํจ๋", "%"],
default_index=6 if len(df.columns) > 6 else None,
exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col],
prefer_many_values=True,
)
trade_ko_col = find_optional_col(
df,
["trade name(๊ตญ๋ฌธ)", "trade name ๊ตญ๋ฌธ", "์๋ฃ๋ช
", "์ํ๋ช
", "๊ตญ๋ฌธ"],
exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col, formula_col],
)
trade_en_col = find_optional_col(
df,
["trade name(์๋ฌธ)", "trade name ์๋ฌธ", "trade", "raw material", "material", "์๋ฌธ"],
exclude_cols=[no_col, korean_ing_col, inci_col, function_col, cas_col, source_col, formula_col, trade_ko_col],
)
return {
"no_col": no_col,
"korean_ing_col": korean_ing_col,
"inci_col": inci_col,
"function_col": function_col,
"cas_col": cas_col,
"source_col": source_col,
"formula_col": formula_col,
"trade_ko_col": trade_ko_col,
"trade_en_col": trade_en_col,
}
# ============================================================
# 5. ์
๋ ฅ ์์
์ ๋ฆฌ / ์ ์ฑ๋ถ ํ ์์ฑ
# ============================================================
def clean_input_df(df, cols):
no_col = cols["no_col"]
korean_ing_col = cols["korean_ing_col"]
inci_col = cols["inci_col"]
footer_markers = [
"commitment of the manufacturer",
"the manufacturer here",
"it is illegal",
"rebom co",
"myeonghaksandanseo",
"sejong special",
"tel :",
"fax :",
"lab no.",
"permission",
]
keep_indices = []
footer_started = False
for idx, row in df.iterrows():
row_values = [safe_str(v) for v in row.values]
row_text = " ".join([v for v in row_values if v]).strip()
row_text_lower = row_text.lower()
if not row_text:
continue
no_text = safe_str(row.get(no_col, "")).lower() if no_col in df.columns else ""
korean_text = safe_str(row.get(korean_ing_col, "")).lower() if korean_ing_col in df.columns else ""
inci_text = safe_str(row.get(inci_col, "")).lower() if inci_col in df.columns else ""
if no_text in ["no", "no.", "๋ฒํธ", "์๋ฒ"]:
continue
if korean_text in ["ํ๊ธ ํ์คํ ๋ช
์นญ", "ํ๊ธ ์ฑ๋ถ๋ช
", "ํ๊ธ์ฑ๋ถ๋ช
", "๊ตญ๋ฌธ ์ฑ๋ถ๋ช
"]:
continue
if inci_text in ["ingredient name (inci)", "inci", "inci name"]:
continue
if (
is_total_like_text(no_text)
or is_total_like_text(korean_text)
or is_total_like_text(inci_text)
or row_has_total_like(row_values)
):
footer_started = True
continue
if any(marker in row_text_lower for marker in footer_markers):
footer_started = True
continue
if footer_started:
continue
keep_indices.append(idx)
return df.loc[keep_indices].reset_index(drop=True)
def make_grouped_materials(df):
cols = find_main_columns(df)
cleaned_df = clean_input_df(df, cols)
no_col = cols["no_col"]
korean_ing_col = cols["korean_ing_col"]
inci_col = cols["inci_col"]
function_col = cols["function_col"]
cas_col = cols["cas_col"]
source_col = cols["source_col"]
formula_col = cols["formula_col"]
trade_ko_col = cols.get("trade_ko_col")
trade_en_col = cols.get("trade_en_col")
row_materials = []
for _, row in cleaned_df.iterrows():
no_value = format_no(row.get(no_col, "")) if no_col in row else ""
korean_ing = safe_str(row.get(korean_ing_col, "")) if korean_ing_col in row else ""
inci_name = safe_str(row.get(inci_col, "")) if inci_col in row else ""
if (
is_total_like_text(no_value)
or is_total_like_text(korean_ing)
or is_total_like_text(inci_name)
or row_has_total_like(row.values)
):
continue
if not korean_ing and not inci_name:
continue
function_value = safe_str(row.get(function_col, "")) if function_col and function_col in row else ""
cas_value = safe_str(row.get(cas_col, "")) if cas_col and cas_col in row else ""
source_value = safe_str(row.get(source_col, "")) if source_col and source_col in row else ""
formula_value = format_amount(row.get(formula_col)) if formula_col and formula_col in row else ""
if not source_value:
source_value = "ICID"
trade_ko = safe_str(row.get(trade_ko_col, "")) if trade_ko_col and trade_ko_col in row else korean_ing
trade_en = safe_str(row.get(trade_en_col, "")) if trade_en_col and trade_en_col in row else inci_name
component = {
"ํ๊ธ ์ฑ๋ถ๋ช
": korean_ing,
"INCI Name": inci_name,
"FUNCTION": function_value,
"CAS.No": cas_value,
"SOURCE": source_value,
"In formula(w/w %)": formula_value,
"amount_float": to_number(row.get(formula_col)) if formula_col and formula_col in row else None,
}
material = {
"NO": no_value,
"Trade name(๊ตญ๋ฌธ)": trade_ko,
"Trade name(์๋ฌธ)": trade_en,
"Components": [component],
}
row_materials.append(material)
ingredient_totals = defaultdict(float)
ingredient_amount_parts = defaultdict(list)
for material in row_materials:
comp = material["Components"][0]
identity = get_identity_text(material, comp)
amount = comp.get("amount_float")
if amount is None:
continue
for canonical, rule in FRAGRANCE_ALLERGEN_RULES.items():
for alias in rule.get("aliases", []):
alias_norm = normalize_text(alias)
if alias_norm and alias_norm in identity:
ingredient_totals[canonical] += amount
ingredient_amount_parts[canonical].append(amount)
meta = {
"cols": cols,
"cleaned_df": cleaned_df,
"ingredient_totals": ingredient_totals,
"ingredient_amount_parts": ingredient_amount_parts,
}
return row_materials, meta
# ============================================================
# 6. ์์ฝ์ฒ ์ค์๊ฐ ์กฐํ
# ============================================================
def extract_terms_for_mfds_live(row_items):
terms = []
for item in row_items:
comp = item["component"]
for value in [comp.get("INCI Name", ""), comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", "")]:
value = safe_str(value)
if value and len(normalize_compact(value)) >= 3:
terms.append(value)
seen = set()
unique = []
for term in terms:
key = normalize_compact(term)
if key and key not in seen:
seen.add(key)
unique.append(term)
return unique
def mfds_live_visible_text(page):
try:
html = page.content()
if BeautifulSoup is not None:
soup = BeautifulSoup(html, "html.parser")
for tag in soup(["script", "style", "nav", "footer", "header"]):
tag.decompose()
return soup.get_text(separator=" ")
return page.locator("body").inner_text(timeout=5000)
except Exception:
try:
return page.locator("body").inner_text(timeout=5000)
except Exception:
return ""
def mfds_live_fill_search_input(page, term):
selectors = [
"input[type='search']",
"input[type='text']",
"input:not([type])",
]
for selector in selectors:
try:
loc = page.locator(selector)
for i in range(min(loc.count(), 20)):
item = loc.nth(i)
try:
if item.is_visible(timeout=1000) and item.is_enabled(timeout=1000):
item.fill(term, timeout=3000)
return True
except Exception:
continue
except Exception:
continue
return False
def mfds_live_click_search(page):
for txt in ["๊ฒ์", "์กฐํ", "Search"]:
try:
loc = page.get_by_text(txt, exact=True)
if loc.count() > 0:
loc.first.click(timeout=3000)
return True
except Exception:
pass
for selector in ["button", "input[type='submit']", "a"]:
try:
loc = page.locator(selector)
for i in range(min(loc.count(), 20)):
item = loc.nth(i)
try:
if selector == "input[type='submit']":
item.click(timeout=3000)
return True
text = item.inner_text(timeout=500)
if "๊ฒ์" in text or "์กฐํ" in text:
item.click(timeout=3000)
return True
except Exception:
continue
except Exception:
continue
return False
def mfds_live_click_result_row(page, term):
term_norm = normalize_compact(term)
for selector in ["table tbody tr", "tbody tr", "tr"]:
try:
rows = page.locator(selector)
for i in range(min(rows.count(), 30)):
row = rows.nth(i)
try:
row_text = row.inner_text(timeout=1000)
except Exception:
continue
if term_norm and term_norm in normalize_compact(row_text):
row.click(timeout=3000)
page.wait_for_timeout(1500)
return True
except Exception:
continue
try:
loc = page.get_by_text(term, exact=False)
if loc.count() > 0:
loc.first.click(timeout=3000)
page.wait_for_timeout(1500)
return True
except Exception:
pass
return False
def parse_mfds_live_text(term, text):
clean = " ".join(safe_str(text).split())
if not clean:
return []
lower_clean = clean.lower()
country_patterns = {
"EU": ["eu", "์ ๋ฝ", "์ ๋ฝ์ฐํฉ", "european union", "europe"],
"FDA": ["๋ฏธ๊ตญ", "usa", "fda", "united states"],
"Korea": ["ํ๊ตญ", "๋ํ๋ฏผ๊ตญ", "korea"],
"์ผ๋ณธ": ["์ผ๋ณธ", "japan"],
"์ค๊ตญ": ["์ค๊ตญ", "china"],
"ASEAN": ["asean", "์์ธ์"],
"UK": ["์๊ตญ", "uk", "united kingdom"],
}
rows = []
for country, aliases in country_patterns.items():
found_index = -1
for alias in aliases:
idx = lower_clean.find(alias)
if idx >= 0:
found_index = idx
break
if found_index < 0:
continue
start = max(0, found_index - 350)
end = min(len(clean), found_index + 1000)
snippet = clean[start:end]
snippet_lower = snippet.lower()
category = "์ ํ"
if any(k in snippet_lower for k in ["๊ธ์ง", "์ฌ์ฉ๊ธ์ง", "๋ฐฐํฉ๊ธ์ง", "prohibited", "banned", "not allowed"]):
category = "๊ธ์ง"
limit = ""
limit_match = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*%", snippet)
if limit_match:
limit = limit_match.group(0).replace(" ", "")
rows.append({
"์๋ฃ๋ช
": term,
"INCI": term,
"CAS.No": "",
"๊ตฌ๋ถ": category,
"๊ตญ๊ฐ": country,
"๊ท์ ๋ด์ฉ": snippet[:500],
"ํ๋": limit,
"์กฐ๊ฑด": "",
"์ถ์ฒ": "MFDS live: " + MFDS_LIVE_URL,
"์์ธ์๋ฌธ": clean[:5000],
})
return rows
def mfds_live_lookup_terms(terms, max_terms=30, headless=True):
if not PLAYWRIGHT_AVAILABLE or sync_playwright is None:
return pd.DataFrame(), "playwright ๋ฏธ์ค์น ๋๋ ๋ธ๋ผ์ฐ์ ๋ฏธ์ค์น"
terms = [safe_str(t) for t in terms if safe_str(t)]
terms = terms[:int(max_terms)] if max_terms else terms[:30]
all_rows = []
errors = []
try:
with sync_playwright() as p:
browser = p.chromium.launch(headless=bool(headless))
context = browser.new_context(
viewport={"width": 1400, "height": 1000},
user_agent="Mozilla/5.0 reBom Regulatory Screening",
)
page = context.new_page()
for idx, term in enumerate(terms, start=1):
try:
print(f"MFDS ์ค์๊ฐ ์กฐํ {idx}/{len(terms)}: {term}")
page.goto(MFDS_LIVE_URL, wait_until="domcontentloaded", timeout=30000)
page.wait_for_timeout(2000)
if not mfds_live_fill_search_input(page, term):
errors.append(f"{term}: ๊ฒ์ ์
๋ ฅ์ฐฝ ์ฐพ๊ธฐ ์คํจ")
continue
if not mfds_live_click_search(page):
try:
page.keyboard.press("Enter")
except Exception:
pass
page.wait_for_timeout(2500)
mfds_live_click_result_row(page, term)
page.wait_for_timeout(1500)
text = mfds_live_visible_text(page)
rows = parse_mfds_live_text(term, text)
if rows:
all_rows.extend(rows)
else:
errors.append(f"{term}: ๊ตญ๊ฐ๋ณ ์์ธ์ ๋ณด ๋ฏธ๊ฒ์ถ")
except Exception as e:
errors.append(f"{term}: {e}")
context.close()
browser.close()
except Exception as e:
return pd.DataFrame(), f"MFDS ๋ธ๋ผ์ฐ์ ์คํ ์คํจ: {e}"
df = pd.DataFrame(all_rows)
msg = f"MFDS ์ค์๊ฐ ์กฐํ ์๋ฃ: ๊ฒ์์ด {len(terms)}๊ฐ, ๊ฒฐ๊ณผ {len(df)}ํ"
if errors:
msg += " / ์ผ๋ถ ์คํจ: " + " ; ".join(errors[:5])
if len(errors) > 5:
msg += f" ์ธ {len(errors) - 5}๊ฑด"
return df, msg
def ingredient_matches_mfds_row(material, component, row):
identity_values = [
component.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
component.get("INCI Name", ""),
material.get("Trade name(๊ตญ๋ฌธ)", ""),
material.get("Trade name(์๋ฌธ)", ""),
]
identity = normalize_compact(" ".join([safe_str(x) for x in identity_values if safe_str(x)]))
row_terms = [row.get("์๋ฃ๋ช
", ""), row.get("INCI", ""), row.get("CAS.No", "")]
for term in row_terms:
term_norm = normalize_compact(term)
if term_norm and len(term_norm) >= 3 and term_norm in identity:
return True
return False
def mfds_row_country_matches(country, row_country):
row_country_norm = normalize_compact(row_country)
col = display_country(country)
aliases = [country, col, country_key(country)]
if col == "Korea":
aliases += ["ํ๊ตญ", "๋ํ๋ฏผ๊ตญ", "KOREA", "KR"]
elif col == "FDA":
aliases += ["๋ฏธ๊ตญ", "USA", "US", "United States", "FDA"]
elif col == "EU":
aliases += ["EU", "์ ๋ฝ", "์ ๋ฝ์ฐํฉ", "European Union", "Europe"]
aliases_norm = [normalize_compact(x) for x in aliases if safe_str(x)]
return any(alias and alias in row_country_norm for alias in aliases_norm)
def evaluate_mfds_detail_rule(country, material, component, mfds_df):
if mfds_df is None or mfds_df.empty:
return None
hits = []
for _, row in mfds_df.iterrows():
if ingredient_matches_mfds_row(material, component, row) and mfds_row_country_matches(country, row.get("๊ตญ๊ฐ", "")):
hits.append(row)
if not hits:
return None
row = hits[0]
category = safe_str(row.get("๊ตฌ๋ถ", "")) or "์ ํ"
regulation = safe_str(row.get("๊ท์ ๋ด์ฉ", ""))
limit = safe_str(row.get("ํ๋", ""))
source = safe_str(row.get("์ถ์ฒ", "MFDS live"))
parts = [category]
if limit:
parts.append(f"ํ๋ {limit}")
if regulation:
parts.append(regulation[:300])
result_text = " / ".join([p for p in parts if p])
return {
"๋ํ INCI": safe_str(component.get("INCI Name", "")) or safe_str(row.get("์๋ฃ๋ช
", "")) or "-",
"๊ฒฐ๊ณผ": result_text,
"ํ์๋ฌธ๊ตฌ": normalize_formula_country_text(result_text, display_country(country), component.get("INCI Name", "")),
"๋น๊ณ ": source,
}
# ============================================================
# 7. ๋ก์ปฌ ๊ท์น ํ์
# ============================================================
def evaluate_limit_rule(country, material, component, rule_group, rule_type_name):
ckey = country_key(country)
key = match_rule_key(material, component, rule_group)
if not key:
return None
rule = rule_group[key]
country_rule = rule.get(ckey)
if not country_rule:
return None
label = rule.get("label", key)
amount = component.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
status = country_rule.get("status", "allowed")
formula_text = country_rule.get("formula_text", "")
if status == "prohibited":
return {
"๋ํ INCI": label,
"๊ฒฐ๊ณผ": f"{label} ๋ฐฐํฉ๊ธ์ง / ํ์ฌ ํจ๋ {amount_text}% / ์ฌ๊ฒํ ํ์",
"ํ์๋ฌธ๊ตฌ": formula_text or "๋ฐฐํฉ๊ธ์ง",
"๋น๊ณ ": "-",
}
limit = country_rule.get("limit")
if limit is not None:
if amount is not None and amount > limit:
result_text = f"{rule_type_name} / {label} ํ์ฌ ํจ๋ {amount_text}%, ํ๋ {format_percent(limit)}% ์ด๊ณผ(์ฌ๊ฒํ ํ์)"
else:
result_text = f"{rule_type_name} / {label} ํ์ฌ ํจ๋ {amount_text}%, ํ๋ {format_percent(limit)}% ์ด๋ด(ํต๊ณผ)"
return {
"๋ํ INCI": label,
"๊ฒฐ๊ณผ": result_text,
"ํ์๋ฌธ๊ตฌ": formula_text or f"๋ฐฐํฉํ๋: {format_percent(limit)}%",
"๋น๊ณ ": "-",
}
return {
"๋ํ INCI": label,
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts):
ckey = country_key(country)
amount = component.get("amount_float")
uv_result = evaluate_limit_rule(country, material, component, UV_FILTER_RULES, "UV ํํฐ")
if uv_result is not None:
return uv_result
preservative_result = evaluate_limit_rule(country, material, component, PRESERVATIVE_RULES, "๋ณด์กด์ /์ ํ์ฑ๋ถ")
if preservative_result is not None:
return preservative_result
functional_key = match_rule_key(material, component, FUNCTIONAL_KOREA_RULES)
if ckey == "KOREA" and functional_key:
rule = FUNCTIONAL_KOREA_RULES[functional_key]
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
return {
"๋ํ INCI": rule["label"],
"๊ฒฐ๊ณผ": rule["result"].format(amount=amount_text),
"ํ์๋ฌธ๊ตฌ": rule.get("formula_text", "๊ธฐ๋ฅ์ฑ ํ์ธ"),
"๋น๊ณ ": "๊ธฐ๋ฅ์ฑ ํ์ยท๊ด๊ณ ์ฌ๋ถ ํ์ธ",
}
identity = get_identity_text(material, component)
for fragrance_key, rule in FRAGRANCE_ALLERGEN_RULES.items():
matched = False
for alias in rule.get("aliases", []):
if normalize_text(alias) in identity:
matched = True
break
if not matched:
continue
if ckey not in ["EU", "EU_FUTURE", "UK", "KOREA"]:
continue
total_amount = ingredient_totals.get(fragrance_key, amount)
total_text = format_percent(total_amount) if total_amount is not None else "ํจ๋ ํ์ธ ํ์"
result_text = (
f"ํฅ๋ฃ ์๋ ๋ฅด๊ฒ / {rule['label']} ์ด {total_text}%, "
f"Leave-on ๊ธฐ์ค {format_percent(rule['leave_on'])}%, "
f"Wash-off ๊ธฐ์ค {format_percent(rule['wash_off'])}% ํ์ธ ํ์"
)
return {
"๋ํ INCI": rule["label"],
"๊ฒฐ๊ณผ": result_text,
"ํ์๋ฌธ๊ตฌ": "ํ์๊ธฐ์ค ํ์ธ",
"๋น๊ณ ": "-",
}
if amount is None:
return {
"๋ํ INCI": safe_str(component.get("INCI Name", "")) or "-",
"๊ฒฐ๊ณผ": "ํจ๋ ์ ๋ณด ์์ / In formula(w/w %) ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": "ํจ๋ ํ์ธ",
"๋น๊ณ ": "-",
}
return None
# ============================================================
# 8. GPT ๋ณด์กฐ ํ์
# ============================================================
def parse_country_response(text):
result = {
"๋ํ INCI": "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
for line in safe_str(text).splitlines():
line = line.strip()
if line.startswith("๋ํ INCI:"):
result["๋ํ INCI"] = line.split(":", 1)[1].strip() or "-"
elif line.startswith("๊ฒฐ๊ณผ:"):
result["๊ฒฐ๊ณผ"] = line.split(":", 1)[1].strip() or NO_EVIDENCE_TEXT
elif line.startswith("ํ์๋ฌธ๊ตฌ:"):
result["ํ์๋ฌธ๊ตฌ"] = line.split(":", 1)[1].strip() or "Pass"
elif line.startswith("๋น๊ณ :"):
result["๋น๊ณ "] = line.split(":", 1)[1].strip() or "-"
return result
def clean_json_text(text):
text = safe_str(text)
text = re.sub(r"^```json\s*", "", text.strip(), flags=re.IGNORECASE)
text = re.sub(r"^```\s*", "", text.strip())
text = re.sub(r"\s*```$", "", text.strip())
match = re.search(r"\[.*\]", text, flags=re.DOTALL)
if match:
return match.group(0)
match = re.search(r"\{.*\}", text, flags=re.DOTALL)
if match:
return match.group(0)
return text
def sanitize_country_result(parsed, country_col="", component=None):
if not isinstance(parsed, dict):
parsed = {}
component = component or {}
representative = safe_str(parsed.get("๋ํ INCI", "")) or safe_str(component.get("INCI Name", "")) or "-"
result_text = safe_str(parsed.get("๊ฒฐ๊ณผ", "")) or NO_EVIDENCE_TEXT
note = safe_str(parsed.get("๋น๊ณ ", "")) or "-"
display_text = safe_str(parsed.get("ํ์๋ฌธ๊ตฌ", ""))
if not display_text:
display_text = normalize_formula_country_text(
result_text,
country_col=country_col,
inci_name=safe_str(component.get("INCI Name", "")),
amount_text=safe_str(component.get("In formula(w/w %)", "")),
)
bad_tokens = [
"๊ท์ ๋ช
",
"์ด๋ ๊ณ์ฐ",
"๊ท์ / ์ด๋",
"{๊ท์ ๊ตฐ๋ช
}",
"{์ฑ๋ถ๋ช
",
"{ํจ๋}",
"{๊ธฐ์ค์น}",
"placeholder",
"N/A",
"n/a",
]
if any(token in result_text for token in bad_tokens):
result_text = "ํ์ธ ํ์ / ๊ท์ ์ธ๋ถ ๊ณ์ฐ ์ฌํ์ธ ํ์"
display_text = "ํ์ธ ํ์"
if note == "-":
note = "๊ตฌ์ฒด ํ๋ ๋๋ ์ด๋ ๊ณ์ฐ๊ฐ ํ์ธ ํ์"
return {
"๋ํ INCI": representative,
"๊ฒฐ๊ณผ": result_text,
"ํ์๋ฌธ๊ตฌ": display_text,
"๋น๊ณ ": note,
}
def make_eval_cache_key(country, component):
amount = component.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
db_signature = get_current_db_signature(country)
return (
str(country),
str(db_signature),
safe_str(component.get("INCI Name", "")).lower(),
safe_str(component.get("ํ๊ธ ์ฑ๋ถ๋ช
", "")).lower(),
amount_text,
)
def has_meaningful_search_hit(db, search_text, ingredient_names, k=MEANINGFUL_HIT_K):
if not db:
return False, ""
try:
docs = db.similarity_search(search_text, k=k)
context = "\n".join([d.page_content for d in docs])
except Exception:
return False, ""
context_norm = normalize_compact(context)
for name in ingredient_names:
name_norm = normalize_compact(name)
if name_norm and len(name_norm) >= 3 and name_norm in context_norm:
return True, context
return False, context
def evaluate_component_with_llm(country, material, component, llm, target_id=""):
db = build_database(country)
country_col = display_country(country)
inci_name = safe_str(component.get("INCI Name", ""))
korean_name = safe_str(component.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""))
amount = component.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
if not inci_name and not korean_name:
return {
"๋ํ INCI": "-",
"๊ฒฐ๊ณผ": "",
"ํ์๋ฌธ๊ตฌ": "",
"๋น๊ณ ": "-",
}
if not db:
result = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
log_search_context(target_id, country, component, result["๊ฒฐ๊ณผ"], "NO_DB", "ํด๋น ๊ตญ๊ฐ/์ฑ๋ ๊ท์ DB ์์")
return result
cache_key = make_eval_cache_key(country, component)
if cache_key in EVAL_CACHE:
return EVAL_CACHE[cache_key]
trade_ko = material.get("Trade name(๊ตญ๋ฌธ)", "")
trade_en = material.get("Trade name(์๋ฌธ)", "")
search_text = f"""
๊ตญ๊ฐ/์ฑ๋: {country}
์๋ฃ๋ช
๊ตญ๋ฌธ: {trade_ko}
์๋ฃ๋ช
์๋ฌธ: {trade_en}
๊ฒํ ์ฑ๋ถ ๊ตญ๋ฌธ: {korean_name}
๊ฒํ ์ฑ๋ถ INCI/CAS: {inci_name}
์ต์ข
์ ํ ๋ด ํจ๋: {amount_text}%
์ ํ์ ํ: Leave-on ๋ฐ Wash-off ๊ธฐ์ค ๋ชจ๋ ํ์ธ
"""
has_hit, pre_context = has_meaningful_search_hit(
db=db,
search_text=search_text,
ingredient_names=[inci_name, korean_name],
k=MEANINGFUL_HIT_K,
)
if not has_hit:
result = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
EVAL_CACHE[cache_key] = result
log_search_context(target_id, country, component, result["๊ฒฐ๊ณผ"], "NO_MEANINGFUL_HIT", pre_context)
return result
docs = db.similarity_search(search_text, k=RAG_TOP_K_SINGLE)
context = "\n".join([d.page_content for d in docs])
prompt = f"""
๋๋ ํ์ฅํ ์ ์ฑ๋ถ ๊ท์ ์คํฌ๋ฆฌ๋ ์ ๋ฌธ๊ฐ์ผ.
์๋ ๋จ์ผ ๊ตฌ์ฑ์ฑ๋ถ์ ๋ฐ๋์ "{country}" ๊ธฐ์ค์ผ๋ก๋ง ๊ฒํ ํด.
[์ ๋ ๊ท์น]
- ํ์ฌ ๊ฒํ ๊ตญ๊ฐ๋ "{country}"์ด๋ค.
- ์๋ ๊ฒ์ ์๋ฌธ์ "{country}" ํด๋์์๋ง ๊ฒ์๋ ๊ทผ๊ฑฐ๋ค.
- ์ธ๋ถ ์ง์, ํ์ต ์ง์, ์ผ๋ฐ ๊ท์ ์ง์์ ์ฌ์ฉํ์ง ๋ง.
- ๋ค๋ฅธ ๊ตญ๊ฐ ๊ท์ ์ ํ์ฌ ๊ตญ๊ฐ์ ์์ ์ ์ฉํ์ง ๋ง.
- ๊ฒ์ ์๋ฌธ์ ๋ช
์๋์ง ์์ ์ ํ, ๋ฐฐํฉ๊ธ์ง, ๋ฐฐํฉํ๋๋ ๋ง๋ค์ง ๋ง.
- ๊ฒ์ ์๋ฌธ์ ๋ช
์๋ ์ ํ/๊ธ์ง/ํ๋ ๊ทผ๊ฑฐ๊ฐ ์์ผ๋ฉด ๊ฒฐ๊ณผ๋ ์ ํํ "{NO_EVIDENCE_TEXT}"์ผ๋ก ์์ฑํด.
[๊ฒํ ์ฑ๋ถ]
๊ตญ๋ฌธ๋ช
: {korean_name}
INCI/CAS: {inci_name}
์ต์ข
์ ํ ๋ด ํจ๋: {amount_text}%
[๊ฒ์๋ {country} ๊ท์ ์๋ฌธ]
{context}
๋ฐ๋์ ์๋ ํ์์ผ๋ก๋ง ๋ต๋ณํด.
๋ํ INCI:
๊ฒฐ๊ณผ:
ํ์๋ฌธ๊ตฌ:
๋น๊ณ :
ํ์๋ฌธ๊ตฌ ์์ฑ ๊ท์น:
- ๋ฌธ์ ์์ผ๋ฉด "Pass"
- ๋ฐฐํฉํ๋๊ฐ ์์ผ๋ฉด "๋ฐฐํฉํ๋: 10%"์ฒ๋ผ ์งง๊ฒ ์์ฑ
- ์คํ๋ ์ด/๊ธฐํ์ ํ์ฒ๋ผ ์กฐ๊ฑด์ด ์์ผ๋ฉด ์ค๋ฐ๊ฟ์ผ๋ก ์์ฑ
- ๋ผ๋ฒจ ํ์๊ฐ ํ์ํ๋ฉด "๋ผ๋ฒจ๋ง ํ์"
- ์ ํํ ํ๋จ์ด ์ด๋ ค์ฐ๋ฉด "ํ์ธ ํ์"
"""
try:
response = llm.invoke(prompt).content
parsed = parse_country_response(response)
parsed = sanitize_country_result(parsed, country_col=country_col, component=component)
EVAL_CACHE[cache_key] = parsed
log_search_context(target_id, country, component, parsed["๊ฒฐ๊ณผ"], "GPT_SINGLE", context)
return parsed
except Exception as e:
result = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": "ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": "ํ์ธ ํ์",
"๋น๊ณ ": str(e),
}
log_search_context(target_id, country, component, result["๊ฒฐ๊ณผ"], "GPT_SINGLE_ERROR", str(e))
return result
def evaluate_components_with_llm_batch(country, targets, llm):
results = {}
if not targets:
return results
db = build_database(country)
country_col = display_country(country)
if not db:
for item in targets:
comp = item["component"]
inci_name = safe_str(comp.get("INCI Name", ""))
results[item["target_id"]] = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
log_search_context(
item["target_id"],
country,
comp,
NO_EVIDENCE_TEXT,
"NO_DB",
"ํด๋น ๊ตญ๊ฐ/์ฑ๋ ๊ท์ DB ์์",
)
return results
uncached_targets = []
for item in targets:
comp = item["component"]
cache_key = make_eval_cache_key(country, comp)
if cache_key in EVAL_CACHE:
results[item["target_id"]] = EVAL_CACHE[cache_key]
else:
uncached_targets.append(item)
filtered_targets = []
for item in uncached_targets:
material = item["material"]
comp = item["component"]
inci_name = safe_str(comp.get("INCI Name", ""))
korean_name = safe_str(comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""))
amount = comp.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
search_text = f"""
๊ตญ๊ฐ/์ฑ๋: {country}
์๋ฃ๋ช
๊ตญ๋ฌธ: {material.get("Trade name(๊ตญ๋ฌธ)", "")}
์๋ฃ๋ช
์๋ฌธ: {material.get("Trade name(์๋ฌธ)", "")}
๊ฒํ ์ฑ๋ถ ๊ตญ๋ฌธ: {korean_name}
๊ฒํ ์ฑ๋ถ INCI/CAS: {inci_name}
์ต์ข
์ ํ ๋ด ํจ๋: {amount_text}%
"""
has_hit, context = has_meaningful_search_hit(
db=db,
search_text=search_text,
ingredient_names=[inci_name, korean_name],
k=MEANINGFUL_HIT_K,
)
if has_hit:
filtered_targets.append(item)
else:
result = {
"๋ํ INCI": inci_name or "-",
"๊ฒฐ๊ณผ": NO_EVIDENCE_TEXT,
"ํ์๋ฌธ๊ตฌ": "Pass",
"๋น๊ณ ": "-",
}
results[item["target_id"]] = result
EVAL_CACHE[make_eval_cache_key(country, comp)] = result
log_search_context(
item["target_id"],
country,
comp,
result["๊ฒฐ๊ณผ"],
"NO_MEANINGFUL_HIT",
context,
)
uncached_targets = filtered_targets
if not uncached_targets:
return results
for batch in chunk_list(uncached_targets, BATCH_SIZE):
target_payload = []
search_blocks = []
for item in batch:
comp = item["component"]
inci_name = safe_str(comp.get("INCI Name", ""))
korean_name = safe_str(comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""))
amount = comp.get("amount_float")
amount_text = format_percent(amount) if amount is not None else "ํจ๋ ํ์ธ ํ์"
target_payload.append({
"target_id": item["target_id"],
"์ฑ๋ถ ๊ตญ๋ฌธ๋ช
": korean_name,
"INCI/CAS": inci_name,
"์ต์ข
์ ํ ๋ด ํจ๋(%)": amount_text,
})
search_blocks.append(f"{inci_name} {korean_name} {amount_text}%")
search_text = f"""
๊ตญ๊ฐ/์ฑ๋: {country}
๊ฒํ ๋์ ์ฑ๋ถ:
{chr(10).join(search_blocks)}
"""
try:
docs = db.similarity_search(search_text, k=RAG_TOP_K_BATCH)
context = "\n".join([d.page_content for d in docs])
prompt = f"""
๋๋ ํ์ฅํ ์ ์ฑ๋ถ ๊ท์ ์คํฌ๋ฆฌ๋ ์ ๋ฌธ๊ฐ์ผ.
์๋ ์ฌ๋ฌ ๊ตฌ์ฑ์ฑ๋ถ์ ๋ฐ๋์ "{country}" ๊ธฐ์ค์ผ๋ก๋ง ๊ฒํ ํด.
[์ ๋ ๊ท์น]
- ํ์ฌ ๊ฒํ ๊ตญ๊ฐ๋ "{country}"์ด๋ค.
- ์๋ ๊ฒ์ ์๋ฌธ์ "{country}" ํด๋์์๋ง ๊ฒ์๋ ๊ทผ๊ฑฐ๋ค.
- ์ธ๋ถ ์ง์, ํ์ต ์ง์, ์ผ๋ฐ ๊ท์ ์ง์์ ์ฌ์ฉํ์ง ๋ง.
- ๊ฒ์ ์๋ฌธ์ ๊ทผ๊ฑฐ๊ฐ ์์ผ๋ฉด ๊ฒฐ๊ณผ๋ ์ ํํ "{NO_EVIDENCE_TEXT}"์ผ๋ก ์์ฑํด.
[๊ฒํ ๋์ JSON]
{json.dumps(target_payload, ensure_ascii=False, indent=2)}
[๊ฒ์๋ {country} ๊ท์ ์๋ฌธ]
{context}
๋ฐ๋์ JSON ๋ฐฐ์ด๋ง ์ถ๋ ฅํด.
๋งํฌ๋ค์ด, ์ค๋ช
๋ฌธ, ์ฝ๋๋ธ๋ก ์์ด ์์ JSON๋ง ์ถ๋ ฅํด.
์ถ๋ ฅ ํ์:
[
{{
"target_id": "์
๋ ฅ target_id ๊ทธ๋๋ก",
"๋ํ INCI": "๋ํ INCI ๋๋ -",
"๊ฒฐ๊ณผ": "{NO_EVIDENCE_TEXT} ๋๋ ๊ท์ ๋ด์ฉ",
"ํ์๋ฌธ๊ตฌ": "Pass ๋๋ ๋ฐฐํฉํ๋/๋ผ๋ฒจ๋ง/ํ์ธ ํ์ ๋ฑ ์งง์ ๋ฌธ๊ตฌ",
"๋น๊ณ ": "-"
}}
]
"""
response = llm.invoke(prompt).content
parsed = json.loads(clean_json_text(response))
if isinstance(parsed, dict):
parsed = [parsed]
parsed_by_id = {}
for obj in parsed:
if not isinstance(obj, dict):
continue
target_id = safe_str(obj.get("target_id", ""))
if not target_id:
continue
item_comp = None
for item in batch:
if item["target_id"] == target_id:
item_comp = item["component"]
break
parsed_by_id[target_id] = sanitize_country_result(
obj,
country_col=country_col,
component=item_comp or {},
)
for item in batch:
target_id = item["target_id"]
comp = item["component"]
if target_id in parsed_by_id:
result = parsed_by_id[target_id]
results[target_id] = result
EVAL_CACHE[make_eval_cache_key(country, comp)] = result
log_search_context(target_id, country, comp, result["๊ฒฐ๊ณผ"], "GPT_BATCH", context)
for item in batch:
target_id = item["target_id"]
if target_id in results:
continue
results[target_id] = evaluate_component_with_llm(
country=country,
material=item["material"],
component=item["component"],
llm=llm,
target_id=target_id,
)
except Exception as e:
print(f"batch GPT ํ์ ์คํจ: {country} / {e}")
for item in batch:
target_id = item["target_id"]
if target_id in results:
continue
results[target_id] = evaluate_component_with_llm(
country=country,
material=item["material"],
component=item["component"],
llm=llm,
target_id=target_id,
)
return results
# ============================================================
# 9. ์ถ๋ ฅ ๋ฐ์ดํฐ ๊ตฌ์ฑ
# ============================================================
def make_formula_statement_rows(row_items, country_cols):
rows = []
for item in row_items:
material = item["material"]
comp = item["component"]
row_data = item["row_data"]
no_value = safe_str(material.get("NO", ""))
korean_name = safe_str(comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""))
inci_name = safe_str(comp.get("INCI Name", ""))
if (
is_total_like_text(no_value)
or is_total_like_text(korean_name)
or is_total_like_text(inci_name)
):
continue
row = {
"NO.": no_value,
"ํ๊ธ ํ์คํ ๋ช
์นญ": korean_name,
"INGREDIENT NAME (INCI)": inci_name,
"FUNCTION": comp.get("FUNCTION", ""),
"CAS.No": comp.get("CAS.No", ""),
"SOURCE": comp.get("SOURCE", "ICID") or "ICID",
"%(w/w)": comp.get("In formula(w/w %)", ""),
}
for country_col in country_cols:
raw_text = safe_str(row_data.get(country_col, ""))
display_text = safe_str(row_data.get(country_col + "_display", ""))
if display_text:
row[country_col] = display_text
else:
row[country_col] = normalize_formula_country_text(
raw_text,
country_col=country_col,
inci_name=inci_name,
amount_text=comp.get("In formula(w/w %)", ""),
)
rows.append(row)
total = 0.0
for row in rows:
value = to_number(row.get("%(w/w)", ""))
if value is not None:
total += value
total_row = {
"NO.": "",
"ํ๊ธ ํ์คํ ๋ช
์นญ": "",
"INGREDIENT NAME (INCI)": "TOTAL",
"FUNCTION": "",
"CAS.No": "",
"SOURCE": "",
"%(w/w)": format_amount(total),
}
for country_col in country_cols:
total_row[country_col] = ""
rows.append(total_row)
return pd.DataFrame(rows)
def make_regulatory_summary_rows(row_items, country_cols):
rows = []
for item in row_items:
row_data = item["row_data"]
if not is_country_result_issue(row_data.get("Result", "")):
continue
row = {
"ํ๊ธ ์ฑ๋ถ๋ช
": row_data.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
"INCI Name": row_data.get("INCI Name", ""),
"In formula(w/w %)": row_data.get("In formula\n(w/w %)", ""),
"Result": row_data.get("Result", ""),
}
for country_col in country_cols:
value = safe_str(row_data.get(country_col, ""))
row[country_col] = value if is_country_result_issue(value) else "-"
row["๋น๊ณ "] = row_data.get("๋น๊ณ ", "-")
rows.append(row)
columns = ["ํ๊ธ ์ฑ๋ถ๋ช
", "INCI Name", "In formula(w/w %)", "Result"] + country_cols + ["๋น๊ณ "]
if not rows:
return pd.DataFrame(columns=columns)
return pd.DataFrame(rows)[columns]
def sum_formula_percent(formula_df):
total = 0.0
if formula_df is None or formula_df.empty:
return total
for _, row in formula_df.iterrows():
no_value = safe_str(row.get("NO.", ""))
korean_name = safe_str(row.get("ํ๊ธ ํ์คํ ๋ช
์นญ", ""))
inci_name = safe_str(row.get("INGREDIENT NAME (INCI)", ""))
if (
is_total_like_text(no_value)
or is_total_like_text(korean_name)
or is_total_like_text(inci_name)
):
continue
num = to_number(row.get("%(w/w)", ""))
if num is not None:
total += num
return total
# ============================================================
# 10. ์์
์ ์ฅ / ์คํ์ผ
# ============================================================
def write_output_workbook(out_path, product_name, formula_df, regulatory_df, raw_df):
with pd.ExcelWriter(out_path, engine="openpyxl") as writer:
formula_df.to_excel(writer, index=False, sheet_name="Formula Ingredients Statement", startrow=5)
regulatory_df.to_excel(writer, index=False, sheet_name="Regulatory Screening Summary")
raw_df.to_excel(writer, index=False, sheet_name="Evidence Log")
wb = load_workbook(out_path)
ws = wb["Formula Ingredients Statement"]
max_col = max(1, ws.max_column)
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=max_col)
ws["A1"] = "Formular Ingredients Statement"
ws["A1"].font = Font(bold=True, size=24, underline="single")
ws["A1"].alignment = Alignment(horizontal="center", vertical="center")
ws.merge_cells(start_row=4, start_column=1, end_row=4, end_column=max_col)
ws["A4"] = f"PRODUCT NAME : {safe_str(product_name)}"
ws["A4"].font = Font(bold=True, size=13)
ws["A4"].alignment = Alignment(horizontal="left", vertical="center")
wb.save(out_path)
style_output_workbook(out_path)
def style_output_workbook(path):
wb = load_workbook(path)
thin_border = Border(
left=Side(style="thin", color="808080"),
right=Side(style="thin", color="808080"),
top=Side(style="thin", color="808080"),
bottom=Side(style="thin", color="808080"),
)
header_font = Font(color="000000", bold=True, size=10)
body_font = Font(color="000000", size=10)
title_font = Font(color="000000", bold=True, size=24, underline="single")
product_font = Font(color="000000", bold=True, size=13)
warning_fill = PatternFill(start_color="FCE4D6", end_color="FCE4D6", fill_type="solid")
pass_fill = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid")
for ws in wb.worksheets:
if ws.title == "Formula Ingredients Statement":
header_row = 6
ws.sheet_view.showGridLines = False
ws.row_dimensions[1].height = 36
ws.row_dimensions[2].height = 20
ws.row_dimensions[3].height = 20
ws.row_dimensions[4].height = 26
ws.row_dimensions[5].height = 18
ws.row_dimensions[6].height = 28
ws["A1"].font = title_font
ws["A1"].alignment = Alignment(horizontal="center", vertical="center")
ws["A4"].font = product_font
ws["A4"].alignment = Alignment(horizontal="left", vertical="center")
for row in range(header_row, ws.max_row + 1):
for col in range(1, ws.max_column + 1):
cell = ws.cell(row=row, column=col)
cell.border = thin_border
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
cell.font = body_font
if row == header_row:
cell.font = header_font
if row > header_row:
value = safe_str(cell.value)
if value and value != "Pass" and col >= 8:
cell.fill = warning_fill
elif value == "Pass":
cell.fill = pass_fill
total_row = None
for row in range(header_row + 1, ws.max_row + 1):
if safe_str(ws.cell(row=row, column=3).value).upper() == "TOTAL":
total_row = row
break
if total_row:
for col in range(1, ws.max_column + 1):
cell = ws.cell(row=total_row, column=col)
cell.font = Font(bold=True)
cell.border = thin_border
cell.alignment = Alignment(horizontal="center", vertical="center")
try:
ws.merge_cells(start_row=total_row, start_column=2, end_row=total_row, end_column=6)
ws.cell(row=total_row, column=2).value = "TOTAL"
ws.cell(row=total_row, column=2).font = Font(bold=True)
ws.cell(row=total_row, column=2).alignment = Alignment(horizontal="center", vertical="center")
ws.cell(row=total_row, column=3).value = None
except Exception:
pass
widths = {
1: 6,
2: 34,
3: 34,
4: 26,
5: 16,
6: 10,
7: 12,
}
for col_idx in range(1, ws.max_column + 1):
col_letter = get_column_letter(col_idx)
ws.column_dimensions[col_letter].width = widths.get(col_idx, 15)
for row in range(header_row + 1, ws.max_row + 1):
cell = ws.cell(row=row, column=7)
if to_number(cell.value) is not None:
cell.number_format = "0.000######"
ws.freeze_panes = "A7"
else:
header_row = 1
ws.sheet_view.showGridLines = False
for row in range(1, ws.max_row + 1):
for col in range(1, ws.max_column + 1):
cell = ws.cell(row=row, column=col)
cell.border = thin_border
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
if row == header_row:
cell.font = header_font
for col_idx in range(1, ws.max_column + 1):
col_letter = get_column_letter(col_idx)
header = safe_str(ws.cell(row=header_row, column=col_idx).value)
if header in ["๊ฒ์ ์๋ฌธ", "Evidence", "Evidence Text"]:
ws.column_dimensions[col_letter].width = 70
elif header in ["Result", "๋น๊ณ "]:
ws.column_dimensions[col_letter].width = 45
elif header in ["INCI Name"]:
ws.column_dimensions[col_letter].width = 32
else:
ws.column_dimensions[col_letter].width = 18
ws.freeze_panes = "A2"
wb.save(path)
# ============================================================
# 11. ๋ฉ์ธ ์ฒ๋ฆฌ
# ============================================================
def build_integrated_result(row_data, country_cols):
issue_items = []
for country_col in country_cols:
value = safe_str(row_data.get(country_col, ""))
if is_country_result_issue(value):
issue_items.append(country_col)
if not issue_items:
return "PASS"
return "์ฌ๊ฒํ ํ์: " + ", ".join(issue_items)
def process(countries, file, product_name="", use_mfds_live=False, mfds_max_terms=30, mfds_headless=True):
global RAW_SEARCH_LOGS
RAW_SEARCH_LOGS = []
try:
if not file:
return None, None, "โ ์์
ํ์ผ์ ์
๋ก๋ํด์ฃผ์ธ์."
if not countries:
return None, None, "โ ์คํฌ๋ฆฌ๋ ๊ตญ๊ฐ๋ฅผ ์ ํํด์ฃผ์ธ์."
df = pd.read_excel(file.name)
grouped_materials, meta = make_grouped_materials(df)
if not grouped_materials:
return None, None, "โ ์์
์์ ์ ์ฑ๋ถ ์ ๋ณด๋ฅผ ์ฝ์ง ๋ชปํ์ต๋๋ค. ์ปฌ๋ผ๋ช
์ ํ์ธํด์ฃผ์ธ์."
ingredient_totals = meta["ingredient_totals"]
ingredient_amount_parts = meta["ingredient_amount_parts"]
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
row_items = []
for material in grouped_materials:
comp = material["Components"][0]
target_id = f"row_{len(row_items)}"
row_data = {
"NO": material.get("NO", ""),
"Trade name(๊ตญ๋ฌธ)": material.get("Trade name(๊ตญ๋ฌธ)", ""),
"Trade name(์๋ฌธ)": material.get("Trade name(์๋ฌธ)", ""),
"ํ๊ธ ์ฑ๋ถ๋ช
": comp.get("ํ๊ธ ์ฑ๋ถ๋ช
", ""),
"INCI Name": comp.get("INCI Name", ""),
"In formula\n(w/w %)": comp.get("In formula(w/w %)", ""),
"Result": "",
}
row_items.append({
"target_id": target_id,
"material": material,
"component": comp,
"row_data": row_data,
"notes": [],
})
mfds_df = pd.DataFrame()
mfds_live_msg = "์ฌ์ฉ ์ ํจ"
if use_mfds_live:
try:
terms = extract_terms_for_mfds_live(row_items)
mfds_df, mfds_live_msg = mfds_live_lookup_terms(
terms=terms,
max_terms=mfds_max_terms,
headless=mfds_headless,
)
except Exception as e:
mfds_df = pd.DataFrame()
mfds_live_msg = f"MFDS ์ค์๊ฐ ์กฐํ ์คํจ: {e}"
for country in countries:
col_name = display_country(country)
gpt_targets = []
for item in row_items:
local_result = evaluate_local_rules(
country=country,
material=item["material"],
component=item["component"],
ingredient_totals=ingredient_totals,
ingredient_amount_parts=ingredient_amount_parts,
)
if local_result is not None:
item["row_data"][col_name] = local_result.get("๊ฒฐ๊ณผ", "")
item["row_data"][col_name + "_display"] = local_result.get("ํ์๋ฌธ๊ตฌ", "Pass")
note = safe_str(local_result.get("๋น๊ณ ", "-"))
if note and note != "-":
item["notes"].append(f"{col_name}: {note}")
log_search_context(
item["target_id"],
country,
item["component"],
local_result.get("๊ฒฐ๊ณผ", ""),
"LOCAL_RULE",
note if note and note != "-" else "๋ก์ปฌ ๊ณ ์ ๊ท์น ์ฐ์ ํ์ ",
)
continue
mfds_result = None
if use_mfds_live and mfds_df is not None and not mfds_df.empty:
mfds_result = evaluate_mfds_detail_rule(
country=country,
material=item["material"],
component=item["component"],
mfds_df=mfds_df,
)
if mfds_result is not None:
item["row_data"][col_name] = mfds_result.get("๊ฒฐ๊ณผ", "")
item["row_data"][col_name + "_display"] = mfds_result.get("ํ์๋ฌธ๊ตฌ", "ํ์ธ ํ์")
note = safe_str(mfds_result.get("๋น๊ณ ", "-"))
if note and note != "-":
item["notes"].append(f"{col_name}: {note}")
log_search_context(
item["target_id"],
country,
item["component"],
mfds_result.get("๊ฒฐ๊ณผ", ""),
"MFDS_LIVE",
note,
)
continue
gpt_targets.append({
"target_id": item["target_id"],
"material": item["material"],
"component": item["component"],
})
batch_results = evaluate_components_with_llm_batch(
country=country,
targets=gpt_targets,
llm=llm,
)
for item in row_items:
if col_name in item["row_data"]:
continue
result = batch_results.get(item["target_id"])
if result is None:
result = {
"๋ํ INCI": safe_str(item["component"].get("INCI Name", "")) or "-",
"๊ฒฐ๊ณผ": "ํ์ธ ํ์",
"ํ์๋ฌธ๊ตฌ": "ํ์ธ ํ์",
"๋น๊ณ ": "batch ๊ฒฐ๊ณผ ๋๋ฝ",
}
item["row_data"][col_name] = result.get("๊ฒฐ๊ณผ", "")
item["row_data"][col_name + "_display"] = result.get("ํ์๋ฌธ๊ตฌ", "Pass")
note = safe_str(result.get("๋น๊ณ ", "-"))
if note and note != "-":
item["notes"].append(f"{col_name}: {note}")
country_cols = [display_country(c) for c in countries]
for item in row_items:
item["row_data"]["Result"] = build_integrated_result(item["row_data"], country_cols)
item["row_data"]["๋น๊ณ "] = " / ".join(item["notes"]) if item["notes"] else "-"
formula_df = make_formula_statement_rows(row_items, country_cols)
regulatory_df = make_regulatory_summary_rows(row_items, country_cols)
raw_columns = ["target_id", "๊ตญ๊ฐ/์ฑ๋", "์ฑ๋ถ๋ช
", "INCI Name", "ํ์ ", "์ถ์ฒ", "๊ฒ์ ์๋ฌธ"]
raw_df = pd.DataFrame(RAW_SEARCH_LOGS)
if raw_df.empty:
raw_df = pd.DataFrame(columns=raw_columns)
else:
for col in raw_columns:
if col not in raw_df.columns:
raw_df[col] = ""
raw_df = raw_df[raw_columns]
formula_total = sum_formula_percent(formula_df)
safe_country_name = "_".join([
re.sub(r"[^a-zA-Z0-9๊ฐ-ํฃ_-]", "_", str(c))
for c in countries
])
product_part = safe_filename(product_name) if safe_str(product_name) else "product"
out_path = str(OUTPUT_DIR / f"screening_result_{product_part}_{safe_country_name}.xlsx")
write_output_workbook(
out_path=out_path,
product_name=product_name,
formula_df=formula_df,
regulatory_df=regulatory_df,
raw_df=raw_df,
)
msg = (
"โ
๋ถ์ ์๋ฃ\n"
f"- Product Name: {safe_str(product_name) or '-'}\n"
f"- ์ ์ฑ๋ถ ํ ์: {len(formula_df)}๊ฐ\n"
f"- In formula ํฉ๊ณ: {format_amount(formula_total)}%\n"
f"- ์ฌ๊ฒํ ํ์ ์ฑ๋ถ: {len(regulatory_df)}๊ฐ\n"
f"- MFDS ์ํ: {mfds_live_msg}\n"
"- ๊ฒฐ๊ณผ ํ์ผ ์ํธ:\n"
" 1) Formula Ingredients Statement\n"
" 2) Regulatory Screening Summary\n"
" 3) Evidence Log\n"
)
return formula_df, out_path, msg
except Exception as e:
tb = traceback.format_exc()
print(tb)
return None, None, f"โ ์ค๋ฅ ๋ฐ์: {str(e)}\n\n{tb[-3000:]}"
# ============================================================
# 12. Gradio UI
# ============================================================
with gr.Blocks(css=custom_css) as demo:
gr.Markdown("# ๐ reBom Regulatory Screening AI")
gr.Markdown("### ๊ตญ๊ฐ๋ณ ๊ท์ ํด๋ ๊ฒ์ + ์์ฝ์ฒ ์ค์๊ฐ ์กฐํ + Formular Ingredients Statement ์ถ๋ ฅ")
with gr.Row():
gr.Button(
"๐ช ๋ก๊ทธ์์",
link="/logout?all_session=false",
variant="secondary",
)
with gr.Tab("๐ ์คํฌ๋ฆฌ๋"):
country = gr.CheckboxGroup(
choices=get_country_folders(),
value=[],
label="๐ ๊ตญ๊ฐ / ์ฑ๋ ์ ํ",
elem_id="country_checks",
)
refresh = gr.Button("๐ ํด๋/๊ท์ ํ์ผ ์๋ก๊ณ ์นจ")
product_name = gr.Textbox(
label="์ ํ๋ช
/ PRODUCT NAME",
placeholder="์: ๋ง๋ฐ์นดํฌ๋ฆผ",
)
file = gr.File(
label="์ ์ฑ๋ถ ์์
์
๋ก๋",
file_types=[".xlsx"],
)
use_mfds_live = gr.Checkbox(
label="์์ฝ์ฒ ์ฌ์ดํธ ์ค์๊ฐ ์กฐํ ์ฌ์ฉ",
value=False,
)
mfds_max_terms = gr.Number(
label="์์ฝ์ฒ ์ค์๊ฐ ์กฐํ ์ต๋ ๊ฒ์์ด ์",
value=5,
precision=0,
)
mfds_headless = gr.Checkbox(
label="์์ฝ์ฒ ์กฐํ ๋ธ๋ผ์ฐ์ ์จ๊น ๋ชจ๋",
value=True,
)
btn = gr.Button("๐ ๋ถ์ ์์", variant="primary")
df_out = gr.Dataframe(
label="๋ฏธ๋ฆฌ๋ณด๊ธฐ - Formular Ingredients Statement",
wrap=True,
interactive=False,
)
file_out = gr.File(label="๊ฒฐ๊ณผ ๋ค์ด๋ก๋")
msg_out = gr.Textbox(
label="์ํ / ์ค๋ฅ ๋ฉ์์ง",
interactive=False,
lines=12,
)
refresh.click(
fn=refresh_country_choices_and_clear_cache,
inputs=country,
outputs=country,
)
try:
auto_refresh_timer = gr.Timer(15)
auto_refresh_timer.tick(
fn=refresh_country_choices_keep_selection,
inputs=country,
outputs=country,
)
except Exception as e:
print(f"์๋ ๊ตญ๊ฐ ๋ชฉ๋ก ๊ฐฑ์ ํ์ด๋จธ ๋นํ์ฑํ: {e}")
file.change(
fn=preview_excel,
inputs=file,
outputs=df_out,
)
btn.click(
process,
inputs=[
country,
file,
product_name,
use_mfds_live,
mfds_max_terms,
mfds_headless,
],
outputs=[
df_out,
file_out,
msg_out,
],
)
# ============================================================
# 13. ๋ก๊ทธ์ธ ์ธ์ฆ
# ============================================================
USER_DB = {
"jin2li@rebom.kr": "qwer0515!",
"jkh@rebom.kr": "rebom123!",
"member2": "1111",
}
def auth_fn(username, password):
username = str(username).strip()
password = str(password).strip()
return username in USER_DB and USER_DB[username] == password
# ============================================================
# 14. ์ฑ ์คํ
# ============================================================
try:
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
ssr_mode=False,
auth=auth_fn,
allowed_paths=ALLOWED_PATHS,
blocked_paths=BLOCKED_PATHS,
show_api=False,
footer_links=[],
app_kwargs={
"docs_url": None,
"redoc_url": None,
"openapi_url": None,
},
)
except TypeError:
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
auth=auth_fn,
allowed_paths=ALLOWED_PATHS,
blocked_paths=BLOCKED_PATHS,
)
# ============================================================
# reBom Regulatory Screening AI - Fast Grounded Fixed Version
# - ๊ตญ๊ฐ/์ฑ๋ ํด๋ ์๋ ์ธ์
# - ๊ท์ ํ์ผ ์๋ ๋ณ๊ฒฝ ๊ฐ์ง
# - ๊ตญ๊ฐ๋ณ FAISS ๋ฒกํฐ DB ๋์คํฌ ์บ์
# - ๊ตญ๊ฐ๋ณ ๋ฌธ์ ๊ฒฉ๋ฆฌ ๊ฒ์์ผ๋ก ํ๊ตญ ๊ท์ ํ์ฐ ๋ฐฉ์ง
# - ๋ก์ปฌ ๊ท์น ์ฐ์ ํ์
# - MFDS ์์ฝํ์์ ๋๋ผ ์์ธ DB ์์
์ฐ๋
# - GPT ํธ์ถ ์ ์๋ฏธ ์๋ ๊ฒ์๊ฒฐ๊ณผ ํํฐ๋ง
# - Formula Ingredients Statement ์๋ณธ ์์ ์ถ๋ ฅ
# - ๋ฌธ์ ์ฑ๋ถ๋ง Regulatory Screening Summary ์ถ๋ ฅ
# - Raw Search Log ๋ณ๋ ์ ์ฅ
# - Gradio ๋ก๊ทธ์ธ ์ธ์ฆ / public share link ์ ์ฉ
# - MergedCell column_letter ์ค๋ฅ ์์ ์๋ฃ
# ============================================================
# ============================================================
# reBom Regulatory Screening AI
# - ๊ตญ๊ฐ๋ณ ๊ท์ ํด๋ ์์์๋ง ๊ฒ์
# - FAISS ๋์คํฌ ์บ์
# - GPT๋ ๊ฒ์๋ ์๋ฌธ ์์์๋ง ํ์
# - ์์ฝ์ฒ ์ฌ์ดํธ ์ค์๊ฐ ์กฐํ ์ต์
# - Formular Ingredients Statement ์๋ณธ ์์ ์ถ๋ ฅ
# - ์๋ณธ TOTAL ํ ์ ๊ฑฐ ํ ์ TOTAL ํ 1๊ฐ๋ง ์์ฑ
# ============================================================
import os
import re
import json
import hashlib
import traceback
from pathlib import Path
from collections import defaultdict
import pandas as pd
import pdfplumber
import gradio as gr
try:
from bs4 import BeautifulSoup
except Exception:
BeautifulSoup = None
try:
from playwright.sync_api import sync_playwright
PLAYWRIGHT_AVAILABLE = True
except Exception:
sync_playwright = None
PLAYWRIGHT_AVAILABLE = False
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
# ============================================================
# 0. ๊ธฐ๋ณธ ์ค์
# ============================================================
api_key = os.getenv("OPENAI_API_KEY")
print("โ
OPENAI_API_KEY ์ ์" if api_key else "โ OPENAI_API_KEY ์์")
BASE_DIR = Path.cwd().resolve()
OUTPUT_DIR = (BASE_DIR / "outputs").resolve()
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
FAISS_CACHE_DIR = ".faiss_cache"
MFDS_LIVE_URL = "https://nedrug.mfds.go.kr/pbp/CCBDF01"
NO_EVIDENCE_TEXT = "ํด๋น ์๋ฃ ๋ด ์ ํ ๊ทผ๊ฑฐ ์์"
VECTOR_DB_CACHE = {}
EVAL_CACHE = {}
EMBEDDINGS_CACHE = None
RAW_SEARCH_LOGS = []
SUPPORTED_REG_FILE_EXTENSIONS = {".pdf", ".txt", ".csv", ".xlsx", ".xls"}
COUNTRY_ORDER = [
"ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "FDA",
"JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA",
]
COUNTRY_DISPLAY = {
"EU": "EU", "์ ๋ฝ": "EU", "EUROPE": "EU",
"FDA": "FDA", "๋ฏธ๊ตญ": "FDA", "USA": "FDA", "US": "FDA",
"KOREA": "Korea", "ํ๊ตญ": "Korea", "KR": "Korea",
"JAPAN": "์ผ๋ณธ", "์ผ๋ณธ": "์ผ๋ณธ", "JP": "์ผ๋ณธ",
"CHINA": "์ค๊ตญ", "์ค๊ตญ": "์ค๊ตญ", "CN": "์ค๊ตญ",
"ASEAN": "ASEAN", "์์ธ์": "ASEAN",
"UK": "UK", "์๊ตญ": "UK",
"EU (FUTURE)": "EU (FUTURE)", "EU_FUTURE": "EU (FUTURE)",
"CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO",
"SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA",
}
COUNTRY_FOLDER_ALIASES = {