jin2li commited on
Commit
b60ab34
ยท
verified ยท
1 Parent(s): 6da0bee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -89
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import pandas as pd
3
  import pdfplumber
4
  import gradio as gr
@@ -10,15 +11,15 @@ from langchain_community.vectorstores import FAISS
10
  from langchain_text_splitters import RecursiveCharacterTextSplitter
11
 
12
 
13
- # API ํ‚ค ํ™•์ธ
14
  api_key = os.getenv("OPENAI_API_KEY")
15
  if not api_key:
16
- print("โŒ OPENAI_API_KEY๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
17
  else:
18
- print("โœ… OPENAI_API_KEY๊ฐ€ ์„ค์ •๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
19
 
20
 
21
- # ๊ตญ๊ฐ€ ํด๋” ๊ฐ€์ ธ์˜ค๊ธฐ
22
  def get_country_folders():
23
  exclude = [".git", ".cache", "__pycache__", ".ipynb_checkpoints"]
24
  folders = [f for f in os.listdir(".") if os.path.isdir(f) and f not in exclude]
@@ -26,44 +27,50 @@ def get_country_folders():
26
 
27
 
28
  # ์—‘์…€ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
29
- def preview_excel(excel_file):
30
- if not excel_file:
31
  return None
32
- try:
33
- return pd.read_excel(excel_file.name)
34
- except Exception as e:
35
- return pd.DataFrame({"์˜ค๋ฅ˜": [str(e)]})
36
 
37
 
38
- # PDF โ†’ ๋ฒกํ„ฐDB
39
- def build_database(country_folder):
40
- if country_folder == "ํด๋” ์—†์Œ":
 
 
 
 
 
 
 
 
 
41
  return None
 
 
42
 
43
- all_texts = []
 
 
 
44
  splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
45
 
46
- path = f"./{country_folder}"
47
- files = [f for f in os.listdir(path) if f.lower().endswith(".pdf")]
48
 
49
- if not files:
50
- return None
51
-
52
- for filename in files:
53
  try:
54
- with pdfplumber.open(os.path.join(path, filename)) as pdf:
55
  for page in pdf.pages:
56
- text = page.extract_text()
57
- if text:
58
- all_texts.extend(splitter.split_text(f"[์ถœ์ฒ˜: {filename}] {text}"))
59
- except Exception as e:
60
- print(f"PDF ์˜ค๋ฅ˜: {filename} / {e}")
61
 
62
- if not all_texts:
63
  return None
64
 
65
- embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
66
- return FAISS.from_texts(all_texts, embeddings)
67
 
68
 
69
  # ์—‘์…€ ์Šคํƒ€์ผ
@@ -71,60 +78,54 @@ def style_excel(path):
71
  wb = load_workbook(path)
72
  ws = wb.active
73
 
74
- red = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
75
- yellow = PatternFill(start_color="FFF2CC", end_color="FFF2CC", fill_type="solid")
76
 
77
  headers = [c.value for c in ws[1]]
78
- ์ ํ•ฉ_col = headers.index("์ ํ•ฉ ์—ฌ๋ถ€") + 1
79
- ๊ทœ์ œ_col = headers.index("๊ทœ์ œ ์ •๋„") + 1
80
-
81
- for row in range(2, ws.max_row + 1):
82
- status = str(ws.cell(row, ์ ํ•ฉ_col).value or "")
83
- reg = str(ws.cell(row, ๊ทœ์ œ_col).value or "")
84
 
85
- if "๋ถ€์ ํ•ฉ" in status:
86
- for c in range(1, ws.max_column + 1):
87
- ws.cell(row, c).fill = red
88
 
89
- elif "ํ™•์ธ ํ•„์š”" in status or ("์ •๋ณด ์—†์Œ" not in reg and reg.strip()):
90
- for c in range(1, ws.max_column + 1):
91
- ws.cell(row, c).fill = yellow
 
 
 
92
 
93
  wb.save(path)
94
 
95
 
96
- # ํ•ต์‹ฌ ๋ถ„์„
97
- def process_screening(country, excel_file):
98
- if not excel_file:
99
- return None, "โŒ ์—‘์…€ ์—…๋กœ๋“œ ํ•„์š”"
100
-
101
- vector_db = build_database(country)
102
- if not vector_db:
103
- return None, "โŒ PDF ์—†์Œ"
104
 
 
105
  llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
106
 
107
- df = pd.read_excel(excel_file.name)
108
 
109
- ์ ํ•ฉ์—ฌ๋ถ€, ๋ถ€์ ํ•ฉ์‚ฌ์œ , ๊ทœ์ œ๊ฒฐ๊ณผ = [], [], []
110
 
111
  for _, row in df.iterrows():
112
- ing = str(row.iloc[0]).strip()
113
 
114
- if not ing:
115
- ์ ํ•ฉ์—ฌ๋ถ€.append("ํ™•์ธ ํ•„์š”")
116
- ๋ถ€์ ํ•ฉ์‚ฌ์œ .append("์„ฑ๋ถ„ ์—†์Œ")
117
- ๊ทœ์ œ๊ฒฐ๊ณผ.append("์ •๋ณด ์—†์Œ")
118
- continue
119
 
120
- try:
121
- docs = vector_db.similarity_search(ing, k=3)
122
- context = "\n".join([d.page_content for d in docs])
123
 
124
- prompt = f"""
125
  ์„ฑ๋ถ„: {ing}
 
126
 
127
- ๊ทœ์ œ ๊ธฐ๋ฐ˜์œผ๋กœ ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ๋‹ต๋ณ€
128
 
129
  ์ ํ•ฉ ์—ฌ๋ถ€:
130
  ๋ถ€์ ํ•ฉ ์‚ฌ์œ :
@@ -133,30 +134,28 @@ def process_screening(country, excel_file):
133
  {context}
134
  """
135
 
 
136
  res = llm.invoke(prompt).content
 
 
137
 
138
- s, r, g = "", "", ""
139
-
140
- for line in res.splitlines():
141
- if line.startswith("์ ํ•ฉ ์—ฌ๋ถ€:"):
142
- s = line.replace("์ ํ•ฉ ์—ฌ๋ถ€:", "").strip()
143
- elif line.startswith("๋ถ€์ ํ•ฉ ์‚ฌ์œ :"):
144
- r = line.replace("๋ถ€์ ํ•ฉ ์‚ฌ์œ :", "").strip()
145
- elif line.startswith("๊ทœ์ œ ์ •๋„:"):
146
- g = line.replace("๊ทœ์ œ ์ •๋„:", "").strip()
147
 
148
- ์ ํ•ฉ์—ฌ๋ถ€.append(s or "ํ™•์ธ ํ•„์š”")
149
- ๋ถ€์ ํ•ฉ์‚ฌ์œ .append(r or "-")
150
- ๊ทœ์ œ๊ฒฐ๊ณผ.append(g or "์ •๋ณด ์—†์Œ")
 
 
 
 
151
 
152
- except Exception as e:
153
- ์ ํ•ฉ์—ฌ๋ถ€.append("ํ™•์ธ ํ•„์š”")
154
- ๋ถ€์ ํ•ฉ์‚ฌ์œ .append(str(e))
155
- ๊ทœ์ œ๊ฒฐ๊ณผ.append("์—๋Ÿฌ")
156
 
157
- df["์ ํ•ฉ ์—ฌ๋ถ€"] = ์ ํ•ฉ์—ฌ๋ถ€
158
- df["๋ถ€์ ํ•ฉ ์‚ฌ์œ "] = ๋ถ€์ ํ•ฉ์‚ฌ์œ 
159
- df["๊ทœ์ œ ์ •๋„"] = ๊ทœ์ œ๊ฒฐ๊ณผ
160
 
161
  out = f"result_{country}.xlsx"
162
  df.to_excel(out, index=False)
@@ -167,18 +166,19 @@ def process_screening(country, excel_file):
167
 
168
  # UI
169
  with gr.Blocks() as demo:
170
- gr.Markdown("# ๐Ÿงช Regulatory AI")
 
171
 
172
- country = gr.Dropdown(choices=get_country_folders(), value=get_country_folders()[0])
173
  file = gr.File()
174
 
175
  btn = gr.Button("๋ถ„์„")
176
 
177
- df_out = gr.Dataframe(label="๋ฏธ๋ฆฌ๋ณด๊ธฐ", wrap=True, interactive=False)
178
- file_out = gr.File()
179
 
180
- file.change(preview_excel, inputs=file, outputs=df_out)
181
- btn.click(process_screening, inputs=[country, file], outputs=[df_out, file_out])
182
 
183
 
184
  demo.launch()
 
1
  import os
2
+ import re
3
  import pandas as pd
4
  import pdfplumber
5
  import gradio as gr
 
11
  from langchain_text_splitters import RecursiveCharacterTextSplitter
12
 
13
 
14
+ # API KEY ์ฒดํฌ
15
  api_key = os.getenv("OPENAI_API_KEY")
16
  if not api_key:
17
+ print("โŒ OPENAI_API_KEY ์—†์Œ")
18
  else:
19
+ print("โœ… OPENAI_API_KEY ์ •์ƒ")
20
 
21
 
22
+ # ๊ตญ๊ฐ€ ํด๋”
23
  def get_country_folders():
24
  exclude = [".git", ".cache", "__pycache__", ".ipynb_checkpoints"]
25
  folders = [f for f in os.listdir(".") if os.path.isdir(f) and f not in exclude]
 
27
 
28
 
29
  # ์—‘์…€ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
30
+ def preview_excel(file):
31
+ if not file:
32
  return None
33
+ return pd.read_excel(file.name)
 
 
 
34
 
35
 
36
+ # ํ•จ๋Ÿ‰ ์ปฌ๋Ÿผ ์ฐพ๊ธฐ
37
+ def find_amount_column(df):
38
+ keywords = ["ํ•จ๋Ÿ‰", "๋†๋„", "concentration", "%", "amount"]
39
+ for col in df.columns:
40
+ if any(k in str(col).lower() for k in keywords):
41
+ return col
42
+ return None
43
+
44
+
45
+ # ์ˆซ์ž ์ถ”์ถœ
46
+ def extract_number(value):
47
+ if pd.isna(value):
48
  return None
49
+ m = re.search(r"(\d+\.?\d*)", str(value))
50
+ return float(m.group(1)) if m else None
51
 
52
+
53
+ # DB ์ƒ์„ฑ
54
+ def build_database(folder):
55
+ texts = []
56
  splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
57
 
58
+ files = [f for f in os.listdir(folder) if f.lower().endswith(".pdf")]
 
59
 
60
+ for f in files:
 
 
 
61
  try:
62
+ with pdfplumber.open(os.path.join(folder, f)) as pdf:
63
  for page in pdf.pages:
64
+ t = page.extract_text()
65
+ if t:
66
+ texts.extend(splitter.split_text(t))
67
+ except:
68
+ pass
69
 
70
+ if not texts:
71
  return None
72
 
73
+ return FAISS.from_texts(texts, OpenAIEmbeddings(model="text-embedding-3-small"))
 
74
 
75
 
76
  # ์—‘์…€ ์Šคํƒ€์ผ
 
78
  wb = load_workbook(path)
79
  ws = wb.active
80
 
81
+ red = PatternFill(start_color="FFC7CE", fill_type="solid")
82
+ yellow = PatternFill(start_color="FFF2CC", fill_type="solid")
83
 
84
  headers = [c.value for c in ws[1]]
85
+ s_col = headers.index("์ ํ•ฉ ์—ฌ๋ถ€") + 1
86
+ r_col = headers.index("๊ทœ์ œ ์ •๋„") + 1
 
 
 
 
87
 
88
+ for i in range(2, ws.max_row + 1):
89
+ s = str(ws.cell(i, s_col).value or "")
90
+ r = str(ws.cell(i, r_col).value or "")
91
 
92
+ if "๋ถ€์ ํ•ฉ" in s:
93
+ for j in range(1, ws.max_column + 1):
94
+ ws.cell(i, j).fill = red
95
+ elif "ํ™•์ธ ํ•„์š”" in s or r:
96
+ for j in range(1, ws.max_column + 1):
97
+ ws.cell(i, j).fill = yellow
98
 
99
  wb.save(path)
100
 
101
 
102
+ # ๋ฉ”์ธ ๋ถ„์„
103
+ def process(country, file):
104
+ db = build_database(country)
105
+ if not db:
106
+ return None, "PDF ์—†์Œ"
 
 
 
107
 
108
+ df = pd.read_excel(file.name)
109
  llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
110
 
111
+ amount_col = find_amount_column(df)
112
 
113
+ status, reason, reg = [], [], []
114
 
115
  for _, row in df.iterrows():
116
+ ing = str(row.iloc[0])
117
 
118
+ amount = row.get(amount_col) if amount_col else "-"
119
+ amount_num = extract_number(amount)
 
 
 
120
 
121
+ docs = db.similarity_search(ing, k=3)
122
+ context = "\n".join([d.page_content for d in docs])
 
123
 
124
+ prompt = f"""
125
  ์„ฑ๋ถ„: {ing}
126
+ ํ•จ๋Ÿ‰: {amount} ({amount_num})
127
 
128
+ ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ๋‹ต๋ณ€:
129
 
130
  ์ ํ•ฉ ์—ฌ๋ถ€:
131
  ๋ถ€์ ํ•ฉ ์‚ฌ์œ :
 
134
  {context}
135
  """
136
 
137
+ try:
138
  res = llm.invoke(prompt).content
139
+ except Exception as e:
140
+ res = f"์—๋Ÿฌ\n{e}"
141
 
142
+ s, r, g = "", "", ""
 
 
 
 
 
 
 
 
143
 
144
+ for line in res.splitlines():
145
+ if "์ ํ•ฉ ์—ฌ๋ถ€" in line:
146
+ s = line.split(":")[-1].strip()
147
+ elif "๋ถ€์ ํ•ฉ ์‚ฌ์œ " in line:
148
+ r = line.split(":")[-1].strip()
149
+ elif "๊ทœ์ œ ์ •๋„" in line:
150
+ g = line.split(":")[-1].strip()
151
 
152
+ status.append(s or "ํ™•์ธ ํ•„์š”")
153
+ reason.append(r or "-")
154
+ reg.append(g or "์ •๋ณด ์—†์Œ")
 
155
 
156
+ df["์ ํ•ฉ ์—ฌ๋ถ€"] = status
157
+ df["๋ถ€์ ํ•ฉ ์‚ฌ์œ "] = reason
158
+ df["๊ทœ์ œ ์ •๋„"] = reg
159
 
160
  out = f"result_{country}.xlsx"
161
  df.to_excel(out, index=False)
 
166
 
167
  # UI
168
  with gr.Blocks() as demo:
169
+ gr.Markdown("# ๐ŸŒ reBom Regulatory Screening AI")
170
+ gr.Markdown("### ๊ธ€๋กœ๋ฒŒ ํ™”์žฅํ’ˆ ๊ทœ์ œ ๊ธฐ๋ฐ˜ ์ „์„ฑ๋ถ„ ์Šคํฌ๋ฆฌ๋‹")
171
 
172
+ country = gr.Dropdown(get_country_folders())
173
  file = gr.File()
174
 
175
  btn = gr.Button("๋ถ„์„")
176
 
177
+ df_out = gr.Dataframe(wrap=True)
178
+ f_out = gr.File()
179
 
180
+ file.change(preview_excel, file, df_out)
181
+ btn.click(process, [country, file], [df_out, f_out])
182
 
183
 
184
  demo.launch()