jin2li commited on
Commit
fd2df95
ยท
verified ยท
1 Parent(s): 1330d1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +384 -3
app.py CHANGED
@@ -56,6 +56,14 @@ from langchain_openai import OpenAIEmbeddings, ChatOpenAI
56
  from langchain_community.vectorstores import FAISS
57
  from langchain_text_splitters import RecursiveCharacterTextSplitter
58
 
 
 
 
 
 
 
 
 
59
  BASE_DIR = Path.cwd().resolve()
60
  OUTPUT_DIR = BASE_DIR / "outputs"
61
  OUTPUT_DIR.mkdir(exist_ok=True)
@@ -64,6 +72,7 @@ REG_INDEX_CACHE_DIR = ".reg_index_cache"
64
  NO_EVIDENCE_TEXT = "ํ•ด๋‹น ์ž๋ฃŒ ๋‚ด ์ œํ•œ ๊ทผ๊ฑฐ ์—†์Œ"
65
  NEED_CHECK_TEXT = "ํ™•์ธ ํ•„์š”"
66
  LIMIT_CHECK_TEXT = "๋ฐฐํ•ฉํ•œ๋„ ํ™•์ธ ํ•„์š”"
 
67
  VECTOR_DB_CACHE = {}
68
  EVAL_CACHE = {}
69
  EMBEDDINGS_CACHE = None
@@ -528,10 +537,382 @@ def extract_terms_for_live_lookup(row_items):
528
  if t not in seen: seen.append(t)
529
  return seen
530
 
531
- def mfds_live_lookup_terms(terms,max_terms=30,headless=True):
532
- return pd.DataFrame(), f"MFDS ์‹ค์‹œ๊ฐ„ ์กฐํšŒ ๋น„ํ™œ์„ฑํ™”: ๊ฒ€์ƒ‰์–ด {len(terms[:int(max_terms)]) if terms else 0}๊ฐœ"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
533
 
534
- def evaluate_live_detail_rule(country,material,component,live_df): return None
535
 
536
  def evaluate_critical_country_rule(country,material,component):
537
  ckey=country_key(country); identity=get_identity_text(material,component)
 
56
  from langchain_community.vectorstores import FAISS
57
  from langchain_text_splitters import RecursiveCharacterTextSplitter
58
 
59
+ try:
60
+ from playwright.sync_api import sync_playwright
61
+ PLAYWRIGHT_AVAILABLE = True
62
+ except Exception:
63
+ sync_playwright = None
64
+ PLAYWRIGHT_AVAILABLE = False
65
+
66
+
67
  BASE_DIR = Path.cwd().resolve()
68
  OUTPUT_DIR = BASE_DIR / "outputs"
69
  OUTPUT_DIR.mkdir(exist_ok=True)
 
72
  NO_EVIDENCE_TEXT = "ํ•ด๋‹น ์ž๋ฃŒ ๋‚ด ์ œํ•œ ๊ทผ๊ฑฐ ์—†์Œ"
73
  NEED_CHECK_TEXT = "ํ™•์ธ ํ•„์š”"
74
  LIMIT_CHECK_TEXT = "๋ฐฐํ•ฉํ•œ๋„ ํ™•์ธ ํ•„์š”"
75
+ MFDS_LIVE_URL = "https://nedrug.mfds.go.kr/pbp/CCBDF01"
76
  VECTOR_DB_CACHE = {}
77
  EVAL_CACHE = {}
78
  EMBEDDINGS_CACHE = None
 
537
  if t not in seen: seen.append(t)
538
  return seen
539
 
540
+ def mfds_visible_text(page):
541
+ try:
542
+ return page.locator("body").inner_text(timeout=5000)
543
+ except Exception:
544
+ try:
545
+ return page.content()
546
+ except Exception:
547
+ return ""
548
+
549
+
550
+ def mfds_fill_search_input(page, term):
551
+ selectors = [
552
+ "input[type='search']",
553
+ "input[type='text']",
554
+ "input[placeholder*='๊ฒ€์ƒ‰']",
555
+ "input[placeholder*='์„ฑ๋ถ„']",
556
+ "input[placeholder*='์›๋ฃŒ']",
557
+ "input[title*='๊ฒ€์ƒ‰']",
558
+ "input:not([type])",
559
+ ]
560
+
561
+ for selector in selectors:
562
+ try:
563
+ loc = page.locator(selector)
564
+ count = min(loc.count(), 40)
565
+
566
+ for i in range(count):
567
+ item = loc.nth(i)
568
+
569
+ try:
570
+ if item.is_visible(timeout=700) and item.is_enabled(timeout=700):
571
+ item.fill(term, timeout=3000)
572
+ return True
573
+ except Exception:
574
+ continue
575
+ except Exception:
576
+ continue
577
+
578
+ return False
579
+
580
+
581
+ def mfds_click_search(page):
582
+ for text in ["๊ฒ€์ƒ‰", "์กฐํšŒ", "Search"]:
583
+ try:
584
+ loc = page.get_by_text(text, exact=True)
585
+
586
+ if loc.count() > 0:
587
+ loc.first.click(timeout=3000)
588
+ return True
589
+ except Exception:
590
+ pass
591
+
592
+ selectors = [
593
+ "button[type='submit']",
594
+ "input[type='submit']",
595
+ "button",
596
+ "a",
597
+ ".btn-search",
598
+ ".btn_search",
599
+ ".search",
600
+ ]
601
+
602
+ for selector in selectors:
603
+ try:
604
+ loc = page.locator(selector)
605
+ count = min(loc.count(), 60)
606
+
607
+ for i in range(count):
608
+ item = loc.nth(i)
609
+
610
+ try:
611
+ if selector == "input[type='submit']":
612
+ item.click(timeout=3000)
613
+ return True
614
+
615
+ text = ""
616
+ try:
617
+ text = item.inner_text(timeout=500)
618
+ except Exception:
619
+ pass
620
+
621
+ if "๊ฒ€์ƒ‰" in text or "์กฐํšŒ" in text or "Search" in text or selector in [".btn-search", ".btn_search", ".search"]:
622
+ item.click(timeout=3000)
623
+ return True
624
+ except Exception:
625
+ continue
626
+ except Exception:
627
+ continue
628
+
629
+ return False
630
+
631
+
632
+ def mfds_click_probable_result(page, term):
633
+ term_norm = normalize_compact(term)
634
+ selectors = [
635
+ "table tbody tr",
636
+ "tbody tr",
637
+ "tr",
638
+ ".list li",
639
+ ".result li",
640
+ ".search-result li",
641
+ ".card",
642
+ "a",
643
+ ]
644
+
645
+ for selector in selectors:
646
+ try:
647
+ rows = page.locator(selector)
648
+ count = min(rows.count(), 80)
649
+
650
+ for i in range(count):
651
+ row = rows.nth(i)
652
+
653
+ try:
654
+ row_text = row.inner_text(timeout=1000)
655
+ except Exception:
656
+ continue
657
+
658
+ row_norm = normalize_compact(row_text)
659
+
660
+ if term_norm and term_norm in row_norm:
661
+ row.click(timeout=3000)
662
+ page.wait_for_timeout(1000)
663
+ return True
664
+ except Exception:
665
+ continue
666
+
667
+ return False
668
+
669
+
670
+ def country_aliases_for_mfds(country):
671
+ c = country_key(country)
672
+ alias_map = {
673
+ "ASEAN": ["์•„์„ธ์•ˆ", "ASEAN"],
674
+ "EU": ["์œ ๋Ÿฝ", "EU", "์œ ๋Ÿฝ์—ฐํ•ฉ", "European Union", "Europe"],
675
+ "FDA": ["๋ฏธ๊ตญ", "USA", "US", "United States", "FDA"],
676
+ "KOREA": ["ํ•œ๊ตญ", "๋Œ€ํ•œ๋ฏผ๊ตญ", "Korea", "KOREA"],
677
+ "JAPAN": ["์ผ๋ณธ", "Japan", "JAPAN"],
678
+ "CHINA": ["์ค‘๊ตญ", "China", "CHINA"],
679
+ "UK": ["์˜๊ตญ", "UK", "United Kingdom"],
680
+ }
681
+ return alias_map.get(c, [safe_str(country), display_country(country)])
682
+
683
+
684
+ def parse_mfds_detail_text(term, text):
685
+ """
686
+ ์‹์•ฝ์ฒ˜ ์ƒ์„ธ ํ™”๋ฉด์˜ ํ‘œ์‹œ ํ…์ŠคํŠธ์—์„œ ๊ตฌ๋ถ„/๋ฐฐํ•ฉ๊ธˆ์ง€๊ตญ๊ฐ€/์ œํ•œ๊ตญ๊ฐ€/์ œํ•œ์‚ฌํ•ญ์„ ๊ตฌ์กฐ์ ์œผ๋กœ ์ฝ๋Š”๋‹ค.
687
+
688
+ ๊ฒ€์ƒ‰์–ด์™€ ์‹์•ฝ์ฒ˜ ๊ณ ์‹œ์›๋ฃŒ๋ช…์ด ์„œ๋กœ ๋‹ฌ๋ผ๋„, ์ƒ์„ธ ํ™”๋ฉด์— ๋“ค์–ด๊ฐ„ ๊ฒฐ๊ณผ๋ผ๋ฉด
689
+ '๊ตฌ๋ถ„=๊ธˆ์ง€'์™€ '๋ฐฐํ•ฉ๊ธˆ์ง€๊ตญ๊ฐ€=์•„์„ธ์•ˆ' ๊ฐ™์€ ํ•„๋“œ ๊ธฐ์ค€์œผ๋กœ ํŒ์ •ํ•œ๋‹ค.
690
+ """
691
+ clean = re.sub(r"\s+", " ", safe_str(text)).strip()
692
+
693
+ if not clean:
694
+ return []
695
+
696
+ rows = []
697
+
698
+ prohibited_region = ""
699
+ restricted_region = ""
700
+
701
+ m = re.search(r"๋ฐฐํ•ฉ๊ธˆ์ง€๊ตญ๊ฐ€(.{0,1200})", clean)
702
+ if m:
703
+ prohibited_region = m.group(0)
704
+
705
+ m = re.search(r"(๋ฐฐํ•ฉ์ œํ•œ๊ตญ๊ฐ€|์ œํ•œ๊ตญ๊ฐ€|์ œํ•œ์‚ฌํ•ญ|์ œํ•œ๊ตญ๊ฐ€)(.{0,1500})", clean)
706
+ if m:
707
+ restricted_region = m.group(0)
708
+
709
+ notice_name = ""
710
+ m = re.search(r"๊ณ ์‹œ์›๋ฃŒ๋ช…\s*([^\n\r]{0,180}?)(?:๋‹จ์„œ์กฐํ•ญ|์ œํ•œ์‚ฌํ•ญ|๋ฐฐํ•ฉ๊ธˆ์ง€๊ตญ๊ฐ€|๋ฐฐํ•ฉ๋ชฉ์ |๊ธฐ์ค€์ผ์ž|$)", clean)
711
+ if m:
712
+ notice_name = m.group(1).strip(" :|-")
713
+
714
+ is_prohibited_page = ("๊ตฌ๋ถ„ ๊ธˆ์ง€" in clean) or ("๊ตฌ๋ถ„: ๊ธˆ์ง€" in clean) or ("๊ธˆ์ง€" in prohibited_region)
715
+ is_restricted_page = ("๊ตฌ๋ถ„ ์ œํ•œ" in clean) or ("๊ตฌ๋ถ„: ์ œํ•œ" in clean) or bool(restricted_region)
716
+
717
+ country_candidates = [
718
+ ("ASEAN", ["์•„์„ธ์•ˆ", "ASEAN"]),
719
+ ("EU", ["์œ ๋Ÿฝ", "EU", "์œ ๋Ÿฝ์—ฐํ•ฉ"]),
720
+ ("FDA", ["๋ฏธ๊ตญ", "USA", "United States", "FDA"]),
721
+ ("Korea", ["ํ•œ๊ตญ", "๋Œ€ํ•œ๋ฏผ๊ตญ"]),
722
+ ("์ผ๋ณธ", ["์ผ๋ณธ", "Japan"]),
723
+ ("์ค‘๊ตญ", ["์ค‘๊ตญ", "China"]),
724
+ ("UK", ["์˜๊ตญ", "UK", "United Kingdom"]),
725
+ ]
726
+
727
+ if is_prohibited_page:
728
+ region = prohibited_region or clean
729
+
730
+ for display, aliases in country_candidates:
731
+ if any(alias in region for alias in aliases):
732
+ rows.append({
733
+ "๊ฒ€์ƒ‰์–ด": term,
734
+ "์›๋ฃŒ๋ช…": notice_name or term,
735
+ "INCI": notice_name or term,
736
+ "CAS.No": "",
737
+ "๊ตฌ๋ถ„": "๊ธˆ์ง€",
738
+ "๊ตญ๊ฐ€": display,
739
+ "๊ทœ์ œ๋‚ด์šฉ": region[:1200],
740
+ "ํ•œ๋„": "",
741
+ "์กฐ๊ฑด": "",
742
+ "์ถœ์ฒ˜": "MFDS live: " + MFDS_LIVE_URL,
743
+ "์ƒ์„ธ์›๋ฌธ": clean[:6000],
744
+ })
745
+
746
+ if is_restricted_page and not rows:
747
+ region = restricted_region or clean
748
+
749
+ for display, aliases in country_candidates:
750
+ if any(alias in region for alias in aliases):
751
+ limit_match = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*%", region)
752
+ rows.append({
753
+ "๊ฒ€์ƒ‰์–ด": term,
754
+ "์›๋ฃŒ๋ช…": notice_name or term,
755
+ "INCI": notice_name or term,
756
+ "CAS.No": "",
757
+ "๊ตฌ๋ถ„": "์ œํ•œ",
758
+ "๊ตญ๊ฐ€": display,
759
+ "๊ทœ์ œ๋‚ด์šฉ": region[:1200],
760
+ "ํ•œ๋„": limit_match.group(0).replace(" ", "") if limit_match else "",
761
+ "์กฐ๊ฑด": "",
762
+ "์ถœ์ฒ˜": "MFDS live: " + MFDS_LIVE_URL,
763
+ "์ƒ์„ธ์›๋ฌธ": clean[:6000],
764
+ })
765
+
766
+ return rows
767
+
768
+
769
+ def mfds_live_lookup_terms(terms, max_terms=30, headless=True):
770
+ if not PLAYWRIGHT_AVAILABLE or sync_playwright is None:
771
+ return pd.DataFrame(), "MFDS ์‹ค์‹œ๊ฐ„ ์กฐํšŒ ์‹คํŒจ: playwright ๋ฏธ์„ค์น˜"
772
+
773
+ terms = [safe_str(t) for t in terms if safe_str(t)]
774
+ terms = terms[:int(max_terms)] if max_terms else terms[:30]
775
+
776
+ all_rows = []
777
+ errors = []
778
+
779
+ try:
780
+ with sync_playwright() as p:
781
+ browser = p.chromium.launch(
782
+ headless=True,
783
+ args=[
784
+ "--no-sandbox",
785
+ "--disable-setuid-sandbox",
786
+ "--disable-dev-shm-usage",
787
+ "--disable-gpu",
788
+ "--disable-software-rasterizer",
789
+ ],
790
+ )
791
+ context = browser.new_context(
792
+ viewport={"width": 1280, "height": 900},
793
+ ignore_https_errors=True,
794
+ user_agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36",
795
+ )
796
+ page = context.new_page()
797
+
798
+ for idx, term in enumerate(terms, start=1):
799
+ try:
800
+ page.goto(MFDS_LIVE_URL, wait_until="domcontentloaded", timeout=12000)
801
+ page.wait_for_timeout(1000)
802
+
803
+ if not mfds_fill_search_input(page, term):
804
+ errors.append(f"{term}: ๊ฒ€์ƒ‰ ์ž…๋ ฅ์ฐฝ ์ฐพ๊ธฐ ์‹คํŒจ")
805
+ continue
806
+
807
+ if not mfds_click_search(page):
808
+ try:
809
+ page.keyboard.press("Enter")
810
+ except Exception:
811
+ pass
812
+
813
+ page.wait_for_timeout(1500)
814
+ mfds_click_probable_result(page, term)
815
+ page.wait_for_timeout(1500)
816
+
817
+ detail_text = mfds_visible_text(page)
818
+ rows = parse_mfds_detail_text(term, detail_text)
819
+
820
+ if rows:
821
+ all_rows.extend(rows)
822
+ else:
823
+ errors.append(f"{term}: ์‹์•ฝ์ฒ˜ ์ƒ์„ธ ๊ทœ์ œ ํ•„๋“œ ๋ฏธ๊ฒ€์ถœ")
824
+ except Exception as e:
825
+ errors.append(f"{term}: {e}")
826
+
827
+ context.close()
828
+ browser.close()
829
+
830
+ except Exception as e:
831
+ return pd.DataFrame(), f"MFDS ๋ธŒ๋ผ์šฐ์ € ์‹คํ–‰ ์‹คํŒจ: {e}"
832
+
833
+ df = pd.DataFrame(all_rows)
834
+ msg = f"MFDS ์‹ค์‹œ๊ฐ„ ์กฐํšŒ ์™„๋ฃŒ: ๊ฒ€์ƒ‰์–ด {len(terms)}๊ฐœ, ๊ฒฐ๊ณผ {len(df)}ํ–‰"
835
+
836
+ if errors:
837
+ msg += " / ์ผ๋ถ€ ์‹คํŒจ: " + " ; ".join(errors[:4])
838
+
839
+ if len(errors) > 4:
840
+ msg += f" ์™ธ {len(errors) - 4}๊ฑด"
841
+
842
+ return df, msg
843
+
844
+
845
+ def ingredient_matches_live_row(material, component, row):
846
+ identity_values = [
847
+ component.get("ํ•œ๊ธ€ ์„ฑ๋ถ„๋ช…", ""),
848
+ component.get("INCI Name", ""),
849
+ component.get("CAS.No", ""),
850
+ material.get("Trade name(๊ตญ๋ฌธ)", ""),
851
+ material.get("Trade name(์˜๋ฌธ)", ""),
852
+ ]
853
+ identity = normalize_compact(" ".join([safe_str(x) for x in identity_values if safe_str(x)]))
854
+
855
+ query = safe_str(row.get("๊ฒ€์ƒ‰์–ด", ""))
856
+ query_norm = normalize_compact(query)
857
+
858
+ if query_norm and len(query_norm) >= 3 and query_norm in identity:
859
+ return True
860
+
861
+ for term in [row.get("์›๋ฃŒ๋ช…", ""), row.get("INCI", ""), row.get("CAS.No", "")]:
862
+ term_norm = normalize_compact(term)
863
+
864
+ if term_norm and len(term_norm) >= 3 and term_norm in identity:
865
+ return True
866
+
867
+ return False
868
+
869
+
870
+ def live_row_country_matches(country, row_country):
871
+ row_country = safe_str(row_country)
872
+ aliases = country_aliases_for_mfds(country)
873
+
874
+ return any(alias and normalize_compact(alias) in normalize_compact(row_country) for alias in aliases)
875
+
876
+
877
+ def evaluate_live_detail_rule(country, material, component, live_df):
878
+ if live_df is None or live_df.empty:
879
+ return None
880
+
881
+ hits = []
882
+
883
+ for _, row in live_df.iterrows():
884
+ if ingredient_matches_live_row(material, component, row) and live_row_country_matches(country, row.get("๊ตญ๊ฐ€", "")):
885
+ hits.append(row)
886
+
887
+ if not hits:
888
+ return None
889
+
890
+ row = hits[0]
891
+ category = safe_str(row.get("๊ตฌ๋ถ„", ""))
892
+ regulation = safe_str(row.get("๊ทœ์ œ๋‚ด์šฉ", ""))
893
+ limit = safe_str(row.get("ํ•œ๋„", ""))
894
+ source = safe_str(row.get("์ถœ์ฒ˜", "MFDS live"))
895
+
896
+ if "๊ธˆ์ง€" in category:
897
+ display = "๋ฐฐํ•ฉ๊ธˆ์ง€"
898
+ result_text = f"์‹์•ฝ์ฒ˜ ์‹ค์‹œ๊ฐ„ ์กฐํšŒ: {display_country(country)} ๋ฐฐํ•ฉ๊ธˆ์ง€"
899
+ elif limit:
900
+ display = f"๋ฐฐํ•ฉํ•œ๋„: {limit}"
901
+ result_text = f"์‹์•ฝ์ฒ˜ ์‹ค์‹œ๊ฐ„ ์กฐํšŒ: {display_country(country)} ์ œํ•œ / ํ•œ๋„ {limit}"
902
+ else:
903
+ display = NEED_CHECK_TEXT
904
+ result_text = f"์‹์•ฝ์ฒ˜ ์‹ค์‹œ๊ฐ„ ์กฐํšŒ: {display_country(country)} ์ œํ•œ/ํ™•์ธ ํ•„์š”"
905
+
906
+ if regulation:
907
+ result_text += " / " + regulation[:300]
908
+
909
+ return {
910
+ "๋Œ€ํ‘œ INCI": safe_str(component.get("INCI Name", "")) or safe_str(row.get("์›๋ฃŒ๋ช…", "")) or "-",
911
+ "๊ฒฐ๊ณผ": result_text,
912
+ "ํ‘œ์‹œ๋ฌธ๊ตฌ": display,
913
+ "๋น„๊ณ ": source,
914
+ }
915
 
 
916
 
917
  def evaluate_critical_country_rule(country,material,component):
918
  ckey=country_key(country); identity=get_identity_text(material,component)