jin2li commited on
Commit
c2bdd5c
ยท
verified ยท
1 Parent(s): 57081d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -324
app.py CHANGED
@@ -1,11 +1,12 @@
1
  import os
2
  import re
 
3
  import pandas as pd
4
  import pdfplumber
5
  import gradio as gr
6
 
7
  from openpyxl import load_workbook
8
- from openpyxl.styles import PatternFill, Font, Alignment
9
  from langchain_openai import OpenAIEmbeddings, ChatOpenAI
10
  from langchain_community.vectorstores import FAISS
11
  from langchain_text_splitters import RecursiveCharacterTextSplitter
@@ -83,7 +84,6 @@ def extract_number(value):
83
 
84
  return None
85
 
86
-
87
  def is_numeric_like(value):
88
  if pd.isna(value):
89
  return False
@@ -103,178 +103,91 @@ def find_main_columns(df):
103
  - amount_col: ์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰
104
  - final_amount_col: ์ตœ์ข… ์ œํ’ˆ ๋‚ด ๊ตฌ์„ฑ ์„ฑ๋ถ„ ํ•จ๋Ÿ‰
105
  """
106
-
107
  n = max(len(df), 1)
108
 
109
- raw_keywords = [
110
- "์›๋ฃŒ", "์›๋ฃŒ๋ช…", "์ƒํ’ˆ", "์ƒํ’ˆ๋ช…", "trade",
111
- "material", "raw", "blend", "๋ณตํ•ฉ"
112
- ]
113
-
114
- ingredient_keywords = [
115
- "์„ฑ๋ถ„", "์ „์„ฑ๋ถ„", "inci", "ingredient",
116
- "composition", "๊ตฌ์„ฑ"
117
- ]
118
-
119
- amount_keywords = [
120
- "ํ•จ๋Ÿ‰", "๋ฐฐํ•ฉ๋Ÿ‰", "๋†๋„", "ํˆฌ์ž…", "์‚ฌ์šฉ๋Ÿ‰",
121
- "content", "amount", "concentration", "%"
122
- ]
123
 
124
  raw_scores = []
125
-
126
  for idx, col in enumerate(df.columns):
127
  values = df[col].dropna().astype(str).str.strip()
128
-
129
- if values.empty:
130
- continue
131
-
132
  numeric_ratio = values.apply(is_numeric_like).mean()
133
-
134
- if numeric_ratio > 0.7:
135
- continue
136
 
137
  header = str(col).lower()
138
  sample_text = " ".join(values.head(30).tolist()).lower()
139
-
140
  non_null_ratio = len(values) / n
141
  unique_ratio = values.nunique() / max(len(values), 1)
142
 
143
  score = 0
144
-
145
- if any(k.lower() in header for k in raw_keywords):
146
- score += 10
147
-
148
- if any(k.lower() in header for k in ingredient_keywords):
149
- score -= 5
150
-
151
- if 0 < non_null_ratio < 0.7:
152
- score += 4
153
-
154
- if unique_ratio < 0.8:
155
- score += 2
156
-
157
- if idx <= 3:
158
- score += 1
159
-
160
- if "โ„ข" in sample_text or "ยฎ" in sample_text:
161
- score += 2
162
 
163
  raw_scores.append((score, col))
164
 
165
- if raw_scores:
166
- raw_col = sorted(raw_scores, reverse=True, key=lambda x: x[0])[0][1]
167
- else:
168
- raw_col = df.columns[0]
169
 
170
  ingredient_scores = []
171
-
172
- known_ingredients = [
173
- "aqua", "water", "glycerin", "retinol", "retinyl",
174
- "retinal", "acid", "extract", "lecithin", "palmitate",
175
- "hexanediol", "caprylic", "triglyceride"
176
- ]
177
 
178
  for idx, col in enumerate(df.columns):
179
- if col == raw_col:
180
- continue
181
-
182
  values = df[col].dropna().astype(str).str.strip()
183
-
184
- if values.empty:
185
- continue
186
-
187
  numeric_ratio = values.apply(is_numeric_like).mean()
188
-
189
- if numeric_ratio > 0.5:
190
- continue
191
 
192
  header = str(col).lower()
193
  sample_text = " ".join(values.head(50).tolist()).lower()
194
  non_null_ratio = len(values) / n
195
 
196
  score = 0
197
-
198
- if any(k.lower() in header for k in ingredient_keywords):
199
- score += 10
200
-
201
- if any(k in sample_text for k in known_ingredients):
202
- score += 5
203
-
204
- if non_null_ratio > 0.5:
205
- score += 3
206
-
207
- if any(k.lower() in header for k in raw_keywords):
208
- score -= 4
209
 
210
  ingredient_scores.append((score, col))
211
 
212
- if ingredient_scores:
213
- ingredient_col = sorted(ingredient_scores, reverse=True, key=lambda x: x[0])[0][1]
214
- else:
215
- ingredient_col = df.columns[1] if len(df.columns) > 1 else raw_col
216
 
217
  numeric_candidates = []
218
-
219
  for idx, col in enumerate(df.columns):
220
- if col in [raw_col, ingredient_col]:
221
- continue
222
-
223
  header = str(col).lower()
224
-
225
- if header in ["no", "๋ฒˆํ˜ธ", "์ˆœ๋ฒˆ", "index", "#"]:
226
- continue
227
 
228
  values = df[col].dropna()
229
-
230
- if values.empty:
231
- continue
232
 
233
  numeric_like_count = values.apply(is_numeric_like).sum()
234
  converted = pd.to_numeric(values, errors="coerce")
235
  numeric_count = converted.notna().sum()
236
-
237
  count = max(numeric_like_count, numeric_count)
238
 
239
- if count <= 0:
240
- continue
241
-
242
  non_null_count = len(values)
243
 
244
  score = 0
 
245
 
246
- if any(k.lower() in header for k in amount_keywords):
247
- score += 5
248
-
249
- numeric_candidates.append({
250
- "col": col,
251
- "idx": idx,
252
- "count": count,
253
- "non_null_count": non_null_count,
254
- "score": score
255
- })
256
 
257
  amount_col = None
258
  final_amount_col = None
259
 
260
  if numeric_candidates:
261
- final_amount_col = sorted(
262
- numeric_candidates,
263
- key=lambda x: (x["non_null_count"], x["idx"]),
264
- reverse=True
265
- )[0]["col"]
266
-
267
- low_fill_candidates = [
268
- c for c in numeric_candidates
269
- if c["col"] != final_amount_col
270
- ]
271
 
272
  if low_fill_candidates:
273
- amount_col = sorted(
274
- low_fill_candidates,
275
- key=lambda x: (x["score"], -x["non_null_count"]),
276
- reverse=True
277
- )[0]["col"]
278
  else:
279
  amount_col = final_amount_col
280
 
@@ -292,36 +205,22 @@ def build_database(country_folders):
292
  country_folders = [country_folders]
293
 
294
  texts = []
295
-
296
- splitter = RecursiveCharacterTextSplitter(
297
- chunk_size=800,
298
- chunk_overlap=100
299
- )
300
 
301
  for folder in country_folders:
302
- if folder == "ํด๋” ์—†์Œ":
303
- continue
304
-
305
- if not os.path.isdir(folder):
306
  continue
307
 
308
- files = [
309
- f for f in os.listdir(folder)
310
- if f.lower().endswith(".pdf")
311
- ]
312
 
313
  for filename in files:
314
  try:
315
  with pdfplumber.open(os.path.join(folder, filename)) as pdf:
316
  for page in pdf.pages:
317
  text = page.extract_text()
318
-
319
  if text:
320
- chunks = splitter.split_text(
321
- f"[๊ตญ๊ฐ€/ํด๋”: {folder}] [์ถœ์ฒ˜: {filename}] {text}"
322
- )
323
  texts.extend(chunks)
324
-
325
  except Exception as e:
326
  print(f"PDF ์˜ค๋ฅ˜: {folder}/{filename} / {e}")
327
 
@@ -333,89 +232,66 @@ def build_database(country_folders):
333
 
334
 
335
  # =========================
336
- # GPT ์‘๋‹ต ํŒŒ์‹ฑ
337
  # =========================
338
- def parse_response(text):
339
- result = {
340
- "๊ทœ์ œ ๋Œ€์ƒ": "-",
341
- "์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰": "-",
342
- "์ ํ•ฉ ์—ฌ๋ถ€": "ํ™•์ธ ํ•„์š”",
343
- "๋ถ€์ ํ•ฉ ์‚ฌ์œ ": "-",
344
- "๊ทœ์ œ ์ •๋„": "์ •๋ณด ์—†์Œ"
345
- }
346
-
347
- for line in text.splitlines():
348
- line = line.strip()
349
-
350
- if line.startswith("๊ทœ์ œ ๋Œ€์ƒ:"):
351
- result["๊ทœ์ œ ๋Œ€์ƒ"] = line.split(":", 1)[1].strip() or "-"
352
-
353
- elif line.startswith("์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰:"):
354
- result["์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰"] = line.split(":", 1)[1].strip() or "-"
355
-
356
- elif line.startswith("์ ํ•ฉ ์—ฌ๋ถ€:"):
357
- result["์ ํ•ฉ ์—ฌ๋ถ€"] = line.split(":", 1)[1].strip() or "ํ™•์ธ ํ•„์š”"
358
-
359
- elif line.startswith("๋ถ€์ ํ•ฉ ์‚ฌ์œ :"):
360
- result["๋ถ€์ ํ•ฉ ์‚ฌ์œ "] = line.split(":", 1)[1].strip() or "-"
361
-
362
- elif line.startswith("๊ทœ์ œ ์ •๋„:"):
363
- result["๊ทœ์ œ ์ •๋„"] = line.split(":", 1)[1].strip() or "์ •๋ณด ์—†์Œ"
364
-
365
- return result
366
-
367
-
368
- # =========================
369
- # ์—‘์…€ ์Šคํƒ€์ผ
370
- # =========================
371
- def style_excel(path):
372
  wb = load_workbook(path)
373
  ws = wb.active
374
 
375
- red = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
376
- yellow = PatternFill(start_color="FFF2CC", end_color="FFF2CC", fill_type="solid")
377
- header = PatternFill(start_color="D9EAF7", end_color="D9EAF7", fill_type="solid")
378
-
379
- for cell in ws[1]:
380
- cell.fill = header
381
- cell.font = Font(bold=True)
382
- cell.alignment = Alignment(horizontal="center", vertical="center")
383
 
 
 
 
384
  headers = [c.value for c in ws[1]]
385
-
386
- status_col = headers.index("์ ํ•ฉ ์—ฌ๋ถ€") + 1
387
- reg_col = headers.index("๊ทœ์ œ ์ •๋„") + 1
388
-
389
- for row in range(2, ws.max_row + 1):
390
- status = str(ws.cell(row, status_col).value or "")
391
- reg = str(ws.cell(row, reg_col).value or "")
392
-
393
- if "๋ถ€์ ํ•ฉ" in status:
394
- for col in range(1, ws.max_column + 1):
395
- ws.cell(row, col).fill = red
396
-
397
- elif (
398
- reg.strip()
399
- and "์ •๋ณด ์—†์Œ" not in reg
400
- and "๊ด€๋ จ ๊ทœ์ œ ์—†์Œ" not in reg
401
- and "๊ทœ์ œ ์—†์Œ" not in reg
402
- and "๊ทœ์ œ ํ™•์ธ๋˜์ง€ ์•Š์Œ" not in reg
403
- and reg.strip() not in ["-", "์—†์Œ"]
404
- ):
405
- for col in range(1, ws.max_column + 1):
406
- ws.cell(row, col).fill = yellow
407
-
 
 
 
 
 
 
 
408
  for col in ws.columns:
409
- max_len = 0
410
  col_letter = col[0].column_letter
411
-
412
- for cell in col:
413
- cell.alignment = Alignment(vertical="top", wrap_text=True)
414
-
415
- if cell.value:
416
- max_len = max(max_len, len(str(cell.value)))
417
-
418
- ws.column_dimensions[col_letter].width = min(max(max_len + 2, 12), 55)
 
 
419
 
420
  ws.freeze_panes = "A2"
421
  wb.save(path)
@@ -432,165 +308,114 @@ def process(country_folders, file):
432
  return None, "โŒ ์Šคํฌ๋ฆฌ๋‹ ๊ตญ๊ฐ€๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”."
433
 
434
  db = build_database(country_folders)
435
-
436
  if not db:
437
  return None, "โŒ ์„ ํƒํ•œ ๊ตญ๊ฐ€ ํด๋”์— PDF๊ฐ€ ์—†๊ฑฐ๋‚˜ ์ฝ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."
438
 
439
  df = pd.read_excel(file.name)
440
-
441
  raw_col, ingredient_col, amount_col, final_amount_col = find_main_columns(df)
442
-
443
  df[raw_col] = df[raw_col].ffill()
444
 
445
- llm = ChatOpenAI(
446
- model="gpt-4o-mini",
447
- temperature=0
448
  )
449
 
450
  output_rows = []
 
 
451
 
452
  for raw_material, group in df.groupby(raw_col, dropna=True):
453
  raw_material = str(raw_material).strip()
454
-
455
  if not raw_material or raw_material.lower() == "nan":
456
  continue
457
 
458
- group_records = group.to_dict(orient="records")
459
-
460
  ingredients = []
461
  final_amounts = []
462
 
463
  for _, row in group.iterrows():
464
  ing = str(row.get(ingredient_col, "")).strip()
465
-
466
  if ing and ing.lower() != "nan":
467
  ingredients.append(ing)
468
 
469
  if final_amount_col:
470
  val = row.get(final_amount_col)
471
-
472
  if not pd.isna(val):
473
  final_amounts.append(str(val))
474
 
475
  raw_amount = "-"
476
-
477
  if amount_col:
478
  raw_amount_values = group[amount_col].dropna().tolist()
479
-
480
  if raw_amount_values:
481
  raw_amount = raw_amount_values[0]
482
 
483
- search_text = f"""
484
- ์›๋ฃŒ๋ช…: {raw_material}
485
- ๊ตฌ์„ฑ์„ฑ๋ถ„: {' / '.join(ingredients)}
486
- ์›๋ฃŒํˆฌ์ž…๋Ÿ‰: {raw_amount}
487
- ์ตœ์ข…ํ•จ๋Ÿ‰๋“ค: {' / '.join(final_amounts)}
488
- ์ „์ฒด์ •๋ณด: {group_records}
489
- """
490
-
491
- docs = db.similarity_search(search_text, k=6)
492
  context = "\n".join([d.page_content for d in docs])
493
 
494
  prompt = f"""
495
- ๋„ˆ๋Š” ํ™”์žฅํ’ˆ ์ „์„ฑ๋ถ„ ๊ทœ์ œ ์Šคํฌ๋ฆฌ๋‹ ์ „๋ฌธ๊ฐ€์•ผ.
496
-
497
- ๋„ˆ์˜ ์—ญํ• :
498
- ์—‘์…€์˜ ํ•œ ํ–‰๋งŒ ๋ณด๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ํ•˜๋‚˜์˜ ๋ณตํ•ฉ ์›๋ฃŒ ๊ทธ๋ฃน ์ „์ฒด๋ฅผ ๋ณด๊ณ  ๊ทœ์ œ ์ ํ•ฉ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•œ๋‹ค.
499
-
500
- [๋ถ„์„ ๋Œ€์ƒ ์›๋ฃŒ๋ช…]
501
- {raw_material}
502
-
503
- [์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰]
504
- {raw_amount}
505
-
506
- [๊ตฌ์„ฑ ์„ฑ๋ถ„ ๋ชฉ๋ก]
507
- {ingredients}
508
-
509
- [์ตœ์ข… ์ œํ’ˆ ๋‚ด ๊ตฌ์„ฑ ์„ฑ๋ถ„ ํ•จ๋Ÿ‰ ๋ชฉ๋ก]
510
- {final_amounts}
511
-
512
- [๊ทธ๋ฃน ์ „์ฒด ์—‘์…€ ์ •๋ณด]
513
- {group_records}
514
-
515
- [๊ฒ€์ƒ‰๋œ ๊ทœ์ œ ์›๋ฌธ]
516
- {context}
517
-
518
- ๋ฐ˜๋“œ์‹œ ์•„๋ž˜ ํ˜•์‹์œผ๋กœ๋งŒ ๋‹ต๋ณ€ํ•ด.
519
-
520
- ๊ทœ์ œ ๋Œ€์ƒ:
521
- ์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰:
522
- ์ ํ•ฉ ์—ฌ๋ถ€:
523
- ๋ถ€์ ํ•ฉ ์‚ฌ์œ :
524
- ๊ทœ์ œ ์ •๋„:
525
-
526
- ํŒ๋‹จ ์›์น™:
527
- 1. ์ด ์›๋ฃŒ๊ฐ€ ๋ณตํ•ฉ ์›๋ฃŒ๋ผ๋ฉด ๊ตฌ์„ฑ ์„ฑ๋ถ„ ์ „์ฒด๋ฅผ ๊ธฐ์ค€์œผ๋กœ ํŒ๋‹จํ•œ๋‹ค.
528
- 2. ๊ทœ์ œ ๋Œ€์ƒ์€ ์›๋ฃŒ๋ช… ์ž์ฒด๊ฐ€ ์•„๋‹ˆ๋ผ ์‹ค์ œ ๊ตฌ์„ฑ ์„ฑ๋ถ„ ๋˜๋Š” ๊ทœ์ œ ์›๋ฌธ์— ๋“ฑ์žฌ๋œ ์„ฑ๋ถ„๋ช…์ด๋‹ค.
529
- 3. ๊ฐ™์€ ๊ทœ์ œ๊ตฐ์— ์†ํ•˜๋Š” ์„ฑ๋ถ„์ด ์—ฌ๋Ÿฌ ๊ฐœ ์žˆ์œผ๋ฉด ์ตœ์ข… ์ œํ’ˆ ๋‚ด ํ•จ๋Ÿ‰ ๊ธฐ์ค€์œผ๋กœ ํ•ฉ์‚ฐํ•œ๋‹ค.
530
- 4. ์ œํ’ˆ ํ•จ๋Ÿ‰, ์›๋ฃŒ ํ•จ๋Ÿ‰, ์›๋ฃŒ ๋‚ด ํ•จ๋Ÿ‰์ด ๊ตฌ๋ถ„๋˜์–ด ์žˆ์œผ๋ฉด ์ตœ์ข… ์ œํ’ˆ ๋‚ด ์‹ค์ œ ํ•จ๋Ÿ‰ ๊ธฐ์ค€์œผ๋กœ ํŒ๋‹จํ•œ๋‹ค.
531
- 5. ๊ทœ์ œ ์›๋ฌธ์— ๊ธˆ์ง€ ์„ฑ๋ถ„์œผ๋กœ ๋ช…ํ™•ํžˆ ํ™•์ธ๋˜๋ฉด '๋ถ€์ ํ•ฉ'์œผ๋กœ ํŒ๋‹จํ•œ๋‹ค.
532
- 6. ๊ทœ์ œ ์›๋ฌธ์— ์ตœ๋Œ€ ์‚ฌ์šฉ ํ•œ๋„ ๋˜๋Š” ์ œํ•œ ์กฐ๊ฑด์ด ์žˆ๊ณ , ์ œํ’ˆ ๋‚ด ์‹ค์ œ ํ•จ๋Ÿ‰์ด ๊ธฐ์ค€์„ ์ดˆ๊ณผํ•˜๋ฉด '๋ถ€์ ํ•ฉ'์œผ๋กœ ํŒ๋‹จํ•œ๋‹ค.
533
- 7. ๊ทœ์ œ ์›๋ฌธ์— ์ตœ๋Œ€ ์‚ฌ์šฉ ํ•œ๋„ ๋˜๋Š” ์ œํ•œ ์กฐ๊ฑด์ด ์žˆ๊ณ , ์ œํ’ˆ ๋‚ด ์‹ค์ œ ํ•จ๋Ÿ‰์ด ๊ธฐ์ค€ ์ด๋‚ด์ด๋ฉด 'ํ†ต๊ณผ' ๋˜๋Š” '์ ํ•ฉ'์œผ๋กœ ํŒ๋‹จํ•œ๋‹ค.
534
- 8. ๊ทœ์ œ๋Š” ์žˆ์œผ๋‚˜ ์ œํ’ˆ ์œ ํ˜•, ์‚ฌ์šฉ ๋ถ€์œ„, leave-on/rinse-off ์—ฌ๋ถ€, ํ•จ๋Ÿ‰ ๋‹จ์œ„ ๋“ฑ์ด ๋ถ€์กฑํ•ด ํŒ๋‹จ์ด ์–ด๋ ค์šฐ๋ฉด 'ํ™•์ธ ํ•„์š”'๋กœ ํŒ๋‹จํ•œ๋‹ค.
535
- 9. ๊ฒ€์ƒ‰๋œ ๊ทœ์ œ ์›๋ฌธ์— ํ•ด๋‹น ์›๋ฃŒ์˜ ๊ตฌ์„ฑ ์„ฑ๋ถ„, ๋™์˜์–ด, ๊ทœ์ œ๊ตฐ์ด ์ง์ ‘ ๊ด€๋ จ๋˜์ง€ ์•Š์œผ๋ฉด ๋‹ค๋ฅธ ์„ฑ๋ถ„ ๊ทœ์ œ๋ฅผ ์ ์šฉํ•˜์ง€ ๋ง๊ณ  '์ •๋ณด ์—†์Œ'์œผ๋กœ ๋‹ต๋ณ€ํ•œ๋‹ค.
536
- 10. ๋ถ€์ ํ•ฉ ์‚ฌ์œ ๋Š” ๋ถ€์ ํ•ฉ์ผ ๋•Œ๋งŒ ์ž‘์„ฑํ•˜๊ณ , ์•„๋‹ˆ๋ฉด '-'๋กœ ์ž‘์„ฑํ•œ๋‹ค.
537
- 11. ๊ทœ์ œ ์ •๋„์—๋Š” ๊ทœ์ œ๊ตฐ, ์ด๋Ÿ‰ ๊ณ„์‚ฐ, ํ•œ๋„, ํŒ๋‹จ ๊ฒฐ๊ณผ๋ฅผ ์งง๊ฒŒ ์ž‘์„ฑํ•œ๋‹ค.
538
- 12. ๋‹ต๋ณ€์€ ํ•œ ์›๋ฃŒ๋‹น ํ•œ ์ค„ ๊ฒฐ๊ณผ๋กœ ์š”์•ฝํ•œ๋‹ค.
539
-
540
- ๋‹ต๋ณ€ ์˜ˆ์‹œ:
541
- ๊ทœ์ œ ๋Œ€์ƒ: Retinol ํฌํ•จ ๋ณตํ•ฉ
542
- ์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰: 0.200
543
- ์ ํ•ฉ ์—ฌ๋ถ€: ํ†ต๊ณผ
544
- ๋ถ€์ ํ•ฉ ์‚ฌ์œ : -
545
- ๊ทœ์ œ ์ •๋„: ๋น„ํƒ€๋ฏผA ๊ทœ์ œ / ์ด Retinol 0.1002%(=0.0002+0.100), ํ•œ๋„ 0.3% RE ์ด๋‚ด(ํ†ต๊ณผ)
546
-
547
- ๋‹ต๋ณ€ ์˜ˆ์‹œ:
548
- ๊ทœ์ œ ๋Œ€์ƒ: -
549
- ์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰: 1.000
550
- ์ ํ•ฉ ์—ฌ๋ถ€: ์ •๋ณด ์—†์Œ
551
- ๋ถ€์ ํ•ฉ ์‚ฌ์œ : -
552
- ๊ทœ์ œ ์ •๋„: ๊ด€๋ จ ๊ทœ์ œ ํ™•์ธ๋˜์ง€ ์•Š์Œ
553
- """
554
 
555
  try:
556
  response = llm.invoke(prompt).content
557
- parsed = parse_response(response)
558
-
559
  except Exception as e:
560
- parsed = {
561
- "๊ทœ์ œ ๋Œ€์ƒ": "-",
562
- "์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰": str(raw_amount),
563
- "์ ํ•ฉ ์—ฌ๋ถ€": "ํ™•์ธ ํ•„์š”",
564
- "๋ถ€์ ํ•ฉ ์‚ฌ์œ ": str(e),
565
- "๊ทœ์ œ ์ •๋„": "์—๋Ÿฌ"
566
- }
567
-
568
- output_rows.append({
569
- "์›๋ฃŒ๋ช…": raw_material,
570
- "๊ทœ์ œ ๋Œ€์ƒ": parsed["๊ทœ์ œ ๋Œ€์ƒ"],
571
- "์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰": parsed["์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰"] if parsed["์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰"] != "-" else raw_amount,
572
- "์ ํ•ฉ ์—ฌ๋ถ€": parsed["์ ํ•ฉ ์—ฌ๋ถ€"],
573
- "๋ถ€์ ํ•ฉ ์‚ฌ์œ ": parsed["๋ถ€์ ํ•ฉ ์‚ฌ์œ "],
574
- "๊ทœ์ œ ์ •๋„": parsed["๊ทœ์ œ ์ •๋„"]
575
- })
576
 
577
- result_df = pd.DataFrame(output_rows)
 
 
 
 
 
 
 
578
 
579
- result_df = result_df[
580
- ["์›๋ฃŒ๋ช…", "๊ทœ์ œ ๋Œ€์ƒ", "์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰", "์ ํ•ฉ ์—ฌ๋ถ€", "๋ถ€์ ํ•ฉ ์‚ฌ์œ ", "๊ทœ์ œ ์ •๋„"]
581
- ]
582
 
583
- if isinstance(country_folders, list):
584
- country_name = "_".join(country_folders)
585
- else:
586
- country_name = str(country_folders)
587
 
588
- safe_country_name = re.sub(r"[^a-zA-Z0-9๊ฐ€-ํžฃ_-]", "_", country_name)
589
 
590
- out = f"result_{safe_country_name}.xlsx"
 
 
591
 
 
 
 
 
 
592
  result_df.to_excel(out, index=False)
593
- style_excel(out)
594
 
595
  return result_df, out
596
 
@@ -600,7 +425,7 @@ def process(country_folders, file):
600
  # =========================
601
  with gr.Blocks() as demo:
602
  gr.Markdown("# ๐ŸŒ reBom Regulatory Screening AI")
603
- gr.Markdown("### ๊ธ€๋กœ๋ฒŒ ํ™”์žฅํ’ˆ ๊ทœ์ œ ๊ธฐ๋ฐ˜ ์ „์„ฑ๋ถ„ ์Šคํฌ๋ฆฌ๋‹")
604
 
605
  country = gr.CheckboxGroup(
606
  choices=get_country_folders(),
@@ -646,7 +471,6 @@ with gr.Blocks() as demo:
646
  outputs=[df_out, file_out]
647
  )
648
 
649
-
650
  demo.launch(
651
  ssr_mode=False,
652
  css=custom_css
 
1
  import os
2
  import re
3
+ import json
4
  import pandas as pd
5
  import pdfplumber
6
  import gradio as gr
7
 
8
  from openpyxl import load_workbook
9
+ from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
10
  from langchain_openai import OpenAIEmbeddings, ChatOpenAI
11
  from langchain_community.vectorstores import FAISS
12
  from langchain_text_splitters import RecursiveCharacterTextSplitter
 
84
 
85
  return None
86
 
 
87
  def is_numeric_like(value):
88
  if pd.isna(value):
89
  return False
 
103
  - amount_col: ์›๋ฃŒ ํˆฌ์ž…๋Ÿ‰
104
  - final_amount_col: ์ตœ์ข… ์ œํ’ˆ ๋‚ด ๊ตฌ์„ฑ ์„ฑ๋ถ„ ํ•จ๋Ÿ‰
105
  """
 
106
  n = max(len(df), 1)
107
 
108
+ raw_keywords = ["์›๋ฃŒ", "์›๋ฃŒ๋ช…", "์ƒํ’ˆ", "์ƒํ’ˆ๋ช…", "trade", "material", "raw", "blend", "๋ณตํ•ฉ"]
109
+ ingredient_keywords = ["์„ฑ๋ถ„", "์ „์„ฑ๋ถ„", "inci", "ingredient", "composition", "๊ตฌ์„ฑ"]
110
+ amount_keywords = ["ํ•จ๋Ÿ‰", "๋ฐฐํ•ฉ๋Ÿ‰", "๋†๋„", "ํˆฌ์ž…", "์‚ฌ์šฉ๋Ÿ‰", "content", "amount", "concentration", "%"]
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  raw_scores = []
 
113
  for idx, col in enumerate(df.columns):
114
  values = df[col].dropna().astype(str).str.strip()
115
+ if values.empty: continue
 
 
 
116
  numeric_ratio = values.apply(is_numeric_like).mean()
117
+ if numeric_ratio > 0.7: continue
 
 
118
 
119
  header = str(col).lower()
120
  sample_text = " ".join(values.head(30).tolist()).lower()
 
121
  non_null_ratio = len(values) / n
122
  unique_ratio = values.nunique() / max(len(values), 1)
123
 
124
  score = 0
125
+ if any(k.lower() in header for k in raw_keywords): score += 10
126
+ if any(k.lower() in header for k in ingredient_keywords): score -= 5
127
+ if 0 < non_null_ratio < 0.7: score += 4
128
+ if unique_ratio < 0.8: score += 2
129
+ if idx <= 3: score += 1
130
+ if "โ„ข" in sample_text or "ยฎ" in sample_text: score += 2
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  raw_scores.append((score, col))
133
 
134
+ raw_col = sorted(raw_scores, reverse=True, key=lambda x: x[0])[0][1] if raw_scores else df.columns[0]
 
 
 
135
 
136
  ingredient_scores = []
137
+ known_ingredients = ["aqua", "water", "glycerin", "retinol", "retinyl", "retinal", "acid", "extract", "lecithin", "palmitate", "hexanediol", "caprylic", "triglyceride"]
 
 
 
 
 
138
 
139
  for idx, col in enumerate(df.columns):
140
+ if col == raw_col: continue
 
 
141
  values = df[col].dropna().astype(str).str.strip()
142
+ if values.empty: continue
 
 
 
143
  numeric_ratio = values.apply(is_numeric_like).mean()
144
+ if numeric_ratio > 0.5: continue
 
 
145
 
146
  header = str(col).lower()
147
  sample_text = " ".join(values.head(50).tolist()).lower()
148
  non_null_ratio = len(values) / n
149
 
150
  score = 0
151
+ if any(k.lower() in header for k in ingredient_keywords): score += 10
152
+ if any(k in sample_text for k in known_ingredients): score += 5
153
+ if non_null_ratio > 0.5: score += 3
154
+ if any(k.lower() in header for k in raw_keywords): score -= 4
 
 
 
 
 
 
 
 
155
 
156
  ingredient_scores.append((score, col))
157
 
158
+ ingredient_col = sorted(ingredient_scores, reverse=True, key=lambda x: x[0])[0][1] if ingredient_scores else (df.columns[1] if len(df.columns) > 1 else raw_col)
 
 
 
159
 
160
  numeric_candidates = []
 
161
  for idx, col in enumerate(df.columns):
162
+ if col in [raw_col, ingredient_col]: continue
 
 
163
  header = str(col).lower()
164
+ if header in ["no", "๋ฒˆํ˜ธ", "์ˆœ๋ฒˆ", "index", "#"]: continue
 
 
165
 
166
  values = df[col].dropna()
167
+ if values.empty: continue
 
 
168
 
169
  numeric_like_count = values.apply(is_numeric_like).sum()
170
  converted = pd.to_numeric(values, errors="coerce")
171
  numeric_count = converted.notna().sum()
 
172
  count = max(numeric_like_count, numeric_count)
173
 
174
+ if count <= 0: continue
 
 
175
  non_null_count = len(values)
176
 
177
  score = 0
178
+ if any(k.lower() in header for k in amount_keywords): score += 5
179
 
180
+ numeric_candidates.append({"col": col, "idx": idx, "count": count, "non_null_count": non_null_count, "score": score})
 
 
 
 
 
 
 
 
 
181
 
182
  amount_col = None
183
  final_amount_col = None
184
 
185
  if numeric_candidates:
186
+ final_amount_col = sorted(numeric_candidates, key=lambda x: (x["non_null_count"], x["idx"]), reverse=True)[0]["col"]
187
+ low_fill_candidates = [c for c in numeric_candidates if c["col"] != final_amount_col]
 
 
 
 
 
 
 
 
188
 
189
  if low_fill_candidates:
190
+ amount_col = sorted(low_fill_candidates, key=lambda x: (x["score"], -x["non_null_count"]), reverse=True)[0]["col"]
 
 
 
 
191
  else:
192
  amount_col = final_amount_col
193
 
 
205
  country_folders = [country_folders]
206
 
207
  texts = []
208
+ splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
 
 
 
 
209
 
210
  for folder in country_folders:
211
+ if folder == "ํด๋” ์—†์Œ" or not os.path.isdir(folder):
 
 
 
212
  continue
213
 
214
+ files = [f for f in os.listdir(folder) if f.lower().endswith(".pdf")]
 
 
 
215
 
216
  for filename in files:
217
  try:
218
  with pdfplumber.open(os.path.join(folder, filename)) as pdf:
219
  for page in pdf.pages:
220
  text = page.extract_text()
 
221
  if text:
222
+ chunks = splitter.split_text(f"[๊ตญ๊ฐ€: {folder}] [์ถœ์ฒ˜: {filename}] {text}")
 
 
223
  texts.extend(chunks)
 
224
  except Exception as e:
225
  print(f"PDF ์˜ค๋ฅ˜: {folder}/{filename} / {e}")
226
 
 
232
 
233
 
234
  # =========================
235
+ # ์‚ฌ์ง„ ์–‘์‹ ๊ธฐ๋ฐ˜ ์—‘์…€ ์Šคํƒ€์ผ๋ง
236
  # =========================
237
+ def style_excel(path, country_folders):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  wb = load_workbook(path)
239
  ws = wb.active
240
 
241
+ # ํ…Œ๋‘๋ฆฌ ์Šคํƒ€์ผ ์„ค์ • (๋ชจ๋“  ์…€์— ์–‡์€ ์„ )
242
+ thin_border = Border(
243
+ left=Side(style='thin', color='000000'),
244
+ right=Side(style='thin', color='000000'),
245
+ top=Side(style='thin', color='000000'),
246
+ bottom=Side(style='thin', color='000000')
247
+ )
 
248
 
249
+ # ํ—ค๋” ์Šคํƒ€์ผ (์˜…์€ ํšŒ์ƒ‰)
250
+ header_fill = PatternFill(start_color="D9D9D9", end_color="D9D9D9", fill_type="solid")
251
+
252
  headers = [c.value for c in ws[1]]
253
+ country_cols = [headers.index(c) + 1 for c in country_folders if c in headers]
254
+
255
+ red_font = Font(color="FF0000", bold=True)
256
+ black_font = Font(color="000000")
257
+ header_font = Font(bold=True, color="000000")
258
+
259
+ # ์ „์ฒด ๋ฐ์ดํ„ฐ ์˜์—ญ ์Šคํƒ€์ผ๋ง
260
+ for row in range(1, ws.max_row + 1):
261
+ for col in range(1, ws.max_column + 1):
262
+ cell = ws.cell(row, col)
263
+
264
+ # ์ค‘์•™ ์ •๋ ฌ ๋ฐ ์ž๋™ ์ค„๋ฐ”๊ฟˆ
265
+ cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
266
+ # ๋ชจ๋“  ์…€์— ํ…Œ๋‘๋ฆฌ ์ ์šฉ
267
+ cell.border = thin_border
268
+
269
+ # ์ฒซ ๋ฒˆ์งธ ์ค„(ํ—ค๋”) ์„ค์ •
270
+ if row == 1:
271
+ cell.fill = header_fill
272
+ cell.font = header_font
273
+ else:
274
+ # ๊ตญ๊ฐ€ ๊ทœ์ œ ๊ฒฐ๊ณผ ์ปฌ๋Ÿผ์—์„œ ํŠน์ • ํ‚ค์›Œ๋“œ ๊ฐ์ง€ ์‹œ ๊ธ€์ž๋ฅผ ๋นจ๊ฐ„์ƒ‰์œผ๋กœ ๋ณ€๊ฒฝ
275
+ if col in country_cols:
276
+ val = str(cell.value or "")
277
+ if "๊ทœ์ œ" in val or "๋ถ€์ ํ•ฉ" in val or "ํ™•์ธ ํ•„์š”" in val:
278
+ cell.font = red_font
279
+ else:
280
+ cell.font = black_font
281
+
282
+ # ์ปฌ๋Ÿผ ๋„ˆ๋น„ ์ตœ์ ํ™”
283
  for col in ws.columns:
 
284
  col_letter = col[0].column_letter
285
+ if col_letter == "A": # NO
286
+ ws.column_dimensions[col_letter].width = 5
287
+ elif col_letter in ["B", "C"]: # Trade name, INCI
288
+ ws.column_dimensions[col_letter].width = 28
289
+ elif col_letter == "D": # ํ•จ๋Ÿ‰
290
+ ws.column_dimensions[col_letter].width = 12
291
+ elif col_letter == ws.cell(1, ws.max_column).column_letter: # ๋งˆ์ง€๋ง‰ '๋น„๊ณ ' ์ปฌ๋Ÿผ
292
+ ws.column_dimensions[col_letter].width = 15
293
+ else: # ๊ตญ๊ฐ€๋“ค
294
+ ws.column_dimensions[col_letter].width = 30
295
 
296
  ws.freeze_panes = "A2"
297
  wb.save(path)
 
308
  return None, "โŒ ์Šคํฌ๋ฆฌ๋‹ ๊ตญ๊ฐ€๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”."
309
 
310
  db = build_database(country_folders)
 
311
  if not db:
312
  return None, "โŒ ์„ ํƒํ•œ ๊ตญ๊ฐ€ ํด๋”์— PDF๊ฐ€ ์—†๊ฑฐ๋‚˜ ์ฝ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."
313
 
314
  df = pd.read_excel(file.name)
 
315
  raw_col, ingredient_col, amount_col, final_amount_col = find_main_columns(df)
 
316
  df[raw_col] = df[raw_col].ffill()
317
 
318
+ # JSON ์ถœ๋ ฅ์„ ๊ฐ•์ œํ•˜๊ธฐ ์œ„ํ•ด json_object ๋ชจ๋“œ ํ™œ์„ฑํ™” (์•ˆ์ •์„ฑ ๊ฐ•ํ™”)
319
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0).bind(
320
+ response_format={"type": "json_object"}
321
  )
322
 
323
  output_rows = []
324
+ idx = 1
325
+ countries_str = ", ".join(country_folders)
326
 
327
  for raw_material, group in df.groupby(raw_col, dropna=True):
328
  raw_material = str(raw_material).strip()
 
329
  if not raw_material or raw_material.lower() == "nan":
330
  continue
331
 
 
 
332
  ingredients = []
333
  final_amounts = []
334
 
335
  for _, row in group.iterrows():
336
  ing = str(row.get(ingredient_col, "")).strip()
 
337
  if ing and ing.lower() != "nan":
338
  ingredients.append(ing)
339
 
340
  if final_amount_col:
341
  val = row.get(final_amount_col)
 
342
  if not pd.isna(val):
343
  final_amounts.append(str(val))
344
 
345
  raw_amount = "-"
 
346
  if amount_col:
347
  raw_amount_values = group[amount_col].dropna().tolist()
 
348
  if raw_amount_values:
349
  raw_amount = raw_amount_values[0]
350
 
351
+ search_text = f"์›๋ฃŒ๋ช…: {raw_material} / ๊ตฌ์„ฑ์„ฑ๋ถ„: {' / '.join(ingredients)}"
352
+ docs = db.similarity_search(search_text, k=8)
 
 
 
 
 
 
 
353
  context = "\n".join([d.page_content for d in docs])
354
 
355
  prompt = f"""
356
+ ๋„ˆ๋Š” ๊ธ€๋กœ๋ฒŒ ํ™”์žฅํ’ˆ ์„ฑ๋ถ„ ๊ทœ์ œ ์ „๋ฌธ๊ฐ€์•ผ.
357
+ ์ œ๊ณต๋œ ๊ทœ์ œ ์›๋ฌธ์„ ๋ฐ”ํƒ•์œผ๋กœ ์•„๋ž˜ [๋Œ€์ƒ ๊ตญ๊ฐ€] ๊ฐ๊ฐ์— ๋Œ€ํ•ด ์ ํ•ฉ ์—ฌ๋ถ€๋ฅผ ํ‰๊ฐ€ํ•ด.
358
+
359
+ [๋Œ€์ƒ ๊ตญ๊ฐ€]
360
+ {countries_str}
361
+
362
+ [๋ถ„์„ ๋Œ€์ƒ ์›๋ฃŒ ์ •๋ณด]
363
+ - Trade name: {raw_material}
364
+ - INCI (๊ตฌ์„ฑ ์„ฑ๋ถ„): {', '.join(ingredients)}
365
+ - ํ•จ๋Ÿ‰ (%): {raw_amount}
366
+ - ์ตœ์ข… ํ•จ๋Ÿ‰ ๋ชฉ๋ก: {', '.join(final_amounts) if final_amounts else '-'}
367
+
368
+ [๊ฒ€์ƒ‰๋œ ๊ทœ์ œ ์›๋ฌธ]
369
+ {context}
370
+
371
+ [์ž‘์„ฑ ์›์น™]
372
+ 1. ์›๋ฌธ์— ํ•ด๋‹น ์„ฑ๋ถ„์˜ ๊ทœ์ œ๊ฐ€ ์—†๊ฑฐ๋‚˜ ๋ฌด๊ด€ํ•˜๋ฉด "์ œํ•œ ์—†์Œ (ํ†ต๊ณผ)" ๋˜๋Š” "ํ†ต๊ณผ"๋กœ ์ž‘์„ฑ.
373
+ 2. ๊ทœ์ œ๊ฐ€ ์กด์žฌํ•˜์ง€๋งŒ ์ œํ’ˆ ๋‚ด ํ•œ๋„ ์ด๋‚ด์—ฌ์„œ ์•ˆ์ „ํ•˜๋‹ค๋ฉด ๊ตฌ์ฒด์  ์‚ฌ์œ  ํฌํ•จ (์˜ˆ: "๋น„ํƒ€๋ฏผA ๊ทœ์ œ / ์ด Retinol 0.1002%, ํ•œ๋„ 0.3% RE ์ด๋‚ด(ํ†ต๊ณผ)").
374
+ 3. ๊ธˆ์ง€ ์„ฑ๋ถ„์ด๊ฑฐ๋‚˜ ํ•œ๋„๋ฅผ ์ดˆ๊ณผํ•˜๋ฉด "๋ถ€์ ํ•ฉ / [์‚ฌ์œ ]".
375
+ 4. ํŒ๋‹จ ๋ณด๋ฅ˜ ์ƒํ™ฉ์ด๋ฉด "ํ™•์ธ ํ•„์š” / [์‚ฌ์œ ]".
376
+
377
+ ๋ฐ˜๋“œ์‹œ ์•„๋ž˜ JSON ํ˜•์‹์œผ๋กœ๋งŒ ๋‹ต๋ณ€ํ•ด.
378
+ {{
379
+ "{country_folders[0]}": "๊ฒฐ๊ณผ๊ฐ’",
380
+ ...
381
+ }}
382
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
 
384
  try:
385
  response = llm.invoke(prompt).content
386
+ parsed_result = json.loads(response)
 
387
  except Exception as e:
388
+ parsed_result = {c: "์—๋Ÿฌ (ํ™•์ธ ํ•„์š”)" for c in country_folders}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
 
390
+ # ๊ฒฐ๊ณผ Row ์ƒ์„ฑ
391
+ row_data = {
392
+ "NO": idx,
393
+ "Trade name": raw_material,
394
+ "INCI": "\n".join(ingredients) if ingredients else "-",
395
+ "ํ•จ๋Ÿ‰ (%)": raw_amount,
396
+ "๋น„๊ณ ": "" # ๋นˆ ๋น„๊ณ ๋ž€ ์ถ”๊ฐ€
397
+ }
398
 
399
+ # ๊ตญ๊ฐ€๋ณ„ ์ปฌ๋Ÿผ ๋ฐ์ดํ„ฐ ๋งคํ•‘
400
+ for c in country_folders:
401
+ row_data[c] = parsed_result.get(c, "ํ™•์ธ ํ•„์š”")
402
 
403
+ output_rows.append(row_data)
404
+ idx += 1
 
 
405
 
406
+ result_df = pd.DataFrame(output_rows)
407
 
408
+ # ์ปฌ๋Ÿผ ์ˆœ์„œ ๋ณด์žฅ (์ด๋ฏธ์ง€ ์–‘์‹๊ณผ ๋™์ผํ•˜๊ฒŒ)
409
+ columns_order = ["NO", "Trade name", "INCI", "ํ•จ๋Ÿ‰ (%)"] + country_folders + ["๋น„๊ณ "]
410
+ result_df = result_df[[col for col in columns_order if col in result_df.columns]]
411
 
412
+ # ์—‘์…€ ์ €์žฅ
413
+ safe_country_name = "_".join(country_folders) if isinstance(country_folders, list) else str(country_folders)
414
+ safe_country_name = re.sub(r"[^a-zA-Z0-9๊ฐ€-ํžฃ_-]", "_", safe_country_name)
415
+ out = f"result_{safe_country_name}.xlsx"
416
+
417
  result_df.to_excel(out, index=False)
418
+ style_excel(out, country_folders)
419
 
420
  return result_df, out
421
 
 
425
  # =========================
426
  with gr.Blocks() as demo:
427
  gr.Markdown("# ๐ŸŒ reBom Regulatory Screening AI")
428
+ gr.Markdown("### ๊ธ€๋กœ๋ฒŒ ํ™”์žฅํ’ˆ ๊ทœ์ œ ๊ธฐ๋ฐ˜ ์ „์„ฑ๋ถ„ ์Šคํฌ๋ฆฌ๋‹ (๊ตญ๊ฐ€๋ณ„ ๋ถ„์„)")
429
 
430
  country = gr.CheckboxGroup(
431
  choices=get_country_folders(),
 
471
  outputs=[df_out, file_out]
472
  )
473
 
 
474
  demo.launch(
475
  ssr_mode=False,
476
  css=custom_css