jin2li commited on
Commit
f57aedb
·
verified ·
1 Parent(s): bd37755

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +522 -118
app.py CHANGED
@@ -12,18 +12,46 @@ from langchain_text_splitters import RecursiveCharacterTextSplitter
12
 
13
 
14
  # =========================
15
- # API KEY
16
  # =========================
17
  api_key = os.getenv("OPENAI_API_KEY")
18
  print("✅ KEY OK" if api_key else "❌ KEY 없음")
19
 
20
 
21
  # =========================
22
- # 폴더 목록
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  # =========================
24
  def get_country_folders():
25
  exclude = [".git", ".cache", "__pycache__", ".ipynb_checkpoints"]
26
- folders = [f for f in os.listdir(".") if os.path.isdir(f) and f not in exclude]
 
 
 
27
  return folders if folders else ["폴더 없음"]
28
 
29
 
@@ -33,18 +61,11 @@ def get_country_folders():
33
  def preview_excel(file):
34
  if not file:
35
  return None
36
- return pd.read_excel(file.name)
37
-
38
 
39
- # =========================
40
- # 함량 컬럼 찾기
41
- # =========================
42
- def find_amount_column(df):
43
- keywords = ["함량", "농도", "concentration", "%", "amount"]
44
- for col in df.columns:
45
- if any(k in str(col).lower() for k in keywords):
46
- return col
47
- return None
48
 
49
 
50
  # =========================
@@ -53,36 +74,293 @@ def find_amount_column(df):
53
  def extract_number(value):
54
  if pd.isna(value):
55
  return None
56
- m = re.search(r"(\d+\.?\d*)", str(value))
57
- return float(m.group(1)) if m else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
 
60
  # =========================
61
- # 벡터 DB 생성
62
  # =========================
63
- def build_database(folder):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  texts = []
65
- splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
66
 
67
- files = [f for f in os.listdir(folder) if f.lower().endswith(".pdf")]
 
 
 
68
 
69
- for f in files:
70
- try:
71
- with pdfplumber.open(os.path.join(folder, f)) as pdf:
72
- for page in pdf.pages:
73
- t = page.extract_text()
74
- if t:
75
- texts.extend(splitter.split_text(f"[{f}] {t}"))
76
- except:
77
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
  if not texts:
80
  return None
81
 
82
- return FAISS.from_texts(
83
- texts,
84
- OpenAIEmbeddings(model="text-embedding-3-small")
85
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
 
88
  # =========================
@@ -92,154 +370,280 @@ def style_excel(path):
92
  wb = load_workbook(path)
93
  ws = wb.active
94
 
95
- red = PatternFill(start_color="FFC7CE", fill_type="solid")
96
- yellow = PatternFill(start_color="FFF2CC", fill_type="solid")
 
 
 
 
 
 
97
 
98
  headers = [c.value for c in ws[1]]
99
- s_col = headers.index("적합 여부") + 1
100
- r_col = headers.index("규제 정도") + 1
101
 
102
- for i in range(2, ws.max_row + 1):
103
- status = str(ws.cell(i, s_col).value or "")
104
- reg = str(ws.cell(i, r_col).value or "")
105
 
106
- # 🔴 부적합만 빨간색
 
 
 
 
107
  if "부적합" in status:
108
- for j in range(1, ws.max_column + 1):
109
- ws.cell(i, j).fill = red
110
 
111
- # 🟡 규제 있는 경우만 노란색
112
  elif (
113
  reg.strip()
114
  and "정보 없음" not in reg
115
  and "관련 규제 없음" not in reg
 
 
116
  and reg.strip() not in ["-", "없음"]
117
  ):
118
- for j in range(1, ws.max_column + 1):
119
- ws.cell(i, j).fill = yellow
 
 
 
 
120
 
 
 
 
 
 
 
 
 
 
121
  wb.save(path)
122
 
123
 
124
  # =========================
125
- # 핵심 분석
126
  # =========================
127
- def process(country, file):
 
 
 
 
 
 
 
128
 
129
- db = build_database(country)
130
  if not db:
131
- return None, "PDF 없음"
132
 
133
  df = pd.read_excel(file.name)
134
 
135
- llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
 
 
 
136
 
137
- amount_col = find_amount_column(df)
 
 
 
 
 
 
 
 
 
 
 
138
 
139
- status, reason, reg = [], [], []
140
 
141
- for _, row in df.iterrows():
 
142
 
143
- ing = str(row.iloc[0]).strip()
 
144
 
145
- row_text = " ".join([f"{k}:{v}" for k, v in row.to_dict().items()])
 
146
 
147
- amount = row.get(amount_col) if amount_col else "-"
148
- amount_num = extract_number(amount)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
- # 🔥 검색 강화
151
- search_query = f"{ing} {row_text}"
152
- docs = db.similarity_search(search_query, k=5)
153
  context = "\n".join([d.page_content for d in docs])
154
 
155
- # 🔥 핵심 프롬프트
156
  prompt = f"""
157
  너는 화장품 전성분 규제 스크리닝 전문가야.
158
 
159
- 단순 성분명 검색이 아니라
160
- 엑셀 행 전체를 기반으로 실제 규제 성분을 찾아 판단해.
161
 
162
- [표시명]
163
- {ing}
164
 
165
- [함량]
166
- {amount}
167
 
168
- [엑셀 전체 정보]
169
- {row.to_dict()}
170
 
171
- [규제 원문]
 
 
 
 
 
 
172
  {context}
173
 
174
- 출력 형식:
175
 
 
 
176
  적합 여부:
177
  부적합 사유:
178
  규제 정도:
179
 
180
- 판단 규칙:
181
-
182
- 1. 표시명은 상표명/복합 원료일 수 있으므로 실제 구성 성분을 찾는다
183
- 2. 규제 대상은 실제 성분 기준이다
184
- 3. 같은 규제군이면 함량을 합산한다
185
- 4. 규제 한도와 비교한다
186
- 5. 관련 성분이 없으면 정보 없음
187
- 6. 다른 성분 규제를 절대 적용하지 마
188
- 7. 판단이 애매하면 확인 필요
 
 
 
 
 
 
 
 
 
 
 
189
 
190
- 예시:
191
- 적합 여부: 적합
 
 
192
  부적합 사유: -
193
- 규제 정도: 비타민A 규제 / 총 Retinol 0.1002%(=0.0002+0.100), 한도 0.3% RE 이내
194
  """
195
 
196
  try:
197
- res = llm.invoke(prompt).content
198
- except Exception as e:
199
- res = str(e)
200
-
201
- s, r, g = "", "", ""
202
-
203
- for line in res.splitlines():
204
- if "적합 여부" in line:
205
- s = line.split(":")[-1].strip()
206
- elif "부적합 사유" in line:
207
- r = line.split(":")[-1].strip()
208
- elif "규제 정도" in line:
209
- g = line.split(":")[-1].strip()
210
-
211
- status.append(s or "확인 필요")
212
- reason.append(r or "-")
213
- reg.append(g or "정보 없음")
214
 
215
- df["적합 여부"] = status
216
- df["부적합 사유"] = reason
217
- df["규제 정도"] = reg
218
-
219
- out = f"result_{country}.xlsx"
220
- df.to_excel(out, index=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  style_excel(out)
222
 
223
- return df, out
224
 
225
 
226
  # =========================
227
  # UI
228
  # =========================
229
- with gr.Blocks() as demo:
230
-
231
  gr.Markdown("# 🌍 reBom Regulatory Screening AI")
232
  gr.Markdown("### 글로벌 화장품 규제 기반 전성분 스크리닝")
233
 
234
- country = gr.Dropdown(get_country_folders())
235
- file = gr.File()
 
 
 
 
 
 
 
 
 
 
 
236
 
237
- btn = gr.Button("🚀 분석 시작")
238
 
239
- df_out = gr.Dataframe(wrap=True)
240
- f_out = gr.File()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
 
242
- file.change(preview_excel, file, df_out)
243
- btn.click(process, [country, file], [df_out, f_out])
244
 
245
- demo.launch()
 
12
 
13
 
14
  # =========================
15
+ # API KEY 확인
16
  # =========================
17
  api_key = os.getenv("OPENAI_API_KEY")
18
  print("✅ KEY OK" if api_key else "❌ KEY 없음")
19
 
20
 
21
  # =========================
22
+ # UI CSS
23
+ # =========================
24
+ custom_css = """
25
+ #country_checks .wrap,
26
+ #country_checks .checkbox-group {
27
+ display: flex !important;
28
+ flex-direction: row !important;
29
+ flex-wrap: wrap !important;
30
+ gap: 10px !important;
31
+ }
32
+
33
+ #country_checks label {
34
+ display: inline-flex !important;
35
+ align-items: center !important;
36
+ width: auto !important;
37
+ min-width: 100px !important;
38
+ padding: 8px 12px !important;
39
+ border: 1px solid #555 !important;
40
+ border-radius: 10px !important;
41
+ margin: 4px !important;
42
+ }
43
+ """
44
+
45
+
46
+ # =========================
47
+ # 국가 폴더 목록
48
  # =========================
49
  def get_country_folders():
50
  exclude = [".git", ".cache", "__pycache__", ".ipynb_checkpoints"]
51
+ folders = [
52
+ f for f in os.listdir(".")
53
+ if os.path.isdir(f) and f not in exclude
54
+ ]
55
  return folders if folders else ["폴더 없음"]
56
 
57
 
 
61
  def preview_excel(file):
62
  if not file:
63
  return None
 
 
64
 
65
+ try:
66
+ return pd.read_excel(file.name)
67
+ except Exception as e:
68
+ return pd.DataFrame({"오류": [str(e)]})
 
 
 
 
 
69
 
70
 
71
  # =========================
 
74
  def extract_number(value):
75
  if pd.isna(value):
76
  return None
77
+
78
+ text = str(value).strip().replace(",", ".")
79
+ match = re.search(r"(\d+\.?\d*)", text)
80
+
81
+ if match:
82
+ return float(match.group(1))
83
+
84
+ return None
85
+
86
+
87
+ def is_numeric_like(value):
88
+ if pd.isna(value):
89
+ return False
90
+
91
+ text = str(value).strip().replace(",", ".")
92
+ return bool(re.fullmatch(r"\d+\.?\d*%?", text))
93
 
94
 
95
  # =========================
96
+ # 엑셀 컬럼 자동 추정
97
  # =========================
98
+ def find_main_columns(df):
99
+ """
100
+ 자동 추정:
101
+ - raw_col: 원료명 / 복합 원료명 / 상표 원료명
102
+ - ingredient_col: 구성 성분명
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
+ # 1) 원료명 컬럼 찾기
125
+ raw_scores = []
126
+
127
+ for idx, col in enumerate(df.columns):
128
+ values = df[col].dropna().astype(str).str.strip()
129
+ if values.empty:
130
+ continue
131
+
132
+ numeric_ratio = values.apply(is_numeric_like).mean()
133
+ if numeric_ratio > 0.7:
134
+ continue
135
+
136
+ header = str(col).lower()
137
+ sample_text = " ".join(values.head(30).tolist()).lower()
138
+
139
+ non_null_ratio = len(values) / n
140
+ unique_ratio = values.nunique() / max(len(values), 1)
141
+
142
+ score = 0
143
+
144
+ if any(k.lower() in header for k in raw_keywords):
145
+ score += 10
146
+
147
+ if any(k.lower() in header for k in ingredient_keywords):
148
+ score -= 5
149
+
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
+ # 2) 구성 성분 컬럼 찾기
171
+ ingredient_scores = []
172
+
173
+ known_ingredients = [
174
+ "aqua", "water", "glycerin", "retinol", "retinyl",
175
+ "retinal", "acid", "extract", "lecithin", "palmitate",
176
+ "hexanediol", "caprylic", "triglyceride"
177
+ ]
178
+
179
+ for idx, col in enumerate(df.columns):
180
+ if col == raw_col:
181
+ continue
182
+
183
+ values = df[col].dropna().astype(str).str.strip()
184
+ if values.empty:
185
+ continue
186
+
187
+ numeric_ratio = values.apply(is_numeric_like).mean()
188
+ if numeric_ratio > 0.5:
189
+ continue
190
+
191
+ header = str(col).lower()
192
+ sample_text = " ".join(values.head(50).tolist()).lower()
193
+ non_null_ratio = len(values) / n
194
+
195
+ score = 0
196
+
197
+ if any(k.lower() in header for k in ingredient_keywords):
198
+ score += 10
199
+
200
+ if any(k in sample_text for k in known_ingredients):
201
+ score += 5
202
+
203
+ if non_null_ratio > 0.5:
204
+ score += 3
205
+
206
+ if any(k.lower() in header for k in raw_keywords):
207
+ score -= 4
208
+
209
+ ingredient_scores.append((score, col))
210
+
211
+ if ingredient_scores:
212
+ ingredient_col = sorted(ingredient_scores, reverse=True, key=lambda x: x[0])[0][1]
213
+ else:
214
+ ingredient_col = df.columns[1] if len(df.columns) > 1 else raw_col
215
+
216
+ # 3) 숫자 컬럼 찾기
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
+ # 번호/순번 컬럼 제외
226
+ if header in ["no", "번호", "순번", "index", "#"]:
227
+ continue
228
+
229
+ values = df[col].dropna()
230
+
231
+ if values.empty:
232
+ continue
233
+
234
+ numeric_like_count = values.apply(is_numeric_like).sum()
235
+ converted = pd.to_numeric(values, errors="coerce")
236
+ numeric_count = converted.notna().sum()
237
+
238
+ count = max(numeric_like_count, numeric_count)
239
+
240
+ if count <= 0:
241
+ continue
242
+
243
+ non_null_count = len(values)
244
+
245
+ score = 0
246
+
247
+ if any(k.lower() in header for k in amount_keywords):
248
+ score += 5
249
+
250
+ numeric_candidates.append({
251
+ "col": col,
252
+ "idx": idx,
253
+ "count": count,
254
+ "non_null_count": non_null_count,
255
+ "score": score
256
+ })
257
+
258
+ amount_col = None
259
+ final_amount_col = None
260
+
261
+ if numeric_candidates:
262
+ # 최종 구성 성분 함량은 보통 값이 많이 채워진 숫자 컬럼
263
+ final_amount_col = sorted(
264
+ numeric_candidates,
265
+ key=lambda x: (x["non_null_count"], x["idx"]),
266
+ reverse=True
267
+ )[0]["col"]
268
+
269
+ # 원료 투입량은 보통 병합 셀이라 값이 적게 있음
270
+ low_fill_candidates = [
271
+ c for c in numeric_candidates
272
+ if c["col"] != final_amount_col
273
+ ]
274
+
275
+ if low_fill_candidates:
276
+ amount_col = sorted(
277
+ low_fill_candidates,
278
+ key=lambda x: (x["score"], -x["non_null_count"]),
279
+ reverse=True
280
+ )[0]["col"]
281
+ else:
282
+ amount_col = final_amount_col
283
+
284
+ return raw_col, ingredient_col, amount_col, final_amount_col
285
+
286
+
287
+ # =========================
288
+ # PDF → 벡터 DB 생성
289
+ # =========================
290
+ def build_database(country_folders):
291
+ if not country_folders:
292
+ return None
293
+
294
+ if isinstance(country_folders, str):
295
+ country_folders = [country_folders]
296
+
297
  texts = []
 
298
 
299
+ splitter = RecursiveCharacterTextSplitter(
300
+ chunk_size=800,
301
+ chunk_overlap=100
302
+ )
303
 
304
+ for folder in country_folders:
305
+ if folder == "폴더 없음":
306
+ continue
307
+
308
+ if not os.path.isdir(folder):
309
+ continue
310
+
311
+ files = [
312
+ f for f in os.listdir(folder)
313
+ if f.lower().endswith(".pdf")
314
+ ]
315
+
316
+ for filename in files:
317
+ try:
318
+ with pdfplumber.open(os.path.join(folder, filename)) as pdf:
319
+ for page in pdf.pages:
320
+ text = page.extract_text()
321
+ if text:
322
+ chunks = splitter.split_text(
323
+ f"[국가/폴더: {folder}] [출처: {filename}] {text}"
324
+ )
325
+ texts.extend(chunks)
326
+
327
+ except Exception as e:
328
+ print(f"PDF 오류: {folder}/{filename} / {e}")
329
 
330
  if not texts:
331
  return None
332
 
333
+ embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
334
+ return FAISS.from_texts(texts, embeddings)
335
+
336
+
337
+ # =========================
338
+ # GPT 응답 파싱
339
+ # =========================
340
+ def parse_response(text):
341
+ result = {
342
+ "규제 대상": "-",
343
+ "원료 투입량": "-",
344
+ "적합 여부": "확인 필요",
345
+ "부적합 사유": "-",
346
+ "규제 정도": "정보 없음"
347
+ }
348
+
349
+ for line in text.splitlines():
350
+ line = line.strip()
351
+
352
+ if line.startswith("규제 대상:"):
353
+ result["규제 대상"] = line.split(":", 1)[1].strip() or "-"
354
+ elif line.startswith("원료 투입량:"):
355
+ result["원료 투입량"] = line.split(":", 1)[1].strip() or "-"
356
+ elif line.startswith("적합 여부:"):
357
+ result["적합 여부"] = line.split(":", 1)[1].strip() or "확인 필요"
358
+ elif line.startswith("부적합 사유:"):
359
+ result["부적합 사유"] = line.split(":", 1)[1].strip() or "-"
360
+ elif line.startswith("규제 정도:"):
361
+ result["규제 정도"] = line.split(":", 1)[1].strip() or "정보 없음"
362
+
363
+ return result
364
 
365
 
366
  # =========================
 
370
  wb = load_workbook(path)
371
  ws = wb.active
372
 
373
+ red = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
374
+ yellow = PatternFill(start_color="FFF2CC", end_color="FFF2CC", fill_type="solid")
375
+ header = PatternFill(start_color="D9EAF7", end_color="D9EAF7", fill_type="solid")
376
+
377
+ for cell in ws[1]:
378
+ cell.fill = header
379
+ cell.font = Font(bold=True)
380
+ cell.alignment = Alignment(horizontal="center", vertical="center")
381
 
382
  headers = [c.value for c in ws[1]]
 
 
383
 
384
+ status_col = headers.index("적합 여부") + 1
385
+ reg_col = headers.index("규제 정도") + 1
 
386
 
387
+ for row in range(2, ws.max_row + 1):
388
+ status = str(ws.cell(row, status_col).value or "")
389
+ reg = str(ws.cell(row, reg_col).value or "")
390
+
391
+ # 부적합만 빨간색
392
  if "부적합" in status:
393
+ for col in range(1, ws.max_column + 1):
394
+ ws.cell(row, col).fill = red
395
 
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)
422
 
423
 
424
  # =========================
425
+ # 메인 분석 함수
426
  # =========================
427
+ def process(country_folders, file):
428
+ if not file:
429
+ return None, "❌ 엑셀 파일을 업로드해주세요."
430
+
431
+ if not country_folders:
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
+ # 병합 셀 때문에 비어 있는 원료명을 위 값으로 채움
444
+ df[raw_col] = df[raw_col].ffill()
445
 
446
+ llm = ChatOpenAI(
447
+ model="gpt-4o-mini",
448
+ temperature=0
449
+ )
450
+
451
+ output_rows = []
452
+
453
+ for raw_material, group in df.groupby(raw_col, dropna=True):
454
+ raw_material = str(raw_material).strip()
455
+
456
+ if not raw_material or raw_material.lower() == "nan":
457
+ continue
458
 
459
+ group_records = group.to_dict(orient="records")
460
 
461
+ ingredients = []
462
+ final_amounts = []
463
 
464
+ for _, row in group.iterrows():
465
+ ing = str(row.get(ingredient_col, "")).strip()
466
 
467
+ if ing and ing.lower() != "nan":
468
+ ingredients.append(ing)
469
 
470
+ if final_amount_col:
471
+ val = row.get(final_amount_col)
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
+ if raw_amount_values:
480
+ raw_amount = raw_amount_values[0]
481
+
482
+ search_text = f"""
483
+ 원료명: {raw_material}
484
+ 구성성분: {' / '.join(ingredients)}
485
+ 원료투입량: {raw_amount}
486
+ 최종함량들: {' / '.join(final_amounts)}
487
+ 전체정보: {group_records}
488
+ """
489
 
490
+ docs = db.similarity_search(search_text, k=6)
 
 
491
  context = "\n".join([d.page_content for d in docs])
492
 
 
493
  prompt = f"""
494
  너는 화장품 전성분 규제 스크리닝 전문가야.
495
 
496
+ 너의 역할:
497
+ 엑셀의 한 행만 보는 것이 아니라, 하나의 복합 원료 그룹 전체를 보고 규제 적합 여부를 판단한다.
498
 
499
+ [분석 대상 원료명]
500
+ {raw_material}
501
 
502
+ [원료 투입량]
503
+ {raw_amount}
504
 
505
+ [구성 성분 목록]
506
+ {ingredients}
507
 
508
+ [최종 제품 내 구성 성분 함량 목록]
509
+ {final_amounts}
510
+
511
+ [그룹 전체 엑셀 정보]
512
+ {group_records}
513
+
514
+ [검색된 규제 원문]
515
  {context}
516
 
517
+ 반드시 아래 형식으로만 답변해.
518
 
519
+ 규제 대상:
520
+ 원료 투입량:
521
  적합 여부:
522
  부적합 사유:
523
  규제 정도:
524
 
525
+ 판단 원칙:
526
+ 1. 이 원료가 복합 원료라면 구성 성분 전체를 기준으로 판단한다.
527
+ 2. 규제 대상은 원료명 자체가 아니라 실제 구성 성분 또는 규제 원문에 등재된 성분명이다.
528
+ 3. 같은 규제군에 속하는 성분이 여러 개 있으면 최종 제품 내 함량 기준으로 합산한다.
529
+ 4. 제품 함량, 원료 함량, 원료 내 함량이 구분되어 있으면 최종 제품 내 실제 함량 기준으로 판단한다.
530
+ 5. 규제 원문에 금지 성분으로 명확히 확인되면 '부적합'으로 판단한다.
531
+ 6. 규제 원문에 최대 사용 한도 또는 제한 조건이 있고, 제품 내 실제 함량이 기준을 초과하면 '부적합'으로 판단한다.
532
+ 7. 규제 원문에 최대 사용 한도 또는 제한 조건이 있고, 제품 내 실제 함량이 기준 이내이면 '통과' 또는 '적합'으로 판단한다.
533
+ 8. 규제는 있으나 제품 유형, 사용 부위, leave-on/rinse-off 여부, 함량 단위 등이 부족해 판단이 어려우면 '확인 필요'로 판단한다.
534
+ 9. 검색된 규제 원문에 해당 원료의 구성 성분, 동의어, 규제군이 직접 관련되지 않으면 다른 성분 규제를 적용하지 말고 '정보 없음'으로 답변한다.
535
+ 10. 부적합 사유는 부적합일 때만 작성하고, 아니면 '-'로 작성한다.
536
+ 11. 규제 정도에는 규제군, 총량 계산, 한도, 판단 결과를 짧게 작성한다.
537
+ 12. 답변은 한 원료당 한 줄 결과로 요약한다.
538
+
539
+ 답변 예시:
540
+ 규제 대상: Retinol 포함 복합
541
+ 원료 투입량: 0.200
542
+ 적합 여부: 통과
543
+ 부적합 사유: -
544
+ 규제 정도: 비타민A 규제 / 총 Retinol 0.1002%(=0.0002+0.100), 한도 0.3% RE 이내(통과)
545
 
546
+ 답변 예시:
547
+ 규제 대상: -
548
+ 원료 투입량: 1.000
549
+ 적합 여부: 정보 없음
550
  부적합 사유: -
551
+ 규제 정도: 관련 규제 확인되지 않음
552
  """
553
 
554
  try:
555
+ response = llm.invoke(prompt).content
556
+ parsed = parse_response(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
 
558
+ except Exception as e:
559
+ parsed = {
560
+ "규제 대상": "-",
561
+ "원료 투입량": str(raw_amount),
562
+ "적합 여부": "확인 필요",
563
+ "부적합 사유": str(e),
564
+ "규제 정도": "에러"
565
+ }
566
+
567
+ output_rows.append({
568
+ "원료명": raw_material,
569
+ "규제 대상": parsed["규제 대상"],
570
+ "원료 투입량": parsed["원료 투입량"] if parsed["원료 투입량"] != "-" else raw_amount,
571
+ "적합 여부": parsed["적합 여부"],
572
+ "부적합 사유": parsed["부적합 사유"],
573
+ "규제 정도": parsed["규제 정도"]
574
+ })
575
+
576
+ result_df = pd.DataFrame(output_rows)
577
+
578
+ result_df = result_df[
579
+ ["원료명", "규제 대상", "원료 투입량", "적합 여부", "부적합 사유", "규제 정도"]
580
+ ]
581
+
582
+ if isinstance(country_folders, list):
583
+ country_name = "_".join(country_folders)
584
+ else:
585
+ country_name = str(country_folders)
586
+
587
+ safe_country_name = re.sub(r"[^a-zA-Z0-9가-힣_-]", "_", country_name)
588
+
589
+ out = f"result_{safe_country_name}.xlsx"
590
+
591
+ result_df.to_excel(out, index=False)
592
  style_excel(out)
593
 
594
+ return result_df, out
595
 
596
 
597
  # =========================
598
  # UI
599
  # =========================
600
+ with gr.Blocks(css=custom_css) as demo:
 
601
  gr.Markdown("# 🌍 reBom Regulatory Screening AI")
602
  gr.Markdown("### 글로벌 화장품 규제 기반 전성분 스크리닝")
603
 
604
+ country = gr.CheckboxGroup(
605
+ choices=get_country_folders(),
606
+ value=[get_country_folders()[0]] if get_country_folders()[0] != "폴더 없음" else [],
607
+ label="🌍 스크리닝 국가 선택",
608
+ elem_id="country_checks"
609
+ )
610
+
611
+ refresh = gr.Button("🔄 폴더 새로고침")
612
+
613
+ file = gr.File(
614
+ label="전성분 엑셀 업로드 (.xlsx)",
615
+ file_types=[".xlsx"]
616
+ )
617
 
618
+ btn = gr.Button("🚀 분석 시작", variant="primary")
619
 
620
+ df_out = gr.Dataframe(
621
+ label="결과 미리보기",
622
+ wrap=True,
623
+ interactive=False
624
+ )
625
+
626
+ file_out = gr.File(label="결과 파일 다운로드")
627
+
628
+ refresh.click(
629
+ fn=lambda: gr.update(
630
+ choices=get_country_folders(),
631
+ value=[get_country_folders()[0]] if get_country_folders()[0] != "폴더 없음" else []
632
+ ),
633
+ outputs=country
634
+ )
635
+
636
+ file.change(
637
+ fn=preview_excel,
638
+ inputs=file,
639
+ outputs=df_out
640
+ )
641
+
642
+ btn.click(
643
+ process,
644
+ inputs=[country, file],
645
+ outputs=[df_out, file_out]
646
+ )
647
 
 
 
648
 
649
+ demo.launch(ssr_mode=False)