jin2li commited on
Commit
17468dd
·
verified ·
1 Parent(s): c47ae0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +313 -199
app.py CHANGED
@@ -86,6 +86,19 @@ def format_no(value):
86
  return str(value).strip()
87
 
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  def get_country_folders():
90
  exclude = [
91
  ".git",
@@ -116,9 +129,9 @@ def preview_excel(file):
116
 
117
 
118
  # =========================
119
- # 컬럼 자동 추정
120
  # =========================
121
- def find_col_by_keywords(df, keywords, default_index=None, exclude_cols=None):
122
  exclude_cols = exclude_cols or []
123
  scores = []
124
 
@@ -127,24 +140,24 @@ def find_col_by_keywords(df, keywords, default_index=None, exclude_cols=None):
127
  continue
128
 
129
  header = str(col).lower()
 
 
 
130
  score = 0
131
 
132
  for kw in keywords:
133
  if kw.lower() in header:
134
- score += 10
135
 
136
- values = df[col].dropna().astype(str).str.strip()
137
- sample = " ".join(values.head(50).tolist()).lower()
138
-
139
- if any(k in sample for k in [
140
  "aqua", "water", "glycerin", "retinol", "niacinamide",
141
  "extract", "acid", "lecithin", "palmitate", "hexanediol",
142
  "triglyceride", "arginine", "crosspolymer", "squalane",
143
- "butylene glycol", "caprylic", "ceramide", "oil",
144
- "phenoxyethanol", "citral", "linalool", "limonene"
145
  ]):
146
  if any(k in keywords for k in ["inci", "ingredient", "성분", "전성분", "구성"]):
147
- score += 5
148
 
149
  scores.append((score, idx, col))
150
 
@@ -159,38 +172,15 @@ def find_col_by_keywords(df, keywords, default_index=None, exclude_cols=None):
159
  return df.columns[0]
160
 
161
 
162
- def find_main_columns(df):
163
- no_col = find_col_by_keywords(
164
- df,
165
- ["no", "번호", "순번"],
166
- default_index=0
167
- )
168
-
169
- trade_col = find_col_by_keywords(
170
- df,
171
- ["trade name", "trade", "원료명", "상품명", "raw material", "material", "복합"],
172
- default_index=1,
173
- exclude_cols=[no_col]
174
- )
175
-
176
- inci_col = find_col_by_keywords(
177
- df,
178
- ["inci", "ingredient", "성분", "전성분", "구성"],
179
- default_index=2,
180
- exclude_cols=[no_col, trade_col]
181
- )
182
-
183
- numeric_candidates = []
184
 
185
  for idx, col in enumerate(df.columns):
186
- if col in [no_col, trade_col, inci_col]:
187
  continue
188
 
189
  header = str(col).lower()
190
-
191
- if header in ["no", "번호", "순번", "index", "#"]:
192
- continue
193
-
194
  values = df[col].dropna()
195
 
196
  if values.empty:
@@ -204,55 +194,123 @@ def find_main_columns(df):
204
  continue
205
 
206
  score = 0
207
- if any(k in header for k in [
208
- "함량", "배합", "농도", "투입",
209
- "amount", "content", "concentration", "%"
210
- ]):
211
- score += 5
212
 
213
- numeric_candidates.append({
 
 
 
 
214
  "col": col,
215
  "idx": idx,
 
216
  "count": count,
217
- "non_null": len(values),
218
- "score": score
219
  })
220
 
221
- amount_col = None
222
- final_amount_col = None
 
 
223
 
224
- if numeric_candidates:
225
- # 값이 많이 채워진 숫자 컬럼 = 구성 성분별 최종 제품 내 함량일 가능성
226
- final_amount_col = sorted(
227
- numeric_candidates,
228
- key=lambda x: (x["non_null"], x["idx"]),
229
  reverse=True
230
- )[0]["col"]
 
 
 
 
 
 
231
 
232
- # 값이 적게 채워진 숫자 컬럼 = 원료 투입량일 가능성
233
- candidates_except_final = [
234
- c for c in numeric_candidates
235
- if c["col"] != final_amount_col
236
- ]
237
 
238
- if candidates_except_final:
239
- amount_col = sorted(
240
- candidates_except_final,
241
- key=lambda x: (x["score"], -x["non_null"], -x["idx"]),
242
- reverse=True
243
- )[0]["col"]
244
- else:
245
- amount_col = final_amount_col
246
-
247
- if amount_col is None:
248
- amount_col = find_col_by_keywords(
249
- df,
250
- ["함량", "amount", "농도", "concentration", "%"],
251
- default_index=3,
252
- exclude_cols=[no_col, trade_col, inci_col]
253
- )
254
 
255
- return no_col, trade_col, inci_col, amount_col, final_amount_col
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
 
257
 
258
  # =========================
@@ -313,65 +371,81 @@ def build_database(country_folder):
313
 
314
 
315
  # =========================
316
- # 복합 원료 그룹화
317
  # =========================
318
  def make_grouped_materials(df):
319
- no_col, trade_col, inci_col, amount_col, final_amount_col = find_main_columns(df)
320
 
321
- df = df.copy()
 
 
 
 
 
 
322
 
323
- if no_col in df.columns:
324
- df[no_col] = df[no_col].ffill()
325
-
326
- if trade_col in df.columns:
327
- df[trade_col] = df[trade_col].ffill()
328
 
329
- if amount_col in df.columns:
330
- df[amount_col] = df[amount_col].ffill()
 
331
 
332
- group_keys = [no_col, trade_col] if no_col != trade_col else [trade_col]
 
333
 
334
  grouped_materials = []
335
 
336
  for key, group in df.groupby(group_keys, dropna=True, sort=False):
337
- if isinstance(key, tuple):
338
- no_value = format_no(key[0])
339
- trade_name = safe_str(key[1])
340
- else:
341
- no_value = ""
342
- trade_name = safe_str(key)
343
 
344
- if not trade_name or trade_name.lower() == "nan":
345
- continue
346
-
347
- amount_value = "-"
348
 
349
- if amount_col in group.columns:
350
- amount_values = group[amount_col].dropna().tolist()
351
- if amount_values:
352
- amount_value = amount_values[0]
353
 
 
354
  inci_list = []
355
  final_amounts = []
356
 
357
  for _, row in group.iterrows():
358
- inci_name = safe_str(row.get(inci_col, ""))
 
359
 
360
- if inci_name and inci_name.lower() != "nan":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  inci_list.append(inci_name)
362
 
363
- if final_amount_col and final_amount_col in group.columns:
364
- v = row.get(final_amount_col)
365
- if not pd.isna(v):
366
- final_amounts.append(str(v))
367
 
368
  inci_list = list(dict.fromkeys(inci_list))
369
 
370
  grouped_materials.append({
371
  "NO": no_value,
372
- "Trade name": trade_name,
373
- "Amount": amount_value,
374
  "INCI_list": inci_list,
 
375
  "Final_amounts": final_amounts,
376
  "Group_records": group.to_dict(orient="records")
377
  })
@@ -405,7 +479,7 @@ def parse_country_response(text):
405
 
406
 
407
  # =========================
408
- # 국가별 판단
409
  # =========================
410
  def evaluate_one_country(country, material, llm):
411
  db = build_database(country)
@@ -417,9 +491,10 @@ def evaluate_one_country(country, material, llm):
417
  "비고": "-"
418
  }
419
 
420
- trade_name = material["Trade name"]
421
- amount_value = material["Amount"]
422
  inci_list = material["INCI_list"]
 
423
  final_amounts = material["Final_amounts"]
424
  group_records = material["Group_records"]
425
 
@@ -427,7 +502,6 @@ def evaluate_one_country(country, material, llm):
427
 
428
  regulatory_hints = []
429
 
430
- # 레티노이드 / 비타민A 계열
431
  if any(x in inci_text for x in [
432
  "retinol", "retinyl", "retinal", "retinoate",
433
  "hydroxypinacolone retinoate", "vitamin a"
@@ -436,7 +510,6 @@ def evaluate_one_country(country, material, llm):
436
  "retinol retinyl palmitate retinal retinoid vitamin A retinol equivalent RE"
437
  )
438
 
439
- # 향료 알레르겐 계열
440
  if any(x in inci_text for x in [
441
  "citral", "limonene", "linalool", "geraniol", "citronellol",
442
  "eugenol", "coumarin", "benzyl alcohol", "benzyl salicylate",
@@ -448,7 +521,6 @@ def evaluate_one_country(country, material, llm):
448
  "fragrance allergen perfume allergen labelling threshold leave-on rinse-off"
449
  )
450
 
451
- # 보존제 계열
452
  if any(x in inci_text for x in [
453
  "phenoxyethanol", "ethylhexylglycerin", "chlorphenesin",
454
  "methylisothiazolinone", "methylchloroisothiazolinone",
@@ -460,7 +532,6 @@ def evaluate_one_country(country, material, llm):
460
  "preservative maximum concentration leave-on rinse-off allowed preservative"
461
  )
462
 
463
- # 자외선차단제 계열
464
  if any(x in inci_text for x in [
465
  "ethylhexyl methoxycinnamate", "octinoxate", "homosalate",
466
  "octocrylene", "benzophenone", "oxybenzone",
@@ -472,7 +543,6 @@ def evaluate_one_country(country, material, llm):
472
  "UV filter sunscreen maximum concentration annex UV filters"
473
  )
474
 
475
- # 색소 계열
476
  if any(x in inci_text for x in [
477
  "ci ", "iron oxides", "titanium dioxide", "ultramarines",
478
  "mica", "carbon black"
@@ -481,7 +551,6 @@ def evaluate_one_country(country, material, llm):
481
  "colorant colouring agent CI permitted colorant restriction"
482
  )
483
 
484
- # 산 / 박피 계열
485
  if any(x in inci_text for x in [
486
  "glycolic acid", "lactic acid", "salicylic acid",
487
  "mandelic acid", "citric acid", "gluconolactone",
@@ -491,7 +560,6 @@ def evaluate_one_country(country, material, llm):
491
  "acid exfoliant AHA BHA maximum concentration pH restriction"
492
  )
493
 
494
- # 정유 / 식물추출물 계열
495
  if any(x in inci_text for x in [
496
  "essential oil", "leaf oil", "peel oil", "melaleuca",
497
  "tea tree", "citrus", "lavender", "eucalyptus",
@@ -502,10 +570,10 @@ def evaluate_one_country(country, material, llm):
502
  )
503
 
504
  search_text = f"""
505
- 원료명: {trade_name}
 
506
  구성성분: {' / '.join(inci_list)}
507
- 원료 투입량: {amount_value}
508
- 최종 제품 내 성분 함량들: {' / '.join(final_amounts)}
509
  규제군 힌트: {' / '.join(regulatory_hints)}
510
  전체 엑셀 정보: {group_records}
511
  """
@@ -518,24 +586,24 @@ def evaluate_one_country(country, material, llm):
518
 
519
  아래 원료를 "{country}" 규제 기준으로 검토해.
520
 
521
- [원료명]
522
- {trade_name}
523
 
524
- [원료 투입량 (%)]
525
- {amount_value}
526
 
527
  [구성 성분 목록]
528
  {inci_list}
529
 
530
- [최종 제품 내 구성 성분 함량 목록]
531
  {final_amounts}
532
 
 
 
 
533
  [규제군 검색 힌트]
534
  {regulatory_hints}
535
 
536
- [엑셀 그룹 전체 정보]
537
- {group_records}
538
-
539
  [검색된 {country} 규제 원문]
540
  {context}
541
 
@@ -551,57 +619,43 @@ def evaluate_one_country(country, material, llm):
551
  - "규제명", "총량 계산", "한도 이내" 같은 placeholder 문구를 절대 쓰지 마.
552
  - 실제 규제군명, 실제 핵심 성분명, 실제 총량, 실제 한도를 쓸 수 있을 때만 구체적으로 작성해.
553
  - 다른 성분의 규제를 분석 대상 성분에 잘못 적용하지 마.
 
554
 
555
  규제군 판단 가이드:
556
  1. 레티노이드 / 비타민A 계열
557
  - Retinol, Retinyl Palmitate, Retinal, Retinoate류는 같은 비타민A/레티노이드 규제군으로 검토한다.
558
  - 같은 규제군 성분이 여러 개 있으면 최종 제품 내 함량 기준으로 합산한다.
559
  - 가능하면 "총 Retinol" 또는 "총 비타민A 환산량" 형태로 계산식을 적는다.
560
- - 예시 형식:
561
  비타민A 규제 / 총 Retinol 0.1002%(=0.0002+0.100), 한도 0.3% RE 이내(통과)
562
 
563
  2. 향료 알레르겐 계열
564
- - Citral, Limonene, Linalool, Geraniol, Citronellol, Eugenol 등은 향료 알레르겐 표시/한도/표시기준 여부를 확인한다.
565
- - leave-on / rinse-off 기준이 있으면 제품 유형 정보가 필요한지 판단한다.
566
- - 예시 형식:
567
  향료 알레르겐 / 표시기준 해당 여부 확인 필요
568
- 향료 알레르겐 / 함량 기준 이내(통과)
569
 
570
  3. 보존제 계열
571
- - Phenoxyethanol, Paraben류, MIT/CMIT, Chlorphenesin, Benzoic Acid, Sorbic Acid 등은 보존제 규제로 검토한다.
572
- - 단일 한도 또는 혼합 한도가 있으면 최종 제품 내 함량과 비교한다.
573
- - 예시 형식:
574
  보존제 규제 / Phenoxyethanol 0.8%, 한도 1.0% 이내(통과)
575
- 보존제 규제 / 사용 조건 확인 필요
576
 
577
  4. 자외선차단제 계열
578
  - UV filter로 등재된 성분은 자외선차단제 성분 규제로 검토한다.
579
- - 최대 배합한도, 사용 조건, nano 여부 등이 있으면 반영한다.
580
- - 예시 형식:
581
  UV filter 규제 / 성분명 3.0%, 한도 10% 이내(통과)
582
 
583
  5. 색소 계열
584
  - CI 번호, Iron Oxides, Titanium Dioxide, Carbon Black 등은 색소 규제 여부를 확인한다.
585
- - 허용 색소인지, 사용 부위 제한이 있는지 확인한다.
586
- - 예시 형식:
587
- 색소 규제 / 허용 색소 여부 확인 필요
588
 
589
  6. 산 / 박피 성분
590
  - AHA/BHA/PHA, Salicylic Acid, Glycolic Acid 등은 농도와 pH 조건을 함께 본다.
591
- - pH 정보가 없으면 확인 필요로 판단한다.
592
- - 예시 형식:
593
- AHA 규제 / Glycolic Acid 5%, pH 조건 확인 필요
594
 
595
  7. 식물추출물 / 정유류
596
  - Essential oil, Citrus oil, Tea tree oil 등은 향료 알레르겐, 광독성, 제한 성분 포함 가능성을 검토한다.
597
- - 실제 규제 성분이 확인되지 않으면 제한 없음으로 작성한다.
598
- - 예시 형식:
599
- 제한 없음 (통과)
600
- 향료 알레르겐 가능성 / 세부 알레르겐 함량 확인 필요
601
 
602
  결과 작성 규칙:
603
  1. 관련 규제가 없으면 결과는 반드시 "제한 없음 (통과)" 로 작성한다.
604
- 2. 규제가 ��고 한도 이내이면 아래처럼 구체적으로 작성한다.
605
  "{{규제군명}} / {{성분명 또는 총량}} {{함량}}%, 한도 {{기준치}} {{단위}} 이내(통과)"
606
  3. 여러 성분 합산이 필요하면 계산식을 반드시 포함한다.
607
  예: 총 Retinol 0.1002%(=0.0002+0.100)
@@ -618,14 +672,6 @@ def evaluate_one_country(country, material, llm):
618
  결과: 비타민A 규제 / 총 Retinol 0.1002%(=0.0002+0.100), 한도 0.3% RE 이내(통과)
619
  비고: -
620
 
621
- 대표 INCI: Phenoxyethanol
622
- 결과: 보존제 규제 / Phenoxyethanol 0.8%, 한도 1.0% 이내(통과)
623
- 비고: -
624
-
625
- 대표 INCI: Citral
626
- 결과: 향료 알레르겐 / 표시기준 해당 여부 확인 필요
627
- 비고: leave-on / rinse-off 및 최종 함량 확인 필요
628
-
629
  대표 INCI: Aqua
630
  결과: 제한 없음 (통과)
631
  비고: -
@@ -667,9 +713,9 @@ def evaluate_one_country(country, material, llm):
667
 
668
 
669
  # =========================
670
- # 엑셀 스타일
671
  # =========================
672
- def style_excel(path, selected_countries):
673
  wb = load_workbook(path)
674
  ws = wb.active
675
 
@@ -686,13 +732,25 @@ def style_excel(path, selected_countries):
686
  red_font = Font(color="FF0000", bold=True)
687
 
688
  headers = [c.value for c in ws[1]]
689
- country_display_cols = []
 
 
 
 
 
 
 
 
 
 
 
690
 
691
  for country in selected_countries:
692
  col_name = display_country(country)
693
  if col_name in headers:
694
- country_display_cols.append(headers.index(col_name) + 1)
695
 
 
696
  for row in range(1, ws.max_row + 1):
697
  for col in range(1, ws.max_column + 1):
698
  cell = ws.cell(row=row, column=col)
@@ -703,37 +761,62 @@ def style_excel(path, selected_countries):
703
  cell.fill = header_fill
704
  cell.font = Font(bold=True)
705
 
706
- elif col in country_display_cols:
707
- value = str(cell.value or "")
708
-
709
- if any(k in value for k in ["부적합", "금지", "초과"]):
710
- cell.fill = red_fill
711
- cell.font = red_font
712
 
713
- elif (
714
- "확인 필요" in value
715
- or ("규제" in value and "제한 없음" not in value)
716
- ):
717
- cell.fill = yellow_fill
718
- cell.font = red_font
 
 
 
 
 
 
 
 
 
 
 
 
 
 
719
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720
  for col_cells in ws.columns:
721
- max_len = 0
722
  col_letter = col_cells[0].column_letter
723
  col_idx = col_cells[0].column
724
 
725
- for cell in col_cells:
726
- if cell.value:
727
- max_len = max(max_len, len(str(cell.value)))
728
-
729
  if col_idx == 1:
730
  ws.column_dimensions[col_letter].width = 6
731
  elif col_idx in [2, 3]:
 
 
732
  ws.column_dimensions[col_letter].width = 28
733
- elif col_idx == 4:
734
- ws.column_dimensions[col_letter].width = 12
735
  else:
736
- ws.column_dimensions[col_letter].width = min(max(max_len + 2, 16), 55)
737
 
738
  ws.freeze_panes = "A2"
739
  wb.save(path)
@@ -762,39 +845,70 @@ def process(countries, file):
762
  )
763
 
764
  output_rows = []
 
765
 
766
  for material in grouped_materials:
767
- row_data = {
768
- "NO": material["NO"],
769
- "Trade name": material["Trade name"],
770
- "INCI": material["INCI_list"][0] if material["INCI_list"] else "-",
771
- "함량 (%)": material["Amount"]
772
- }
773
 
 
 
 
 
 
 
 
 
 
774
  note_list = []
775
 
776
  for country in countries:
777
  country_result = evaluate_one_country(country, material, llm)
778
  col_name = display_country(country)
779
-
780
- row_data[col_name] = country_result["결과"]
781
-
782
- representative = country_result.get("대표 INCI", "-")
783
- if representative and representative != "-":
784
- row_data["INCI"] = representative
785
 
786
  note = safe_str(country_result.get("비고", "-"))
787
  if note and note != "-":
788
  note_list.append(f"{col_name}: {note}")
789
 
790
- row_data["비고"] = " / ".join(note_list) if note_list else "-"
791
 
792
- output_rows.append(row_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
793
 
794
  result_df = pd.DataFrame(output_rows)
795
 
796
  country_cols = [display_country(c) for c in countries]
797
- final_cols = ["NO", "Trade name", "INCI", "함량 (%)"] + country_cols + ["비고"]
 
 
 
 
 
 
 
 
 
798
  result_df = result_df[final_cols]
799
 
800
  safe_country_name = "_".join([
@@ -805,7 +919,7 @@ def process(countries, file):
805
  out_path = f"screening_result_{safe_country_name}.xlsx"
806
 
807
  result_df.to_excel(out_path, index=False)
808
- style_excel(out_path, countries)
809
 
810
  return result_df, out_path, "✅ 분석 완료"
811
 
 
86
  return str(value).strip()
87
 
88
 
89
+ def format_amount(value):
90
+ if pd.isna(value):
91
+ return ""
92
+
93
+ try:
94
+ f = float(value)
95
+ if f.is_integer():
96
+ return str(int(f))
97
+ return str(f).rstrip("0").rstrip(".")
98
+ except Exception:
99
+ return str(value).strip()
100
+
101
+
102
  def get_country_folders():
103
  exclude = [
104
  ".git",
 
129
 
130
 
131
  # =========================
132
+ # 컬럼 자동 인식
133
  # =========================
134
+ def find_best_col(df, keywords, default_index=None, exclude_cols=None):
135
  exclude_cols = exclude_cols or []
136
  scores = []
137
 
 
140
  continue
141
 
142
  header = str(col).lower()
143
+ values = df[col].dropna().astype(str).str.strip()
144
+ sample = " ".join(values.head(50).tolist()).lower()
145
+
146
  score = 0
147
 
148
  for kw in keywords:
149
  if kw.lower() in header:
150
+ score += 20
151
 
152
+ if any(x in sample for x in [
 
 
 
153
  "aqua", "water", "glycerin", "retinol", "niacinamide",
154
  "extract", "acid", "lecithin", "palmitate", "hexanediol",
155
  "triglyceride", "arginine", "crosspolymer", "squalane",
156
+ "butylene glycol", "caprylic", "ceramide", "phenoxyethanol",
157
+ "citral", "linalool", "limonene"
158
  ]):
159
  if any(k in keywords for k in ["inci", "ingredient", "성분", "전성분", "구성"]):
160
+ score += 8
161
 
162
  scores.append((score, idx, col))
163
 
 
172
  return df.columns[0]
173
 
174
 
175
+ def find_numeric_col(df, keywords, default_index=None, exclude_cols=None, prefer_many_values=True):
176
+ exclude_cols = exclude_cols or []
177
+ candidates = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
  for idx, col in enumerate(df.columns):
180
+ if col in exclude_cols:
181
  continue
182
 
183
  header = str(col).lower()
 
 
 
 
184
  values = df[col].dropna()
185
 
186
  if values.empty:
 
194
  continue
195
 
196
  score = 0
 
 
 
 
 
197
 
198
+ for kw in keywords:
199
+ if kw.lower() in header:
200
+ score += 20
201
+
202
+ candidates.append({
203
  "col": col,
204
  "idx": idx,
205
+ "score": score,
206
  "count": count,
207
+ "non_null": len(values)
 
208
  })
209
 
210
+ if not candidates:
211
+ if default_index is not None and len(df.columns) > default_index:
212
+ return df.columns[default_index]
213
+ return None
214
 
215
+ if prefer_many_values:
216
+ candidates = sorted(
217
+ candidates,
218
+ key=lambda x: (x["score"], x["non_null"], x["idx"]),
 
219
  reverse=True
220
+ )
221
+ else:
222
+ candidates = sorted(
223
+ candidates,
224
+ key=lambda x: (x["score"], -x["non_null"], -x["idx"]),
225
+ reverse=True
226
+ )
227
 
228
+ return candidates[0]["col"]
 
 
 
 
229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
+ def find_main_columns(df):
232
+ """
233
+ 기대 출력 형태:
234
+ NO / Trade name(국문) / Trade name(영문) / 한글 성분명 / INCI Name /
235
+ Contents(w/w %) / In formula(w/w %)
236
+ """
237
+
238
+ no_col = find_best_col(
239
+ df,
240
+ ["no", "번호", "순번"],
241
+ default_index=0
242
+ )
243
+
244
+ trade_ko_col = find_best_col(
245
+ df,
246
+ ["trade name(국문)", "trade name 국문", "국문", "원료명", "상품명"],
247
+ default_index=1,
248
+ exclude_cols=[no_col]
249
+ )
250
+
251
+ trade_en_col = find_best_col(
252
+ df,
253
+ ["trade name(영문)", "trade name 영문", "영문", "trade name", "trade", "raw material", "material"],
254
+ default_index=2 if len(df.columns) > 2 else 1,
255
+ exclude_cols=[no_col, trade_ko_col]
256
+ )
257
+
258
+ korean_ing_col = find_best_col(
259
+ df,
260
+ ["한글 성분명", "국문 성분명", "한글성분명", "korean", "국문inci"],
261
+ default_index=3 if len(df.columns) > 3 else None,
262
+ exclude_cols=[no_col, trade_ko_col, trade_en_col]
263
+ )
264
+
265
+ inci_col = find_best_col(
266
+ df,
267
+ ["inci name", "inci", "ingredient", "성분", "전성분", "구성"],
268
+ default_index=4 if len(df.columns) > 4 else 2,
269
+ exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col]
270
+ )
271
+
272
+ contents_col = find_numeric_col(
273
+ df,
274
+ ["contents", "content", "원료 내", "원료내", "함유량", "조성비"],
275
+ default_index=5 if len(df.columns) > 5 else None,
276
+ exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col],
277
+ prefer_many_values=True
278
+ )
279
+
280
+ formula_col = find_numeric_col(
281
+ df,
282
+ ["in formula", "formula", "처방", "최종", "제품 내", "제품내", "배합량", "함량"],
283
+ default_index=6 if len(df.columns) > 6 else None,
284
+ exclude_cols=[no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col],
285
+ prefer_many_values=True
286
+ )
287
+
288
+ # Contents와 In formula가 같은 컬럼으로 잡히면 다른 숫자 컬럼을 보조로 찾음
289
+ if contents_col == formula_col:
290
+ numeric_cols = []
291
+ for col in df.columns:
292
+ if col in [no_col, trade_ko_col, trade_en_col, korean_ing_col, inci_col]:
293
+ continue
294
+ values = df[col].dropna()
295
+ if values.empty:
296
+ continue
297
+ count = max(values.apply(is_numeric_like).sum(), pd.to_numeric(values, errors="coerce").notna().sum())
298
+ if count > 0:
299
+ numeric_cols.append(col)
300
+
301
+ if len(numeric_cols) >= 2:
302
+ contents_col = numeric_cols[-2]
303
+ formula_col = numeric_cols[-1]
304
+
305
+ return {
306
+ "no_col": no_col,
307
+ "trade_ko_col": trade_ko_col,
308
+ "trade_en_col": trade_en_col,
309
+ "korean_ing_col": korean_ing_col,
310
+ "inci_col": inci_col,
311
+ "contents_col": contents_col,
312
+ "formula_col": formula_col,
313
+ }
314
 
315
 
316
  # =========================
 
371
 
372
 
373
  # =========================
374
+ # 원료 그룹화 + 구성 성분 행 보존
375
  # =========================
376
  def make_grouped_materials(df):
377
+ cols = find_main_columns(df)
378
 
379
+ no_col = cols["no_col"]
380
+ trade_ko_col = cols["trade_ko_col"]
381
+ trade_en_col = cols["trade_en_col"]
382
+ korean_ing_col = cols["korean_ing_col"]
383
+ inci_col = cols["inci_col"]
384
+ contents_col = cols["contents_col"]
385
+ formula_col = cols["formula_col"]
386
 
387
+ df = df.copy()
 
 
 
 
388
 
389
+ for col in [no_col, trade_ko_col, trade_en_col]:
390
+ if col and col in df.columns:
391
+ df[col] = df[col].ffill()
392
 
393
+ group_keys = [no_col, trade_ko_col, trade_en_col]
394
+ group_keys = [c for c in group_keys if c in df.columns]
395
 
396
  grouped_materials = []
397
 
398
  for key, group in df.groupby(group_keys, dropna=True, sort=False):
399
+ if not isinstance(key, tuple):
400
+ key = (key,)
 
 
 
 
401
 
402
+ no_value = format_no(key[0]) if len(key) > 0 else ""
403
+ trade_ko = safe_str(key[1]) if len(key) > 1 else ""
404
+ trade_en = safe_str(key[2]) if len(key) > 2 else trade_ko
 
405
 
406
+ if not trade_ko and not trade_en:
407
+ continue
 
 
408
 
409
+ components = []
410
  inci_list = []
411
  final_amounts = []
412
 
413
  for _, row in group.iterrows():
414
+ korean_ing = safe_str(row.get(korean_ing_col, "")) if korean_ing_col in row else ""
415
+ inci_name = safe_str(row.get(inci_col, "")) if inci_col in row else ""
416
 
417
+ contents_value = ""
418
+ if contents_col and contents_col in row:
419
+ contents_value = format_amount(row.get(contents_col))
420
+
421
+ formula_value = ""
422
+ if formula_col and formula_col in row:
423
+ formula_value = format_amount(row.get(formula_col))
424
+
425
+ if not inci_name and not korean_ing:
426
+ continue
427
+
428
+ components.append({
429
+ "한글 성분명": korean_ing,
430
+ "INCI Name": inci_name,
431
+ "Contents(w/w %)": contents_value,
432
+ "In formula(w/w %)": formula_value,
433
+ })
434
+
435
+ if inci_name:
436
  inci_list.append(inci_name)
437
 
438
+ if formula_value:
439
+ final_amounts.append(f"{inci_name}: {formula_value}")
 
 
440
 
441
  inci_list = list(dict.fromkeys(inci_list))
442
 
443
  grouped_materials.append({
444
  "NO": no_value,
445
+ "Trade name(국문)": trade_ko,
446
+ "Trade name(영문)": trade_en,
447
  "INCI_list": inci_list,
448
+ "Components": components,
449
  "Final_amounts": final_amounts,
450
  "Group_records": group.to_dict(orient="records")
451
  })
 
479
 
480
 
481
  # =========================
482
+ # 국가별 규제 판단
483
  # =========================
484
  def evaluate_one_country(country, material, llm):
485
  db = build_database(country)
 
491
  "비고": "-"
492
  }
493
 
494
+ trade_ko = material["Trade name(국문)"]
495
+ trade_en = material["Trade name(영문)"]
496
  inci_list = material["INCI_list"]
497
+ components = material["Components"]
498
  final_amounts = material["Final_amounts"]
499
  group_records = material["Group_records"]
500
 
 
502
 
503
  regulatory_hints = []
504
 
 
505
  if any(x in inci_text for x in [
506
  "retinol", "retinyl", "retinal", "retinoate",
507
  "hydroxypinacolone retinoate", "vitamin a"
 
510
  "retinol retinyl palmitate retinal retinoid vitamin A retinol equivalent RE"
511
  )
512
 
 
513
  if any(x in inci_text for x in [
514
  "citral", "limonene", "linalool", "geraniol", "citronellol",
515
  "eugenol", "coumarin", "benzyl alcohol", "benzyl salicylate",
 
521
  "fragrance allergen perfume allergen labelling threshold leave-on rinse-off"
522
  )
523
 
 
524
  if any(x in inci_text for x in [
525
  "phenoxyethanol", "ethylhexylglycerin", "chlorphenesin",
526
  "methylisothiazolinone", "methylchloroisothiazolinone",
 
532
  "preservative maximum concentration leave-on rinse-off allowed preservative"
533
  )
534
 
 
535
  if any(x in inci_text for x in [
536
  "ethylhexyl methoxycinnamate", "octinoxate", "homosalate",
537
  "octocrylene", "benzophenone", "oxybenzone",
 
543
  "UV filter sunscreen maximum concentration annex UV filters"
544
  )
545
 
 
546
  if any(x in inci_text for x in [
547
  "ci ", "iron oxides", "titanium dioxide", "ultramarines",
548
  "mica", "carbon black"
 
551
  "colorant colouring agent CI permitted colorant restriction"
552
  )
553
 
 
554
  if any(x in inci_text for x in [
555
  "glycolic acid", "lactic acid", "salicylic acid",
556
  "mandelic acid", "citric acid", "gluconolactone",
 
560
  "acid exfoliant AHA BHA maximum concentration pH restriction"
561
  )
562
 
 
563
  if any(x in inci_text for x in [
564
  "essential oil", "leaf oil", "peel oil", "melaleuca",
565
  "tea tree", "citrus", "lavender", "eucalyptus",
 
570
  )
571
 
572
  search_text = f"""
573
+ 원료명 국문: {trade_ko}
574
+ 원료명 영문: {trade_en}
575
  구성성분: {' / '.join(inci_list)}
576
+ 구성성분별 최종 제품 내 함량: {' / '.join(final_amounts)}
 
577
  규제군 힌트: {' / '.join(regulatory_hints)}
578
  전체 엑셀 정보: {group_records}
579
  """
 
586
 
587
  아래 원료를 "{country}" 규제 기준으로 검토해.
588
 
589
+ [원료명 국문]
590
+ {trade_ko}
591
 
592
+ [원료명 영문]
593
+ {trade_en}
594
 
595
  [구성 성분 목록]
596
  {inci_list}
597
 
598
+ [구성 성분별 최종 제품 내 함량]
599
  {final_amounts}
600
 
601
+ [구성 성분 상세 테이블]
602
+ {components}
603
+
604
  [규제군 검색 힌트]
605
  {regulatory_hints}
606
 
 
 
 
607
  [검색된 {country} 규제 원문]
608
  {context}
609
 
 
619
  - "규제명", "총량 계산", "한도 이내" 같은 placeholder 문구를 절대 쓰지 마.
620
  - 실제 규제군명, 실제 핵심 성분명, 실제 총량, 실제 한도를 쓸 수 있을 때만 구체적으로 작성해.
621
  - 다른 성분의 규제를 분석 대상 성분에 잘못 적용하지 마.
622
+ - 규제 판단은 구성 성분별 "In formula(w/w %)" 값을 기준으로 해.
623
 
624
  규제군 판단 가이드:
625
  1. 레티노이드 / 비타민A 계열
626
  - Retinol, Retinyl Palmitate, Retinal, Retinoate류는 같은 비타민A/레티노이드 규제군으로 검토한다.
627
  - 같은 규제군 성분이 여러 개 있으면 최종 제품 내 함량 기준으로 합산한다.
628
  - 가능하면 "총 Retinol" 또는 "총 비타민A 환산량" 형태로 계산식을 적는다.
629
+ - 예시:
630
  비타민A 규제 / 총 Retinol 0.1002%(=0.0002+0.100), 한도 0.3% RE 이내(통과)
631
 
632
  2. 향료 알레르겐 계열
633
+ - Citral, Limonene, Linalool, Geraniol 등은 향료 알레르겐 표시/한도/표시기준 여부를 확인한다.
634
+ - 예시:
 
635
  향료 알레르겐 / 표시기준 해당 여부 확인 필요
 
636
 
637
  3. 보존제 계열
638
+ - Phenoxyethanol, Paraben류, MIT/CMIT, Chlorphenesin, Benzoic Acid 등은 보존제 규제로 검토한다.
639
+ - 예시:
 
640
  보존제 규제 / Phenoxyethanol 0.8%, 한도 1.0% 이내(통과)
 
641
 
642
  4. 자외선차단제 계열
643
  - UV filter로 등재된 성분은 자외선차단제 성분 규제로 검토한다.
644
+ - 예시:
 
645
  UV filter 규제 / 성분명 3.0%, 한도 10% 이내(통과)
646
 
647
  5. 색소 계열
648
  - CI 번호, Iron Oxides, Titanium Dioxide, Carbon Black 등은 색소 규제 여부를 확인한다.
 
 
 
649
 
650
  6. 산 / 박피 성분
651
  - AHA/BHA/PHA, Salicylic Acid, Glycolic Acid 등은 농도와 pH 조건을 함께 본다.
 
 
 
652
 
653
  7. 식물추출물 / 정유류
654
  - Essential oil, Citrus oil, Tea tree oil 등은 향료 알레르겐, 광독성, 제한 성분 포함 가능성을 검토한다.
 
 
 
 
655
 
656
  결과 작성 규칙:
657
  1. 관련 규제가 없으면 결과는 반드시 "제한 없음 (통과)" 로 작성한다.
658
+ 2. 규제가 있고 한도 이내이면:
659
  "{{규제군명}} / {{성분명 또는 총량}} {{함량}}%, 한도 {{기준치}} {{단위}} 이내(통과)"
660
  3. 여러 성분 합산이 필요하면 계산식을 반드시 포함한다.
661
  예: 총 Retinol 0.1002%(=0.0002+0.100)
 
672
  결과: 비타민A 규제 / 총 Retinol 0.1002%(=0.0002+0.100), 한도 0.3% RE 이내(통과)
673
  비고: -
674
 
 
 
 
 
 
 
 
 
675
  대표 INCI: Aqua
676
  결과: 제한 없음 (통과)
677
  비고: -
 
713
 
714
 
715
  # =========================
716
+ # 엑셀 스타일 및 병합
717
  # =========================
718
+ def style_excel(path, selected_countries, merge_ranges):
719
  wb = load_workbook(path)
720
  ws = wb.active
721
 
 
732
  red_font = Font(color="FF0000", bold=True)
733
 
734
  headers = [c.value for c in ws[1]]
735
+
736
+ merge_cols = []
737
+ for name in ["NO", "Trade name(국문)", "Trade name(영문"]:
738
+ if name in headers:
739
+ merge_cols.append(headers.index(name) + 1)
740
+
741
+ # 오타 방지용
742
+ for name in ["NO", "Trade name(국문)", "Trade name(영문)", "비고"]:
743
+ if name in headers:
744
+ col_idx = headers.index(name) + 1
745
+ if col_idx not in merge_cols:
746
+ merge_cols.append(col_idx)
747
 
748
  for country in selected_countries:
749
  col_name = display_country(country)
750
  if col_name in headers:
751
+ merge_cols.append(headers.index(col_name) + 1)
752
 
753
+ # 기본 스타일
754
  for row in range(1, ws.max_row + 1):
755
  for col in range(1, ws.max_column + 1):
756
  cell = ws.cell(row=row, column=col)
 
761
  cell.fill = header_fill
762
  cell.font = Font(bold=True)
763
 
764
+ # 국가 컬럼 색상
765
+ country_cols = []
766
+ for country in selected_countries:
767
+ col_name = display_country(country)
768
+ if col_name in headers:
769
+ country_cols.append(headers.index(col_name) + 1)
770
 
771
+ for row in range(2, ws.max_row + 1):
772
+ for col in country_cols:
773
+ cell = ws.cell(row=row, column=col)
774
+ value = str(cell.value or "")
775
+
776
+ if any(k in value for k in ["부적합", "금지", "초과"]):
777
+ cell.fill = red_fill
778
+ cell.font = red_font
779
+
780
+ elif (
781
+ "확인 필요" in value
782
+ or ("규제" in value and "제한 없음" not in value)
783
+ ):
784
+ cell.fill = yellow_fill
785
+ cell.font = red_font
786
+
787
+ # 그룹 병합
788
+ for start_row, end_row in merge_ranges:
789
+ if end_row <= start_row:
790
+ continue
791
 
792
+ for col in merge_cols:
793
+ try:
794
+ ws.merge_cells(
795
+ start_row=start_row,
796
+ start_column=col,
797
+ end_row=end_row,
798
+ end_column=col
799
+ )
800
+ top_cell = ws.cell(row=start_row, column=col)
801
+ top_cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
802
+ except Exception:
803
+ pass
804
+
805
+ # 열 너비
806
  for col_cells in ws.columns:
 
807
  col_letter = col_cells[0].column_letter
808
  col_idx = col_cells[0].column
809
 
 
 
 
 
810
  if col_idx == 1:
811
  ws.column_dimensions[col_letter].width = 6
812
  elif col_idx in [2, 3]:
813
+ ws.column_dimensions[col_letter].width = 26
814
+ elif col_idx in [4, 5]:
815
  ws.column_dimensions[col_letter].width = 28
816
+ elif col_idx in [6, 7]:
817
+ ws.column_dimensions[col_letter].width = 13
818
  else:
819
+ ws.column_dimensions[col_letter].width = 34
820
 
821
  ws.freeze_panes = "A2"
822
  wb.save(path)
 
845
  )
846
 
847
  output_rows = []
848
+ merge_ranges = []
849
 
850
  for material in grouped_materials:
851
+ components = material["Components"]
 
 
 
 
 
852
 
853
+ if not components:
854
+ components = [{
855
+ "한글 성분명": "",
856
+ "INCI Name": material["INCI_list"][0] if material["INCI_list"] else "-",
857
+ "Contents(w/w %)": "",
858
+ "In formula(w/w %)": ""
859
+ }]
860
+
861
+ country_results = {}
862
  note_list = []
863
 
864
  for country in countries:
865
  country_result = evaluate_one_country(country, material, llm)
866
  col_name = display_country(country)
867
+ country_results[col_name] = country_result["결과"]
 
 
 
 
 
868
 
869
  note = safe_str(country_result.get("비고", "-"))
870
  if note and note != "-":
871
  note_list.append(f"{col_name}: {note}")
872
 
873
+ start_excel_row = len(output_rows) + 2
874
 
875
+ for idx, comp in enumerate(components):
876
+ is_first = idx == 0
877
+
878
+ row_data = {
879
+ "NO": material["NO"] if is_first else "",
880
+ "Trade name(국문)": material["Trade name(국문)"] if is_first else "",
881
+ "Trade name(영문)": material["Trade name(영문)"] if is_first else "",
882
+ "한글 성분명": comp["한글 성분명"],
883
+ "INCI Name": comp["INCI Name"],
884
+ "Contents\n(w/w %)": comp["Contents(w/w %)"],
885
+ "In formula\n(w/w %)": comp["In formula(w/w %)"],
886
+ }
887
+
888
+ for country in countries:
889
+ col_name = display_country(country)
890
+ row_data[col_name] = country_results.get(col_name, "") if is_first else ""
891
+
892
+ row_data["비고"] = " / ".join(note_list) if (is_first and note_list) else ("-" if is_first else "")
893
+
894
+ output_rows.append(row_data)
895
+
896
+ end_excel_row = len(output_rows) + 1
897
+ merge_ranges.append((start_excel_row, end_excel_row))
898
 
899
  result_df = pd.DataFrame(output_rows)
900
 
901
  country_cols = [display_country(c) for c in countries]
902
+ final_cols = [
903
+ "NO",
904
+ "Trade name(국문)",
905
+ "Trade name(영문)",
906
+ "한글 성분명",
907
+ "INCI Name",
908
+ "Contents\n(w/w %)",
909
+ "In formula\n(w/w %)",
910
+ ] + country_cols + ["비고"]
911
+
912
  result_df = result_df[final_cols]
913
 
914
  safe_country_name = "_".join([
 
919
  out_path = f"screening_result_{safe_country_name}.xlsx"
920
 
921
  result_df.to_excel(out_path, index=False)
922
+ style_excel(out_path, countries, merge_ranges)
923
 
924
  return result_df, out_path, "✅ 분석 완료"
925