jin2li commited on
Commit
ffca6e3
·
verified ·
1 Parent(s): d2edd2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -880
app.py CHANGED
@@ -35,7 +35,7 @@
35
  # reBom Regulatory Screening AI - compact full app.py
36
  # Excel/PDF/Image input + country folder RAG + local rules + single ingredient search
37
 
38
- import os, re, json, base64, hashlib, traceback, sqlite3, secrets, datetime, time, sys, subprocess, time
39
  from pathlib import Path
40
  from collections import defaultdict
41
  from functools import lru_cache
@@ -93,10 +93,10 @@ RAW_SEARCH_LOGS = []
93
  REG_TEXT_CACHE = {}
94
  REG_SECTION_INDEX_CACHE = {}
95
 
96
- COUNTRY_ORDER = ["ASEAN","CALIFORNIA","CHINA","EU (FUTURE)","EU","US","JAPAN","KOREA","MEXICO","SEPHORA","TARGET","UK","ULTA"]
97
  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"}
98
  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"}
99
- 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__')]
100
  ALLOWED_PATHS = [str(OUTPUT_DIR), str(BASE_DIR)]
101
  SUPPORTED_INPUT_EXTENSIONS = {".xlsx",".xls",".pdf",".png",".jpg",".jpeg",".webp"}
102
  SUPPORTED_REG_FILE_EXTENSIONS = {".pdf",".txt",".csv",".xlsx",".xls"}
@@ -164,12 +164,7 @@ def safe_filename(text): return re.sub(r"[^a-zA-Z0-9가-힣._() -]","_",safe_str
164
  def chunk_list(items,size):
165
  for i in range(0,len(items),size): yield items[i:i+size]
166
 
167
- def country_key(country):
168
- t=safe_str(country).upper().replace("_"," ").replace("-"," "); t=re.sub(r"\s+"," ",t).strip()
169
- 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"}
170
- return m.get(t,t)
171
 
172
- def display_country(country): return COUNTRY_DISPLAY.get(str(country).upper(),COUNTRY_DISPLAY.get(str(country),str(country)))
173
  def get_embeddings():
174
  global EMBEDDINGS_CACHE
175
  if EMBEDDINGS_CACHE is None: EMBEDDINGS_CACHE=OpenAIEmbeddings(model="text-embedding-3-small")
@@ -257,9 +252,6 @@ def is_plain_fragrance_component(material,component):
257
  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(영문)","")]))
258
  return any(normalize_compact(w) in identity for w in ["향료","fragrance","parfum","perfume","aroma"])
259
 
260
- def evaluate_plain_fragrance_rule(country,material,component):
261
- if not is_plain_fragrance_component(material,component): return None
262
- return {"대표 INCI":safe_str(component.get("INCI Name","")) or "Fragrance","결과":f"향료 / {display_country(country)} 알레르겐 표시성분 및 세부 조성 확인 필요","표시문구":NEED_CHECK_TEXT,"비고":"향료는 세부 구성성분 및 알레르겐 표시대상 여부 확인 필요. 자동 Pass 처리 금지."}
263
 
264
  def get_restricted_candidate_reason(material,component):
265
  if is_always_pass_component(material,component): return ""
@@ -276,10 +268,6 @@ def get_restricted_candidate_reason(material,component):
276
  if normalize_compact(component.get("한글 성분명",""))==normalize_compact("살리실릭애씨드"): return "제한 가능성 성분"
277
  return ""
278
 
279
- def is_country_result_issue(text):
280
- text=safe_str(text)
281
- if not text or text in ["-",NO_EVIDENCE_TEXT,"Pass","PASS","pass"]: return False
282
- return any(k in text for k in ["배합금지","금지","초과","부적합","재검토","확인 필요","자료 확인","표시 필요","라벨링","불가","주의","경고","배합한도 확인 필요","기능성 확인","함량 확인"])
283
 
284
  def log_search_context(target_id,country,component,result_text,source,context):
285
  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]})
@@ -318,32 +306,6 @@ def validate_limit_result_against_evidence(result_obj,evidence_text,component):
318
  result_obj["비고"]=(note+" / "+ev) if note and note!="-" else ev
319
  return result_obj
320
 
321
- def normalize_formula_country_text(text,country_col="",inci_name="",amount_text=""):
322
- text=safe_str(text); lower=text.lower(); inci_norm=normalize_compact(inci_name)
323
- if not text or text=="-" or text==NO_EVIDENCE_TEXT: return "Pass"
324
- if any(k in text for k in ["배합금지","사용금지","금지"]) or any(k in lower for k in ["prohibited","banned","not allowed"]): return "배합금지"
325
- if LIMIT_CHECK_TEXT in text: return LIMIT_CHECK_TEXT
326
- if NEED_CHECK_TEXT in text: return NEED_CHECK_TEXT
327
- if "향료" in text or "fragrance" in lower or "parfum" in lower: return NEED_CHECK_TEXT
328
- if "기능성" in text: return "기능성 확인"
329
- if "함량 정보 없음" in text or "함량 확인" in text: return "함량 확인"
330
- if "octocrylene" in inci_norm or "옥토크릴렌" in inci_norm:
331
- if country_col=="EU": return "배합 한도:\n스프레이: 9% /\n기타제품: 10%"
332
- if country_col=="FDA": return "라벨링 필수"
333
- if country_col in ["Korea","일본"]: return "배합한도: 10%"
334
- if "homosalate" in inci_norm or "호모살레이트" in inci_norm:
335
- if country_col=="ASEAN": return "배합한도: 10%"
336
- if country_col=="EU": return "배합한도: 7.34%"
337
- if country_col=="FDA": return "배합한도: 15%"
338
- if country_col in ["Korea","일본"]: return "배합한도: 10%"
339
- if "octisalate" in inci_norm or "ethylhexylsalicylate" in inci_norm or "옥티살레이트" in inci_norm: return "배합한도: 5%"
340
- if "avobenzone" in inci_norm or "아보벤존" in inci_norm: return "배합한도: 3%" if country_col=="FDA" else "배합한도: 5%"
341
- if any(k in text for k in ["초과","부적합","사용 불가","사용불가"]): return "한도 초과"
342
- if "표시 필요" in text or "라벨" in text or "label" in lower: return "라벨링 필수"
343
- m=re.search(r"(?:배합\s*한도|배합한도|한도|max|maximum|limit|최대|이하|이내)\s*[::]?\s*([0-9]+(?:\.[0-9]+)?\s*%)",text,flags=re.I)
344
- if m: return "배합한도: "+m.group(1).replace(" ","")
345
- if any(k in text for k in ["배합한도","배합 한도","한도","제한"]) or any(k in lower for k in ["maximum","limit","restricted"]): return LIMIT_CHECK_TEXT
346
- return text[:120]
347
 
348
 
349
  def standardize_formula_dataframe(df):
@@ -594,8 +556,6 @@ def is_broad_lookup_term(term):
594
  return False
595
 
596
 
597
-
598
-
599
  # ============================================================
600
  # 규제 동의어 / CAS / 이성질체 레지스트리
601
  # - 국가별 파일 표기가 INCI와 다를 때 PASS 오판을 막기 위한 보정층
@@ -1184,8 +1144,6 @@ def validate_country_file_match_context(context, component, lookup_terms):
1184
  return False
1185
 
1186
 
1187
-
1188
-
1189
  # country db
1190
 
1191
  def resolve_country_folder(country):
@@ -1195,18 +1153,16 @@ def resolve_country_folder(country):
1195
  fmap={f.lower():f for f in os.listdir(".") if os.path.isdir(f)}
1196
  return fmap.get(alias.lower(),alias)
1197
 
1198
- def get_country_folders():
1199
  exclude={".git",".cache","__pycache__",".ipynb_checkpoints",".venv","venv","node_modules",FAISS_CACHE_DIR,"outputs"}
1200
  folders=[f for f in os.listdir(".") if os.path.isdir(f) and f not in exclude]
1201
  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])
1202
  return ordered+extras if ordered or extras else COUNTRY_ORDER.copy()
1203
 
1204
- def refresh_country_choices_keep_selection(current_values=None):
1205
  choices=get_country_folders(); kept=[v for v in (current_values or []) if v in choices]
1206
  return gr.update(choices=choices,value=kept)
1207
 
1208
- def refresh_country_choices_and_clear_cache(current_values=None):
1209
- VECTOR_DB_CACHE.clear(); EVAL_CACHE.clear(); REG_TEXT_CACHE.clear(); REG_SECTION_INDEX_CACHE.clear(); return refresh_country_choices_keep_selection(current_values)
1210
 
1211
  def get_regulatory_file_list(folder):
1212
  files=[]
@@ -1505,8 +1461,6 @@ def mfds_click_probable_result(page, term):
1505
  return False
1506
 
1507
 
1508
-
1509
-
1510
  def mfds_click_first_detail_result(page):
1511
  """
1512
  식약처 검색 결과에서 검색어와 결과명칭이 다를 수 있다.
@@ -1795,8 +1749,6 @@ def mfds_lookup_one_term_with_retry(page, term):
1795
  return [], last_error[:300]
1796
 
1797
 
1798
-
1799
-
1800
  def mfds_launch_chromium(playwright_obj):
1801
  """
1802
  Playwright Chromium 브라우저 실행 함수.
@@ -1991,15 +1943,6 @@ def evaluate_live_detail_rule(country, material, component, live_df):
1991
  }
1992
 
1993
 
1994
- def evaluate_critical_country_rule(country,material,component):
1995
- ckey=country_key(country); identity=get_identity_raw(material,component)
1996
- for r in CRITICAL_COUNTRY_RULES.values():
1997
- if any_exact_alias_match(r.get("aliases",[]), identity):
1998
- cr=r.get(ckey)
1999
- if not cr: return None
2000
- if cr.get("status")=="prohibited": return {"대표 INCI":r.get("label","-"),"결과":cr.get("result","배합금지"),"표시문구":cr.get("formula_text","배합금지"),"비고":cr.get("note","-")}
2001
- if cr.get("status")=="restricted": return {"대표 INCI":r.get("label","-"),"결과":cr.get("result","제한 성분"),"표시문구":cr.get("formula_text",LIMIT_CHECK_TEXT),"비고":cr.get("note","-")}
2002
- return None
2003
 
2004
  def evaluate_limit_rule(country,material,component,group,name):
2005
  key=match_rule_key(material,component,group)
@@ -2013,24 +1956,6 @@ def evaluate_limit_rule(country,material,component,group,name):
2013
  return {"대표 INCI":label,"결과":f"{name} / {label} 현재 함량 {at}%, 한도 {format_percent(lim)}% 이내","표시문구":cr.get("formula_text") or f"배합한도: {format_percent(lim)}%","비고":"-"}
2014
  return {"대표 INCI":label,"결과":f"{name} / {label} / 한도값 확인 필요","표시문구":LIMIT_CHECK_TEXT,"비고":"로컬 규칙에 성분은 있으나 한도값이 비어 있음."}
2015
 
2016
- def evaluate_local_rules(country,material,component,ingredient_totals,ingredient_amount_parts):
2017
- crit=evaluate_critical_country_rule(country,material,component)
2018
- if crit: return crit
2019
- if is_always_pass_component(material,component): return {"대표 INCI":safe_str(component.get("INCI Name","")) or "Water","결과":NO_EVIDENCE_TEXT,"표시문구":"Pass","비고":"정제수/Water/Aqua 기본 Pass 처리"}
2020
- fr=evaluate_plain_fragrance_rule(country,material,component)
2021
- if fr: return fr
2022
- for group,name in [(UV_FILTER_RULES,"UV 필터"),(PRESERVATIVE_RULES,"보존제/제한성분")]:
2023
- res=evaluate_limit_rule(country,material,component,group,name)
2024
- if res: return res
2025
- fkey=match_rule_key(material,component,FUNCTIONAL_KOREA_RULES)
2026
- if country_key(country)=="KOREA" and fkey:
2027
- r=FUNCTIONAL_KOREA_RULES[fkey]; amount=format_percent(component.get("amount_float")) if component.get("amount_float") is not None else "함량 확인 필요"
2028
- return {"대표 INCI":r["label"],"결과":r["result"].format(amount=amount),"표시문구":r.get("formula_text","기능성 확인"),"비고":"기능성 표시·광고 여부 확인"}
2029
- identity=get_identity_raw(material,component)
2030
- for r in FRAGRANCE_ALLERGEN_RULES.values():
2031
- if any_exact_alias_match(r.get("aliases",[]), identity): return {"대표 INCI":r["label"],"결과":f"향료 알레르겐 / {r['label']} / {display_country(country)} 표시기준 확인 필요","표시문구":NEED_CHECK_TEXT,"비고":"향료 알레르겐 후보. 세부 표시기준 및 제품 유형 확인 필요."}
2032
- if component.get("amount_float") is None: return {"대표 INCI":safe_str(component.get("INCI Name","")) or "-","결과":"함량 정보 없음 / In formula(w/w %) 확인 필요","표시문구":"함량 확인","비고":"-"}
2033
- return None
2034
 
2035
  def parse_country_response(text):
2036
  res={"대표 INCI":"-","결과":NO_EVIDENCE_TEXT,"표시문구":"Pass","비고":"-"}
@@ -2089,16 +2014,6 @@ def make_formula_statement_rows(row_items,country_cols):
2089
  for cc in country_cols: total_row[cc]=""
2090
  rows.append(total_row); return pd.DataFrame(rows)
2091
 
2092
- def make_regulatory_summary_rows(row_items,country_cols):
2093
- rows=[]
2094
- for item in row_items:
2095
- rd=item["row_data"]
2096
- if not is_country_result_issue(rd.get("Result","")): continue
2097
- row={"한글 성분명":rd.get("한글 성분명",""),"INCI Name":rd.get("INCI Name",""),"In formula(w/w %)":rd.get("In formula\n(w/w %)",""),"Result":rd.get("Result","")}
2098
- for cc in country_cols: row[cc]=rd.get(cc,"") if is_country_result_issue(rd.get(cc,"")) else "-"
2099
- row["비고"]=rd.get("비고","-"); rows.append(row)
2100
- cols=["한글 성분명","INCI Name","In formula(w/w %)","Result"]+country_cols+["비고"]
2101
- return pd.DataFrame(rows,columns=cols)
2102
 
2103
  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)","")))
2104
 
@@ -2121,9 +2036,6 @@ def style_output_workbook(path,product_name=""):
2121
  for col in range(1,sheet.max_column+1): sheet.column_dimensions[get_column_letter(col)].width=18
2122
  wb.save(path)
2123
 
2124
- def build_integrated_result(rd,country_cols):
2125
- issues=[cc for cc in country_cols if is_country_result_issue(rd.get(cc,""))]
2126
- return "PASS" if not issues else "재검토 필요: "+", ".join(issues)
2127
 
2128
  def process(countries,file,product_name="",use_mfds_live=False,live_max_terms=5,live_headless=True):
2129
  """
@@ -2399,9 +2311,6 @@ def build_single_component_from_query(query, amount="", function="", single_amou
2399
  return mat, comp, at
2400
 
2401
 
2402
-
2403
-
2404
-
2405
  def get_country_regulatory_text_cached(country):
2406
  """
2407
  국가별 규제 파일 원문을 직접 읽어서 캐시한다.
@@ -2635,7 +2544,7 @@ def split_regulatory_text_into_sections(raw_text):
2635
  return sections
2636
 
2637
 
2638
- def get_country_section_index_cached(country):
2639
  """
2640
  단일 성분 검색 고속화용 섹션 인덱스.
2641
  국가별 파일을 매번 PDF/Excel 전체 읽기하지 않고,
@@ -2900,44 +2809,6 @@ def warmup_country_indexes(countries):
2900
  return "\n".join(messages) if messages else "선택된 국가 없음"
2901
 
2902
 
2903
-
2904
-
2905
- def extract_limit_condition_from_context(context):
2906
- text = safe_str(context)
2907
- compact = re.sub(r"\s+", " ", text).strip()
2908
- if not compact:
2909
- return "", ""
2910
-
2911
- patterns = [
2912
- r"([0-9]+(?:\.[0-9]+)?\s*%)",
2913
- r"([0-9]+(?:\.[0-9]+)?\s*ppm)",
2914
- r"([0-9]+(?:\.[0-9]+)?\s*g\s*/\s*100\s*g)",
2915
- r"([0-9]+(?:\.[0-9]+)?\s*g\s+per\s+100\s*g)",
2916
- r"([0-9]+(?:\.[0-9]+)?\s*mg\s*/\s*kg)",
2917
- ]
2918
- limits = []
2919
- for pat in patterns:
2920
- for m in re.finditer(pat, compact, flags=re.IGNORECASE):
2921
- v = m.group(1).replace(" ", "")
2922
- if v not in limits:
2923
- limits.append(v)
2924
-
2925
- condition_keywords = [
2926
- "leave-on", "rinse-off", "oral", "mucosa", "washed away",
2927
- "보존제", "방부제", "자외선", "색소", "점막", "구강",
2928
- "제한사항", "경고", "warning", "condition", "한도", "제한",
2929
- ]
2930
- condition_lines = []
2931
- for line in [safe_str(x) for x in text.splitlines() if safe_str(x)]:
2932
- l = line.lower()
2933
- if any(k.lower() in l for k in condition_keywords):
2934
- cleaned = re.sub(r"\s+", " ", line).strip()
2935
- if cleaned not in condition_lines:
2936
- condition_lines.append(cleaned)
2937
-
2938
- return ", ".join(limits[:5]), " / ".join(condition_lines[:5])[:700]
2939
-
2940
-
2941
  def make_restricted_or_positive_result(country, component, match, reg_type):
2942
  context = safe_str(match.get("context", "")) if isinstance(match, dict) else safe_str(match)
2943
  label = safe_str(reg_type.get("label", "규제 목록"))
@@ -3150,177 +3021,6 @@ def build_country_source_record_index(country):
3150
  return records, "BUILT_SOURCE_RECORD_INDEX"
3151
 
3152
 
3153
- def pick_best_source_record(records):
3154
- priority = {
3155
- "prohibited": 100,
3156
- "restricted": 80,
3157
- "positive_uv": 50,
3158
- "positive_preservative": 50,
3159
- "positive_colorant": 50,
3160
- "unknown": 10,
3161
- }
3162
-
3163
- return sorted(
3164
- records,
3165
- key=lambda r: priority.get(r.get("regulation_type", {}).get("type", "unknown"), 0),
3166
- reverse=True,
3167
- )[0] if records else None
3168
-
3169
-
3170
- def evaluate_component_from_uploaded_source_records(country, material, component, target_id=""):
3171
- """
3172
- 국가 폴더 파일만 보고 판정.
3173
- 파일 record 안에 현재 성분명/국문/CAS가 직접 있을 때만 판정한다.
3174
- """
3175
- terms = source_match_terms_for_component(material, component)
3176
- term_norms = [normalize_compact(t) for t in terms if len(normalize_compact(t)) >= 3]
3177
-
3178
- representative = (
3179
- safe_str(component.get("INCI Name", ""))
3180
- or safe_str(component.get("한글 성분명", ""))
3181
- or safe_str(component.get("CAS.No", ""))
3182
- or "-"
3183
- )
3184
-
3185
- if not term_norms:
3186
- return None
3187
-
3188
- records, status = build_country_source_record_index(country)
3189
- hits = []
3190
-
3191
- for rec in records:
3192
- rec_norm = rec.get("text_norm", "")
3193
-
3194
- if any(tn in rec_norm for tn in term_norms):
3195
- hits.append(rec)
3196
-
3197
- if not hits:
3198
- return None
3199
-
3200
- best = pick_best_source_record(hits)
3201
- reg_type = best.get("regulation_type", {})
3202
- reg_kind = reg_type.get("type", "unknown")
3203
- reg_label = reg_type.get("label", "규제 유형 미분류")
3204
- context = best.get("text", "")
3205
- country_col = display_country(country)
3206
-
3207
- if reg_kind == "prohibited":
3208
- result = {
3209
- "대표 INCI": representative,
3210
- "결과": f"{country_col} {reg_label}에서 성분 직접 확인",
3211
- "표시문구": "배합금지",
3212
- "비고": f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}",
3213
- }
3214
- log_search_context(target_id, country, component, result["결과"], "UPLOADED_SOURCE_RECORD_PROHIBITED", result["비고"])
3215
- return result
3216
-
3217
- if reg_kind == "restricted":
3218
- limit_text, condition_text = extract_limit_condition_from_context(context)
3219
- result = {
3220
- "대표 INCI": representative,
3221
- "결과": f"{country_col} {reg_label}에서 성분 직접 확인" + (f" / 조건: {condition_text}" if condition_text else ""),
3222
- "표시문구": f"배합한도: {limit_text}" if limit_text else NEED_CHECK_TEXT,
3223
- "비고": f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}",
3224
- }
3225
- log_search_context(target_id, country, component, result["결과"], "UPLOADED_SOURCE_RECORD_RESTRICTED", result["비고"])
3226
- return result
3227
-
3228
- if reg_kind.startswith("positive_"):
3229
- limit_text, condition_text = extract_limit_condition_from_context(context)
3230
- result = {
3231
- "대표 INCI": representative,
3232
- "결과": f"{country_col} {reg_label}에서 성분 직접 확인" + (f" / 조건: {condition_text}" if condition_text else ""),
3233
- "표시문구": f"배합한도: {limit_text}" if limit_text else "허용목록 등재 / 한도 확인 필요",
3234
- "비고": f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}",
3235
- }
3236
- log_search_context(target_id, country, component, result["결과"], "UPLOADED_SOURCE_RECORD_POSITIVE", result["비고"])
3237
- return result
3238
-
3239
- # 파일에서는 성분을 찾았지만 파일 유형이 불명확한 경우:
3240
- # PASS로 단정하지 않고 확인 필요로 표시. 단, 이 경우도 "파일 직접 확인"은 남긴다.
3241
- result = {
3242
- "대표 INCI": representative,
3243
- "결과": f"{country_col} 국가별 파일에서 성분 직접 확인 / 파일 유형 미분류",
3244
- "표시문구": NEED_CHECK_TEXT,
3245
- "비고": f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}",
3246
- }
3247
- log_search_context(target_id, country, component, result["결과"], "UPLOADED_SOURCE_RECORD_UNKNOWN", result["비고"])
3248
- return result
3249
-
3250
-
3251
- def evaluate_component_from_country_files_only(country, material, component, target_id=""):
3252
- """
3253
- 국가별 업로드 파일 기반 판정.
3254
- 성분별 하드코딩 registry보다 업로드된 국가 파일 row/line record를 우선 사용한다.
3255
-
3256
- 원칙:
3257
- - 업로드 파일 record에 현재 성분명/국문/CAS가 직접 있으면 그 파일 유형에 따라 판정
3258
- - 금지/제한/Positive List 파일명 또는 row 문맥으로 유형 판단
3259
- - 파일에서 직접 근거가 없으면 Pass
3260
- - broad alias/glycol/extract 같은 넓은 검색어로 금지/제한 만들지 않음
3261
- """
3262
- country_col = display_country(country)
3263
-
3264
- inci_name = safe_str(component.get("INCI Name", ""))
3265
- korean_name = safe_str(component.get("한글 성분명", ""))
3266
- cas_no = safe_str(component.get("CAS.No", ""))
3267
- representative = inci_name or korean_name or cas_no or "-"
3268
-
3269
- critical_result = evaluate_critical_country_rule(
3270
- country=country,
3271
- material=material,
3272
- component=component,
3273
- )
3274
-
3275
- if critical_result is not None:
3276
- log_search_context(
3277
- target_id,
3278
- country,
3279
- component,
3280
- critical_result.get("결과", ""),
3281
- "CRITICAL_COUNTRY_RULE",
3282
- critical_result.get("비고", "-"),
3283
- )
3284
- return critical_result
3285
-
3286
- if is_always_pass_component(material, component):
3287
- result = {
3288
- "대표 INCI": representative if representative != "-" else "Water",
3289
- "결과": NO_EVIDENCE_TEXT,
3290
- "표시문구": "Pass",
3291
- "비고": "정제수/Water/Aqua 기본 Pass 처리",
3292
- }
3293
- log_search_context(target_id, country, component, result["결과"], "ALWAYS_PASS_RULE", result["비고"])
3294
- return result
3295
-
3296
- source_result = evaluate_component_from_uploaded_source_records(
3297
- country=country,
3298
- material=material,
3299
- component=component,
3300
- target_id=target_id,
3301
- )
3302
-
3303
- if source_result is not None:
3304
- return source_result
3305
-
3306
- result = {
3307
- "대표 INCI": representative,
3308
- "결과": NO_EVIDENCE_TEXT,
3309
- "표시문구": "Pass",
3310
- "비고": "업로드된 국가별 파일 내 현재 성분 직접 근거 없음",
3311
- }
3312
- log_search_context(
3313
- target_id,
3314
- country,
3315
- component,
3316
- result["결과"],
3317
- "UPLOADED_SOURCE_RECORD_NO_HIT",
3318
- result["비고"],
3319
- )
3320
- return result
3321
-
3322
-
3323
-
3324
  def shorten_for_table(value, max_len=80):
3325
  value = safe_str(value)
3326
 
@@ -3621,54 +3321,10 @@ DEFAULT_ADMIN_EMAIL = os.getenv("ADMIN_EMAIL", "jin2li@rebom.kr").strip().lower(
3621
  DEFAULT_ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "qwer0515!")
3622
 
3623
 
3624
- def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True):
3625
- if not is_approved_user(user):
3626
- return None, None, require_login_message()
3627
-
3628
- return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless)
3629
-
3630
-
3631
- def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False):
3632
- output_columns = ["국가", "검색어", "배합한도/금지", "상세 판정", "판정 출처", "비고"]
3633
-
3634
- if not is_approved_user(user):
3635
- return pd.DataFrame(columns=output_columns), require_login_message()
3636
-
3637
- return process_single_ingredient(
3638
- countries,
3639
- single_query,
3640
- single_amount,
3641
- single_function,
3642
- single_use_mfds_live,
3643
- )
3644
-
3645
-
3646
- def auth_fn(username, password):
3647
- username = str(username).strip().lower()
3648
- password = str(password).strip()
3649
-
3650
- return USER_DB.get(username) == password
3651
-
3652
-
3653
-
3654
  # ============================================================
3655
  # Gradio 기본 auth 사용 시 내부 로그인 체크 우회
3656
  # ============================================================
3657
 
3658
- def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True):
3659
- return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless)
3660
-
3661
-
3662
- def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False):
3663
- return process_single_ingredient(
3664
- countries,
3665
- single_query,
3666
- single_amount,
3667
- single_function,
3668
- single_use_mfds_live,
3669
- )
3670
-
3671
-
3672
 
3673
  # ============================================================
3674
  # 로그인 인증
@@ -3676,35 +3332,6 @@ def process_single_ingredient_with_auth(user, countries, single_query, single_am
3676
  # - USER_DB에 여러 아이디/비밀번호를 직접 등록
3677
  # ============================================================
3678
 
3679
- USER_DB = {
3680
- "jin2li@rebom.kr": "qwer0515!",
3681
-
3682
- # 사용자 추가 예시:
3683
- # "yubin.p@rebom.kr": "원하는비밀번호",
3684
- # "jkh@rebom.kr": "rebom123!",
3685
- }
3686
-
3687
-
3688
- def auth_fn(username, password):
3689
- username = str(username).strip().lower()
3690
- password = str(password).strip()
3691
- return USER_DB.get(username) == password
3692
-
3693
-
3694
- def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True):
3695
- return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless)
3696
-
3697
-
3698
- def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False):
3699
- return process_single_ingredient(
3700
- countries,
3701
- single_query,
3702
- single_amount,
3703
- single_function,
3704
- single_use_mfds_live,
3705
- )
3706
-
3707
-
3708
 
3709
  # ============================================================
3710
  # 로그인 인증
@@ -3716,34 +3343,28 @@ def process_single_ingredient_with_auth(user, countries, single_query, single_am
3716
  # "메일주소": "비밀번호",
3717
  # ============================================================
3718
 
3719
- USER_DB = {
3720
- "jin2li@rebom.kr": "qwer0515!",
3721
 
3722
- # 사용자 등록 예시:
3723
- # "yubin.p@rebom.kr": "123456!",
3724
- # "jkh@rebom.kr": "rebom123!",
3725
- }
3726
 
3727
 
3728
- def auth_fn(username, password):
3729
- username = str(username).strip().lower()
3730
- password = str(password).strip()
3731
- return USER_DB.get(username) == password
 
3732
 
3733
 
3734
- # Gradio 기본 auth를 통과한 사용자는 이미 인증된 상태이므로 내부 로그인 체크를 하지 않는다.
3735
- def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True):
3736
- return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless)
 
 
3737
 
3738
 
3739
- def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False):
3740
- return process_single_ingredient(
3741
- countries,
3742
- single_query,
3743
- single_amount,
3744
- single_function,
3745
- single_use_mfds_live,
3746
- )
3747
 
3748
 
3749
 
@@ -3752,13 +3373,18 @@ def process_single_ingredient_with_auth(user, countries, single_query, single_am
3752
  # - Gradio 기본 로그인창 사용
3753
  # - 아래 USER_DB에 메일/비밀번호를 직접 등록
3754
  # ============================================================
 
 
 
 
3755
 
3756
  USER_DB = {
3757
  "jin2li@rebom.kr": "qwer0515!",
 
 
3758
 
3759
  # 사용자 등록 예시:
3760
  # "yubin.p@rebom.kr": "123456!",
3761
- # "jkh@rebom.kr": "rebom123!",
3762
  }
3763
 
3764
 
@@ -3781,97 +3407,13 @@ def process_single_ingredient_with_auth(user, countries, single_query, single_am
3781
  single_use_mfds_live,
3782
  )
3783
 
 
 
 
 
3784
 
3785
-
3786
- # ============================================================
3787
- # 로그인 인증
3788
- # - Gradio 기본 로그인창 사용
3789
- # - 아래 USER_DB에 메일/비밀번호를 직접 등록
3790
- # ============================================================
3791
-
3792
- USER_DB = {
3793
- "jin2li@rebom.kr": "qwer0515!",
3794
-
3795
- # 사용자 등록 예시:
3796
- # "yubin.p@rebom.kr": "123456!",
3797
- # "jkh@rebom.kr": "rebom123!",
3798
- }
3799
-
3800
-
3801
- def auth_fn(username, password):
3802
- username = str(username).strip().lower()
3803
- password = str(password).strip()
3804
- return USER_DB.get(username) == password
3805
-
3806
-
3807
- def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True):
3808
- return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless)
3809
-
3810
-
3811
- def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False):
3812
- return process_single_ingredient(
3813
- countries,
3814
- single_query,
3815
- single_amount,
3816
- single_function,
3817
- single_use_mfds_live,
3818
- )
3819
-
3820
-
3821
-
3822
- # ============================================================
3823
- # 로그인 인증
3824
- # - Gradio 기본 로그인창 사용
3825
- # - 아래 USER_DB에 메일/비밀번호를 직접 등록
3826
-
3827
-
3828
-
3829
- # ============================================================
3830
- # 로그인 인증
3831
- # - Gradio 기본 로그인창 사용
3832
- # - 아래 USER_DB에 메일/비밀번호를 직접 등록
3833
- # ============================================================
3834
- # 사용자 추가 방법:
3835
- # USER_DB 안에 "아이디": "비밀번호", 형식으로 한 줄씩 추가하세요.
3836
- # 각 줄 끝에는 콤마(,)를 붙이는 것을 권장합니다.
3837
- # ============================================================
3838
-
3839
- USER_DB = {
3840
- "jin2li@rebom.kr": "qwer0515!",
3841
- "jkh@rebom.kr": "rebom123!",
3842
- "admin": "rebom123!",
3843
-
3844
- # 사용자 등록 예시:
3845
- # "yubin.p@rebom.kr": "123456!",
3846
- }
3847
-
3848
-
3849
- def auth_fn(username, password):
3850
- username = str(username).strip().lower()
3851
- password = str(password).strip()
3852
- return USER_DB.get(username) == password
3853
-
3854
-
3855
- def process_with_auth(user, countries, file, product_name="", use_mfds_live=False, live_max_terms=5, live_headless=True):
3856
- return process(countries, file, product_name, use_mfds_live, live_max_terms, live_headless)
3857
-
3858
-
3859
- def process_single_ingredient_with_auth(user, countries, single_query, single_amount, single_function, single_use_mfds_live=False):
3860
- return process_single_ingredient(
3861
- countries,
3862
- single_query,
3863
- single_amount,
3864
- single_function,
3865
- single_use_mfds_live,
3866
- )
3867
-
3868
- # ============================================================
3869
- # STRUCTURED FOLDER SCREENING PATCH V5.1
3870
- # 기존 UI/로그인/엑셀 출력 형태는 유지하고, 판정 엔진만 폴더 구조 기준으로 재정의
3871
- # ============================================================
3872
-
3873
- SOURCE_ONLY_MODE = True
3874
- TREAT_POSITIVE_LIST_AS_PASS = True
3875
 
3876
  V51_PROHIBITED_TERMS = [
3877
  "배합금지", "사용금지", "사용 금지", "금지원료", "금지 원료", "금지성분", "금지 성분",
@@ -4021,38 +3563,6 @@ def _v51_is_glycerin_deg_impurity_record(country, record, component):
4021
 
4022
  return has_glycerin and has_deg and has_impurity_limit
4023
 
4024
- def _v51_record_type(country, record, component=None):
4025
- if component is not None and _v51_is_glycerin_deg_impurity_record(country, record, component):
4026
- return "nonlegal_impurity"
4027
-
4028
- category = _v51_folder_category(country, record)
4029
- text = safe_str(record.get("text", ""))
4030
- path_text = _v51_path_text(record)
4031
- combined = path_text + "\n" + text[:1500]
4032
-
4033
- if category in ["nonlegal_prop65", "nonlegal_retailer", "nonlegal_impurity", "nonlegal_voluntary", "nonlegal_labeling", "reference"]:
4034
- return category
4035
- if category in ["legal_prohibited", "legal_restricted", "positive_list"]:
4036
- return category
4037
-
4038
- # mixed legal file 내부 문맥 보정
4039
- if category == "legal_mixed":
4040
- if _v51_text_has_any(combined, ["appendix 1", "annex ii", "prohibited", "금지", "사용할 수 없는 원료"]):
4041
- return "legal_prohibited"
4042
- if _v51_text_has_any(combined, ["appendix 2", "annex iii", "restricted", "제한", "배합한도", "maximum amount"]):
4043
- return "legal_restricted"
4044
- if _v51_text_has_any(combined, ["appendix 3", "appendix 4", "annex iv", "annex v", "annex vi", "preservative", "uv absorber", "uv filter", "tar colors", "색소", "보존제", "자외선"]):
4045
- return "positive_list"
4046
- return "reference"
4047
-
4048
- # 폴더명이 불명확한 경우 문맥만으로 매우 보수적으로 판단
4049
- if _v51_text_has_any(combined, V51_PROHIBITED_TERMS):
4050
- return "legal_prohibited"
4051
- if _v51_text_has_any(combined, V51_RESTRICTED_TERMS):
4052
- return "legal_restricted"
4053
- if _v51_text_has_any(combined, ["positive list", "permitted", "허용목록", "허용 목록", "coloring agents", "preservatives", "uv filters"]):
4054
- return "positive_list"
4055
- return "unknown"
4056
 
4057
 
4058
  def _v51_component_match_in_record(record_text, terms):
@@ -4144,24 +3654,6 @@ def normalize_formula_country_text(text, country_col="", inci_name="", amount_te
4144
  return "Pass"
4145
 
4146
 
4147
- def evaluate_critical_country_rule(country, material, component):
4148
- if SOURCE_ONLY_MODE:
4149
- return None
4150
- return None
4151
-
4152
-
4153
- def evaluate_plain_fragrance_rule(country, material, component):
4154
- if SOURCE_ONLY_MODE:
4155
- return None
4156
- return None
4157
-
4158
-
4159
- def evaluate_local_rules(country, material, component, ingredient_totals, ingredient_amount_parts):
4160
- if SOURCE_ONLY_MODE:
4161
- return None
4162
- return None
4163
-
4164
-
4165
  def _v51_nonlegal_result(kind, country, component, best, target_id=""):
4166
  country_col = display_country(country)
4167
  representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-"
@@ -4236,141 +3728,11 @@ def _v51_nonlegal_result(kind, country, component, best, target_id=""):
4236
  return result
4237
 
4238
 
4239
- def evaluate_component_from_uploaded_source_records(country, material, component, target_id=""):
4240
- terms = source_match_terms_for_component(material, component)
4241
- representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-"
4242
- if not terms:
4243
- return None
4244
-
4245
- records, status = build_country_source_record_index(country)
4246
- hits = []
4247
- for rec in records:
4248
- rec_text = safe_str(rec.get("text", ""))
4249
- if _v51_component_match_in_record(rec_text, terms):
4250
- hits.append(rec)
4251
-
4252
- if not hits:
4253
- return None
4254
-
4255
- priority = {
4256
- "legal_prohibited": 100,
4257
- "legal_restricted": 90,
4258
- "positive_list": 70,
4259
- "nonlegal_retailer": 60,
4260
- "nonlegal_prop65": 58,
4261
- "nonlegal_voluntary": 56,
4262
- "nonlegal_impurity": 54,
4263
- "nonlegal_labeling": 52,
4264
- "reference": 20,
4265
- "unknown": 10,
4266
- }
4267
- typed_hits = [(rec, _v51_record_type(country, rec, component)) for rec in hits]
4268
- typed_hits.sort(key=lambda x: priority.get(x[1], 0), reverse=True)
4269
- best, kind = typed_hits[0]
4270
- context = safe_str(best.get("text", ""))
4271
- src_note = f"[출처파일: {best.get('source_file', '')}] [row: {best.get('row_index', '')}] {context[:900]}"
4272
- country_col = display_country(country)
4273
-
4274
- if kind == "legal_prohibited":
4275
- result = {
4276
- "대표 INCI": representative,
4277
- "결과": f"{country_col}: 업로드 법정 금지 폴더/파일에서 성분 직접 확인",
4278
- "표시문구": "배합금지",
4279
- "비고": src_note,
4280
- }
4281
- log_search_context(target_id, country, component, result["결과"], "V51_LEGAL_PROHIBITED", result["비고"])
4282
- return result
4283
-
4284
- if kind == "legal_restricted":
4285
- limit_text, condition_text = extract_limit_condition_from_context(context)
4286
- result = {
4287
- "대표 INCI": representative,
4288
- "결과": f"{country_col}: 업로드 법정 제한 폴더/파일에서 성분 직접 확인" + (f" / 한도 {limit_text}" if limit_text else " / 한도·조건 확인 필요") + (f" / 조건: {condition_text}" if condition_text else ""),
4289
- "표시문구": f"배합한도: {limit_text}" if limit_text else NEED_CHECK_TEXT,
4290
- "비고": src_note,
4291
- }
4292
- log_search_context(target_id, country, component, result["결과"], "V51_LEGAL_RESTRICTED", result["비고"])
4293
- return result
4294
-
4295
- if kind == "positive_list":
4296
- limit_text, condition_text = extract_limit_condition_from_context(context)
4297
- if limit_text:
4298
- result = {
4299
- "대표 INCI": representative,
4300
- "결과": f"{country_col}: 허용목록에서 성분 직접 확인 / 한도 {limit_text}" + (f" / 조건: {condition_text}" if condition_text else ""),
4301
- "표시문구": f"배합한도: {limit_text}",
4302
- "비고": src_note,
4303
- }
4304
- log_search_context(target_id, country, component, result["결과"], "V51_POSITIVE_LIST_LIMIT", result["비고"])
4305
- return result
4306
- result = {
4307
- "대표 INCI": representative,
4308
- "결과": NO_EVIDENCE_TEXT,
4309
- "표시문구": "Pass",
4310
- "비고": "허용목록에서 성분명 확인. 명확한 배합한도 수치 근거 없음. " + src_note,
4311
- }
4312
- log_search_context(target_id, country, component, result["결과"], "V51_POSITIVE_LIST_PASS", result["비고"])
4313
- return result
4314
-
4315
- if kind.startswith("nonlegal_") or kind == "reference":
4316
- return _v51_nonlegal_result(kind, country, component, best, target_id)
4317
-
4318
- result = {
4319
- "대표 INCI": representative,
4320
- "결과": NO_EVIDENCE_TEXT,
4321
- "표시문구": "Pass",
4322
- "비고": "성분명은 업로드 파일에서 발견���었으나 금지/제한/한도 근거 없음. " + src_note,
4323
- }
4324
- log_search_context(target_id, country, component, result["결과"], "V51_SOURCE_NAME_ONLY_PASS", result["비고"])
4325
- return result
4326
-
4327
-
4328
- def evaluate_component_from_country_files_only(country, material, component, target_id=""):
4329
- representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-"
4330
-
4331
- if is_always_pass_component(material, component):
4332
- result = {
4333
- "대표 INCI": representative if representative != "-" else "Water",
4334
- "결과": NO_EVIDENCE_TEXT,
4335
- "표시문구": "Pass",
4336
- "비고": "정제수/Water/Aqua 기본 Pass 처리",
4337
- }
4338
- log_search_context(target_id, country, component, result["결과"], "ALWAYS_PASS_RULE", result["비고"])
4339
- return result
4340
-
4341
- source_result = evaluate_component_from_uploaded_source_records(country, material, component, target_id)
4342
- if source_result is not None:
4343
- return source_result
4344
-
4345
- result = {
4346
- "대표 INCI": representative,
4347
- "결과": NO_EVIDENCE_TEXT,
4348
- "표시문구": "Pass",
4349
- "비고": "업로드된 국가별 파일 내 현재 성분 직접 근거 없음",
4350
- }
4351
- log_search_context(target_id, country, component, result["결과"], "V51_SOURCE_NO_HIT_PASS", result["비고"])
4352
- return result
4353
-
4354
-
4355
- def is_country_result_issue(text):
4356
- text = safe_str(text)
4357
- if not text or text in ["-", NO_EVIDENCE_TEXT, "Pass", "PASS", "pass"]:
4358
- return False
4359
- if "허용목록" in text and not _v51_text_has_any(text, V51_RESTRICTED_TERMS + V51_PROHIBITED_TERMS):
4360
- return False
4361
- issue_markers = [
4362
- "배합금지", "금지", "배합한도", "한도", "확인 필요", "경고표시", "Clean 기준",
4363
- "불순물", "오염물질", "자율기준", "표시기준", "부적합", "재검토", "사용 불가", "사용불가",
4364
- ]
4365
- return _v51_text_has_any(text, issue_markers + V51_PROHIBITED_TERMS + V51_RESTRICTED_TERMS)
4366
-
4367
  # ============================================================
4368
  # END STRUCTURED FOLDER SCREENING PATCH V5.1
4369
  # ============================================================
4370
 
4371
 
4372
-
4373
-
4374
  # ============================================================
4375
  # STRUCTURED FOLDER SCREENING PATCH V5.2
4376
  # 2026-06: US 폴더명 반영 + 주요 오판정 차단
@@ -4380,35 +3742,8 @@ def is_country_result_issue(text):
4380
  # - Phenoxyethanol: EU/ASEAN/KOREA/JAPAN 보존제 최대 1.0% 한도로 고정 보정
4381
  # ============================================================
4382
 
4383
- COUNTRY_ORDER = ["ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "US", "JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA"]
4384
  COUNTRY_DISPLAY.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "US"})
4385
  COUNTRY_FOLDER_ALIASES.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "us"})
4386
- 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__')]
4387
-
4388
-
4389
- def country_key(country):
4390
- t = safe_str(country).upper().replace("_", " ").replace("-", " ")
4391
- t = re.sub(r"\s+", " ", t).strip()
4392
- m = {
4393
- "한국": "KOREA", "KOREA": "KOREA", "KR": "KOREA",
4394
- "EU": "EU", "EUROPE": "EU", "유럽": "EU",
4395
- "EU FUTURE": "EU_FUTURE", "EU (FUTURE)": "EU_FUTURE",
4396
- "JAPAN": "JAPAN", "JP": "JAPAN", "일본": "JAPAN",
4397
- "CHINA": "CHINA", "CN": "CHINA", "중국": "CHINA",
4398
- "USA": "US", "US": "US", "미국": "US", "FDA": "US",
4399
- "ASEAN": "ASEAN", "아세안": "ASEAN",
4400
- "UK": "UK", "영국": "UK",
4401
- "SEPHORA": "SEPHORA", "TARGET": "TARGET", "ULTA": "ULTA",
4402
- "CALIFORNIA": "CALIFORNIA", "MEXICO": "MEXICO",
4403
- }
4404
- return m.get(t, t)
4405
-
4406
-
4407
- def display_country(country):
4408
- c = country_key(country)
4409
- if c == "US":
4410
- return "US"
4411
- return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), c))
4412
 
4413
 
4414
  def _v52_component_blob(material, component):
@@ -4538,35 +3873,6 @@ def _v51_record_type(country, record, component=None):
4538
  return "unknown"
4539
 
4540
 
4541
- def evaluate_component_from_country_files_only(country, material, component, target_id=""):
4542
- representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-"
4543
-
4544
- if is_always_pass_component(material, component):
4545
- result = {
4546
- "대표 INCI": representative if representative != "-" else "Water",
4547
- "결과": NO_EVIDENCE_TEXT,
4548
- "표시문구": "Pass",
4549
- "비고": "정제수/Water/Aqua 기본 Pass 처리",
4550
- }
4551
- log_search_context(target_id, country, component, result["결과"], "ALWAYS_PASS_RULE", result["비고"])
4552
- return result
4553
-
4554
- correction = _v52_known_correction(country, material, component, target_id)
4555
- if correction is not None:
4556
- return correction
4557
-
4558
- source_result = evaluate_component_from_uploaded_source_records(country, material, component, target_id)
4559
- if source_result is not None:
4560
- return source_result
4561
-
4562
- result = {
4563
- "대표 INCI": representative,
4564
- "결과": NO_EVIDENCE_TEXT,
4565
- "표시문구": "Pass",
4566
- "비고": "업로드된 국가별 파일 내 현재 성분 직접 근거 없음",
4567
- }
4568
- log_search_context(target_id, country, component, result["결과"], "V52_SOURCE_NO_HIT_PASS", result["비고"])
4569
- return result
4570
 
4571
  # ============================================================
4572
  # END STRUCTURED FOLDER SCREENING PATCH V5.2
@@ -4583,12 +3889,8 @@ def evaluate_component_from_country_files_only(country, material, component, tar
4583
  # - 파일명/문서 전체의 prohibited/limit 키워드만으로 성분 판정 금지
4584
  # ============================================================
4585
 
4586
- SOURCE_ONLY_MODE = True
4587
- TREAT_POSITIVE_LIST_AS_PASS = True
4588
- COUNTRY_ORDER = ["ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "US", "us", "JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA"]
4589
  COUNTRY_DISPLAY.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "US"})
4590
  COUNTRY_FOLDER_ALIASES.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "us", "Us": "US"})
4591
- 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__')]
4592
 
4593
 
4594
  def country_key(country):
@@ -4609,19 +3911,6 @@ def country_key(country):
4609
  return m.get(t, t)
4610
 
4611
 
4612
- def display_country(country):
4613
- c = country_key(country)
4614
- if c == "US":
4615
- return "US"
4616
- if c == "KOREA":
4617
- return "Korea"
4618
- if c == "JAPAN":
4619
- return "일본"
4620
- if c == "CHINA":
4621
- return "중국"
4622
- return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), c))
4623
-
4624
-
4625
  def _v6_path_text(record):
4626
  return f"{safe_str(record.get('source_file',''))}\n{safe_str(record.get('sheet',''))}".replace('\\', '/')
4627
 
@@ -4868,125 +4157,6 @@ def _v6_nonlegal_result(country, material, component, record, rtype, target_id="
4868
  return _v6_result(representative, NO_EVIDENCE_TEXT, "Pass", src, target_id, country, component, "V6_REFERENCE_ONLY_NO_LEGAL_CLASSIFICATION")
4869
 
4870
 
4871
- def pick_best_source_record(records):
4872
- priority = {
4873
- "legal_prohibited": 100,
4874
- "legal_restricted": 80,
4875
- "positive_list": 60,
4876
- "nonlegal_prop65": 45,
4877
- "nonlegal_retailer": 40,
4878
- "nonlegal_impurity": 35,
4879
- "nonlegal_voluntary": 30,
4880
- "nonlegal_labeling": 30,
4881
- "reference_microplastics": 20,
4882
- "reference": 10,
4883
- "unknown": 0,
4884
- }
4885
- return sorted(records, key=lambda r: priority.get(r.get("v6_type", "unknown"), 0), reverse=True)[0] if records else None
4886
-
4887
-
4888
- def evaluate_component_from_uploaded_source_records(country, material, component, target_id=""):
4889
- """
4890
- V6 source-table-row engine.
4891
- 성분명/CAS가 같은 row/window에 직접 있는 경우만 hit로 인정하고,
4892
- 폴더/Annex/Appendix 구조가 법정 유형을 결정한다.
4893
- """
4894
- terms = _v6_component_terms(material, component)
4895
- representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-"
4896
- if not terms:
4897
- return None
4898
-
4899
- records, status = build_country_source_record_index(country)
4900
- hits = []
4901
- for rec in records:
4902
- if not _v6_row_direct_match(rec.get("text", ""), terms):
4903
- continue
4904
- rtype = _v6_record_type(country, rec, material, component)
4905
- rec2 = dict(rec)
4906
- rec2["v6_type"] = rtype
4907
- hits.append(rec2)
4908
-
4909
- if not hits:
4910
- return None
4911
-
4912
- best = pick_best_source_record(hits)
4913
- rtype = best.get("v6_type", "unknown")
4914
- context = safe_str(best.get("text", ""))
4915
- src_note = f"[출처파일: {best.get('source_file','')}] [row: {best.get('row_index','')}] {context[:900]}"
4916
- cdisp = display_country(country)
4917
-
4918
- if rtype == "legal_prohibited":
4919
- return _v6_result(
4920
- representative,
4921
- f"{cdisp}: 법정 금지목록에서 성분 직접 확인",
4922
- "배합금지",
4923
- src_note,
4924
- target_id, country, component, "V6_ROW_MATCH_PROHIBITED_FOLDER",
4925
- )
4926
-
4927
- if rtype == "legal_restricted":
4928
- limit_text, condition_text = _v6_extract_limit_condition_from_row(context)
4929
- formula = f"배합한도: {limit_text}" if limit_text else NEED_CHECK_TEXT
4930
- result_text = f"{cdisp}: 법정 제한목록에서 성분 직접 확인" + (f" / 조건: {condition_text}" if condition_text else "")
4931
- return _v6_result(
4932
- representative,
4933
- result_text,
4934
- formula,
4935
- src_note,
4936
- target_id, country, component, "V6_ROW_MATCH_RESTRICTED_FOLDER",
4937
- )
4938
-
4939
- if rtype == "positive_list":
4940
- limit_text, condition_text = _v6_extract_limit_condition_from_row(context)
4941
- formula = f"배합한도: {limit_text}" if limit_text else "허용목록 등재 / 한도 확인 필요"
4942
- result_text = f"{cdisp}: 허용목록에서 성분 직접 확인" + (f" / 조건: {condition_text}" if condition_text else "")
4943
- source_tag = "V6_ROW_MATCH_POSITIVE_LIST_LIMIT" if limit_text else "V6_ROW_MATCH_POSITIVE_LIST"
4944
- return _v6_result(
4945
- representative,
4946
- result_text,
4947
- formula,
4948
- src_note,
4949
- target_id, country, component, source_tag,
4950
- )
4951
-
4952
- if rtype in ["nonlegal_prop65", "nonlegal_retailer", "nonlegal_impurity", "nonlegal_voluntary", "nonlegal_labeling", "reference", "reference_microplastics"]:
4953
- return _v6_nonlegal_result(country, material, component, best, rtype, target_id)
4954
-
4955
- # unknown 폴더/파일은 성분명이 있어도 법정 금지·한도 판정을 만들지 않는다.
4956
- return _v6_result(
4957
- representative,
4958
- NO_EVIDENCE_TEXT,
4959
- "Pass",
4960
- src_note + " / 파일 유형 미분류: 법정 금지·한도 자동판정 제외",
4961
- target_id, country, component, "V6_UNKNOWN_SOURCE_NO_LEGAL_CLASSIFICATION",
4962
- )
4963
-
4964
-
4965
- def evaluate_component_from_country_files_only(country, material, component, target_id=""):
4966
- representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-"
4967
-
4968
- if is_always_pass_component(material, component):
4969
- return _v6_result(
4970
- representative if representative != "-" else "Water",
4971
- NO_EVIDENCE_TEXT,
4972
- "Pass",
4973
- "정제수/Water/Aqua 기본 Pass 처리",
4974
- target_id, country, component, "ALWAYS_PASS_RULE",
4975
- )
4976
-
4977
- source_result = evaluate_component_from_uploaded_source_records(country, material, component, target_id)
4978
- if source_result is not None:
4979
- return source_result
4980
-
4981
- return _v6_result(
4982
- representative,
4983
- NO_EVIDENCE_TEXT,
4984
- "Pass",
4985
- "업로드된 국가별 파일 내 현재 성분의 같은 행/근접 행 직접 근거 없음",
4986
- target_id, country, component, "V6_NO_ROW_MATCH_PASS",
4987
- )
4988
-
4989
-
4990
  def evaluate_critical_country_rule(country, material, component):
4991
  if SOURCE_ONLY_MODE:
4992
  return None
@@ -5005,16 +4175,6 @@ def evaluate_local_rules(country, material, component, ingredient_totals, ingred
5005
  return None
5006
 
5007
 
5008
- def is_country_result_issue(text):
5009
- text = safe_str(text)
5010
- if not text or text in ["-", NO_EVIDENCE_TEXT, "Pass", "PASS", "pass"]:
5011
- return False
5012
- if "허용목록" in text and not _v6_has(text, ["배합한도", "한도", "조건", "확인 필요"]):
5013
- return False
5014
- return _v6_has(text, [
5015
- "배합금지", "배합한도", "한도", "확인 필요", "경고표시", "Clean 기준", "불순물", "오염물질",
5016
- "자율기준", "표시기준", "부적합", "재검토", "사용 불가", "사용불가", "Microplastics",
5017
- ])
5018
 
5019
  # ============================================================
5020
  # END SOURCE TABLE ROW ENGINE PATCH V6
@@ -5433,8 +4593,6 @@ def is_country_result_issue(text):
5433
  # ============================================================
5434
 
5435
 
5436
-
5437
-
5438
  # ============================================================
5439
  # USER PATCH 2026-06-15
5440
  # 1) Output country/channel display names forced to English
@@ -5495,7 +4653,7 @@ def display_country(country):
5495
  return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), c))
5496
 
5497
 
5498
- _ORIGINAL_get_country_folders = get_country_folders
5499
 
5500
 
5501
  def get_country_folders():
@@ -5503,7 +4661,7 @@ def get_country_folders():
5503
  return [c for c in _ORIGINAL_get_country_folders() if not _is_hidden_always_folder(c)]
5504
 
5505
 
5506
- _ORIGINAL_refresh_country_choices_keep_selection = refresh_country_choices_keep_selection
5507
 
5508
 
5509
  def refresh_country_choices_keep_selection(current_values=None):
@@ -5520,7 +4678,7 @@ def refresh_country_choices_and_clear_cache(current_values=None):
5520
  return refresh_country_choices_keep_selection(current_values)
5521
 
5522
 
5523
- _ORIGINAL_get_country_section_index_cached = get_country_section_index_cached
5524
 
5525
 
5526
  def get_country_section_index_cached(country):
@@ -5635,8 +4793,6 @@ with gr.Blocks(css=custom_css) as demo:
5635
  </script>
5636
 
5637
 
5638
-
5639
-
5640
  """)
5641
  gr.Markdown("### Screening")
5642
 
 
35
  # reBom Regulatory Screening AI - compact full app.py
36
  # Excel/PDF/Image input + country folder RAG + local rules + single ingredient search
37
 
38
+ import os, re, json, base64, hashlib, traceback, sqlite3, secrets, datetime, time, sys, subprocess
39
  from pathlib import Path
40
  from collections import defaultdict
41
  from functools import lru_cache
 
93
  REG_TEXT_CACHE = {}
94
  REG_SECTION_INDEX_CACHE = {}
95
 
96
+ COUNTRY_ORDER = ["ASEAN", "CALIFORNIA", "CHINA", "EU (FUTURE)", "EU", "US", "us", "JAPAN", "KOREA", "MEXICO", "SEPHORA", "TARGET", "UK", "ULTA"]
97
  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"}
98
  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"}
99
+ 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__')]
100
  ALLOWED_PATHS = [str(OUTPUT_DIR), str(BASE_DIR)]
101
  SUPPORTED_INPUT_EXTENSIONS = {".xlsx",".xls",".pdf",".png",".jpg",".jpeg",".webp"}
102
  SUPPORTED_REG_FILE_EXTENSIONS = {".pdf",".txt",".csv",".xlsx",".xls"}
 
164
  def chunk_list(items,size):
165
  for i in range(0,len(items),size): yield items[i:i+size]
166
 
 
 
 
 
167
 
 
168
  def get_embeddings():
169
  global EMBEDDINGS_CACHE
170
  if EMBEDDINGS_CACHE is None: EMBEDDINGS_CACHE=OpenAIEmbeddings(model="text-embedding-3-small")
 
252
  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(영문)","")]))
253
  return any(normalize_compact(w) in identity for w in ["향료","fragrance","parfum","perfume","aroma"])
254
 
 
 
 
255
 
256
  def get_restricted_candidate_reason(material,component):
257
  if is_always_pass_component(material,component): return ""
 
268
  if normalize_compact(component.get("한글 성분명",""))==normalize_compact("살리실릭애씨드"): return "제한 가능성 성분"
269
  return ""
270
 
 
 
 
 
271
 
272
  def log_search_context(target_id,country,component,result_text,source,context):
273
  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]})
 
306
  result_obj["비고"]=(note+" / "+ev) if note and note!="-" else ev
307
  return result_obj
308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
 
310
 
311
  def standardize_formula_dataframe(df):
 
556
  return False
557
 
558
 
 
 
559
  # ============================================================
560
  # 규제 동의어 / CAS / 이성질체 레지스트리
561
  # - 국가별 파일 표기가 INCI와 다를 때 PASS 오판을 막기 위한 보정층
 
1144
  return False
1145
 
1146
 
 
 
1147
  # country db
1148
 
1149
  def resolve_country_folder(country):
 
1153
  fmap={f.lower():f for f in os.listdir(".") if os.path.isdir(f)}
1154
  return fmap.get(alias.lower(),alias)
1155
 
1156
+ def _base_get_country_folders():
1157
  exclude={".git",".cache","__pycache__",".ipynb_checkpoints",".venv","venv","node_modules",FAISS_CACHE_DIR,"outputs"}
1158
  folders=[f for f in os.listdir(".") if os.path.isdir(f) and f not in exclude]
1159
  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])
1160
  return ordered+extras if ordered or extras else COUNTRY_ORDER.copy()
1161
 
1162
+ def _base_refresh_country_choices_keep_selection(current_values=None):
1163
  choices=get_country_folders(); kept=[v for v in (current_values or []) if v in choices]
1164
  return gr.update(choices=choices,value=kept)
1165
 
 
 
1166
 
1167
  def get_regulatory_file_list(folder):
1168
  files=[]
 
1461
  return False
1462
 
1463
 
 
 
1464
  def mfds_click_first_detail_result(page):
1465
  """
1466
  식약처 검색 결과에서 검색어와 결과명칭이 다를 수 있다.
 
1749
  return [], last_error[:300]
1750
 
1751
 
 
 
1752
  def mfds_launch_chromium(playwright_obj):
1753
  """
1754
  Playwright Chromium 브라우저 실행 함수.
 
1943
  }
1944
 
1945
 
 
 
 
 
 
 
 
 
 
1946
 
1947
  def evaluate_limit_rule(country,material,component,group,name):
1948
  key=match_rule_key(material,component,group)
 
1956
  return {"대표 INCI":label,"결과":f"{name} / {label} 현재 함량 {at}%, 한도 {format_percent(lim)}% 이내","표시문구":cr.get("formula_text") or f"배합한도: {format_percent(lim)}%","비고":"-"}
1957
  return {"대표 INCI":label,"결과":f"{name} / {label} / 한도값 확인 필요","표시문구":LIMIT_CHECK_TEXT,"비고":"로컬 규칙에 성분은 있으나 한도값이 비어 있음."}
1958
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1959
 
1960
  def parse_country_response(text):
1961
  res={"대표 INCI":"-","결과":NO_EVIDENCE_TEXT,"표시문구":"Pass","비고":"-"}
 
2014
  for cc in country_cols: total_row[cc]=""
2015
  rows.append(total_row); return pd.DataFrame(rows)
2016
 
 
 
 
 
 
 
 
 
 
 
2017
 
2018
  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)","")))
2019
 
 
2036
  for col in range(1,sheet.max_column+1): sheet.column_dimensions[get_column_letter(col)].width=18
2037
  wb.save(path)
2038
 
 
 
 
2039
 
2040
  def process(countries,file,product_name="",use_mfds_live=False,live_max_terms=5,live_headless=True):
2041
  """
 
2311
  return mat, comp, at
2312
 
2313
 
 
 
 
2314
  def get_country_regulatory_text_cached(country):
2315
  """
2316
  국가별 규제 파일 원문을 직접 읽어서 캐시한다.
 
2544
  return sections
2545
 
2546
 
2547
+ def _base_get_country_section_index_cached(country):
2548
  """
2549
  단일 성분 검색 고속화용 섹션 인덱스.
2550
  국가별 파일을 매번 PDF/Excel 전체 읽기하지 않고,
 
2809
  return "\n".join(messages) if messages else "선택된 국가 없음"
2810
 
2811
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2812
  def make_restricted_or_positive_result(country, component, match, reg_type):
2813
  context = safe_str(match.get("context", "")) if isinstance(match, dict) else safe_str(match)
2814
  label = safe_str(reg_type.get("label", "규제 목록"))
 
3021
  return records, "BUILT_SOURCE_RECORD_INDEX"
3022
 
3023
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3024
  def shorten_for_table(value, max_len=80):
3025
  value = safe_str(value)
3026
 
 
3321
  DEFAULT_ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "qwer0515!")
3322
 
3323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3324
  # ============================================================
3325
  # Gradio 기본 auth 사용 시 내부 로그인 체크 우회
3326
  # ============================================================
3327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3328
 
3329
  # ============================================================
3330
  # 로그인 인증
 
3332
  # - USER_DB에 여러 아이디/비밀번호를 직접 등록
3333
  # ============================================================
3334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3335
 
3336
  # ============================================================
3337
  # 로그인 인증
 
3343
  # "메일주소": "비밀번호",
3344
  # ============================================================
3345
 
 
 
3346
 
3347
+ # Gradio 기본 auth를 통과한 사용자는 이미 인증된 상태이므로 내부 로그인 체크를 하지 않는다.
 
 
 
3348
 
3349
 
3350
+ # ============================================================
3351
+ # 로그인 인증
3352
+ # - Gradio 기본 로그인창 사용
3353
+ # - 아래 USER_DB에 메일/비밀번호를 직접 등록
3354
+ # ============================================================
3355
 
3356
 
3357
+ # ============================================================
3358
+ # 로그인 인증
3359
+ # - Gradio 기본 로그인창 사용
3360
+ # - 아래 USER_DB에 메일/비밀번호를 직접 등록
3361
+ # ============================================================
3362
 
3363
 
3364
+ # ============================================================
3365
+ # 로그인 인증
3366
+ # - Gradio 기본 로그인창 사용
3367
+ # - 아래 USER_DB에 메일/비밀번호를 직접 등록
 
 
 
 
3368
 
3369
 
3370
 
 
3373
  # - Gradio 기본 로그인창 사용
3374
  # - 아래 USER_DB에 메일/비밀번호를 직접 등록
3375
  # ============================================================
3376
+ # 사용자 추가 방법:
3377
+ # USER_DB 안에 "아이디": "비밀번호", 형식으로 한 줄씩 추가하세요.
3378
+ # 각 줄 끝에는 콤마(,)를 붙이는 것을 권장합니다.
3379
+ # ============================================================
3380
 
3381
  USER_DB = {
3382
  "jin2li@rebom.kr": "qwer0515!",
3383
+ "jkh@rebom.kr": "rebom123!",
3384
+ "admin": "rebom123!",
3385
 
3386
  # 사용자 등록 예시:
3387
  # "yubin.p@rebom.kr": "123456!",
 
3388
  }
3389
 
3390
 
 
3407
  single_use_mfds_live,
3408
  )
3409
 
3410
+ # ============================================================
3411
+ # STRUCTURED FOLDER SCREENING PATCH V5.1
3412
+ # 기존 UI/로그인/엑셀 출력 형태는 유지하고, 판정 엔진만 폴더 구조 기준으로 재정의
3413
+ # ============================================================
3414
 
3415
+ SOURCE_ONLY_MODE = True
3416
+ TREAT_POSITIVE_LIST_AS_PASS = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3417
 
3418
  V51_PROHIBITED_TERMS = [
3419
  "배합금지", "사용금지", "사용 금지", "금지원료", "금지 원료", "금지성분", "금지 성분",
 
3563
 
3564
  return has_glycerin and has_deg and has_impurity_limit
3565
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3566
 
3567
 
3568
  def _v51_component_match_in_record(record_text, terms):
 
3654
  return "Pass"
3655
 
3656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3657
  def _v51_nonlegal_result(kind, country, component, best, target_id=""):
3658
  country_col = display_country(country)
3659
  representative = safe_str(component.get("INCI Name", "")) or safe_str(component.get("한글 성분명", "")) or safe_str(component.get("CAS.No", "")) or "-"
 
3728
  return result
3729
 
3730
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3731
  # ============================================================
3732
  # END STRUCTURED FOLDER SCREENING PATCH V5.1
3733
  # ============================================================
3734
 
3735
 
 
 
3736
  # ============================================================
3737
  # STRUCTURED FOLDER SCREENING PATCH V5.2
3738
  # 2026-06: US 폴더명 반영 + 주요 오판정 차단
 
3742
  # - Phenoxyethanol: EU/ASEAN/KOREA/JAPAN 보존제 최대 1.0% 한도로 고정 보정
3743
  # ============================================================
3744
 
 
3745
  COUNTRY_DISPLAY.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "US"})
3746
  COUNTRY_FOLDER_ALIASES.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "us"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3747
 
3748
 
3749
  def _v52_component_blob(material, component):
 
3873
  return "unknown"
3874
 
3875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3876
 
3877
  # ============================================================
3878
  # END STRUCTURED FOLDER SCREENING PATCH V5.2
 
3889
  # - 파일명/문서 전체의 prohibited/limit 키워드만으로 성분 판정 금지
3890
  # ============================================================
3891
 
 
 
 
3892
  COUNTRY_DISPLAY.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "US"})
3893
  COUNTRY_FOLDER_ALIASES.update({"FDA": "US", "미국": "US", "USA": "US", "US": "US", "us": "us", "Us": "US"})
 
3894
 
3895
 
3896
  def country_key(country):
 
3911
  return m.get(t, t)
3912
 
3913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3914
  def _v6_path_text(record):
3915
  return f"{safe_str(record.get('source_file',''))}\n{safe_str(record.get('sheet',''))}".replace('\\', '/')
3916
 
 
4157
  return _v6_result(representative, NO_EVIDENCE_TEXT, "Pass", src, target_id, country, component, "V6_REFERENCE_ONLY_NO_LEGAL_CLASSIFICATION")
4158
 
4159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4160
  def evaluate_critical_country_rule(country, material, component):
4161
  if SOURCE_ONLY_MODE:
4162
  return None
 
4175
  return None
4176
 
4177
 
 
 
 
 
 
 
 
 
 
 
4178
 
4179
  # ============================================================
4180
  # END SOURCE TABLE ROW ENGINE PATCH V6
 
4593
  # ============================================================
4594
 
4595
 
 
 
4596
  # ============================================================
4597
  # USER PATCH 2026-06-15
4598
  # 1) Output country/channel display names forced to English
 
4653
  return COUNTRY_DISPLAY.get(str(country).upper(), COUNTRY_DISPLAY.get(str(country), c))
4654
 
4655
 
4656
+ _ORIGINAL_get_country_folders = _base_get_country_folders
4657
 
4658
 
4659
  def get_country_folders():
 
4661
  return [c for c in _ORIGINAL_get_country_folders() if not _is_hidden_always_folder(c)]
4662
 
4663
 
4664
+ _ORIGINAL_refresh_country_choices_keep_selection = _base_refresh_country_choices_keep_selection
4665
 
4666
 
4667
  def refresh_country_choices_keep_selection(current_values=None):
 
4678
  return refresh_country_choices_keep_selection(current_values)
4679
 
4680
 
4681
+ _ORIGINAL_get_country_section_index_cached = _base_get_country_section_index_cached
4682
 
4683
 
4684
  def get_country_section_index_cached(country):
 
4793
  </script>
4794
 
4795
 
 
 
4796
  """)
4797
  gr.Markdown("### Screening")
4798