jin2li commited on
Commit
e08cd03
ยท
verified ยท
1 Parent(s): c26954c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -60
app.py CHANGED
@@ -2,100 +2,176 @@ import os
2
  import pandas as pd
3
  import pdfplumber
4
  import gradio as gr
5
- from langchain_community.embeddings import OpenAIEmbeddings
6
- from langchain_community.chat_models import ChatOpenAI
7
  from langchain_community.vectorstores import FAISS
8
  from langchain_text_splitters import RecursiveCharacterTextSplitter
9
 
10
- # 1. API ํ‚ค ์„ค์ •
 
11
  api_key = os.getenv("OPENAI_API_KEY")
12
- if api_key:
13
- os.environ["OPENAI_API_KEY"] = api_key
 
 
 
14
 
15
- # 2. ๊ตญ๊ฐ€ ํด๋” ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ (ํŒŒ์ผ์ด ์•„๋‹Œ ํด๋”๋งŒ ํ•„ํ„ฐ๋ง)
16
  def get_country_folders():
17
  exclude = ['.git', '.cache', '__pycache__', '.ipynb_checkpoints']
18
- folders = [f for f in os.listdir(".") if os.path.isdir(f) and f not in exclude]
 
 
 
19
  return folders if folders else ["ํด๋” ์—†์Œ"]
20
 
 
21
  # 3. ์„ ํƒ๋œ ๊ตญ๊ฐ€์˜ PDF๋กœ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ƒ์„ฑ
22
  def build_database(country_folder):
23
- if country_folder == "ํด๋” ์—†์Œ": return None
24
-
 
25
  all_texts = []
26
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
27
-
28
- # ์„ ํƒ๋œ ํด๋” ์•ˆ์˜ PDF ํŒŒ์ผ๋“ค ์ฐพ๊ธฐ
 
 
29
  path = f"./{country_folder}"
30
- files = [f for f in os.listdir(path) if f.lower().endswith('.pdf')]
31
-
32
- if not files: return None
 
 
 
 
33
 
34
  for filename in files:
35
  try:
36
  with pdfplumber.open(os.path.join(path, filename)) as pdf:
37
  for page in pdf.pages:
38
  text = page.extract_text()
39
- if text: all_texts.extend(text_splitter.split_text(f"[์ถœ์ฒ˜: {filename}] " + text))
40
- except: continue
41
-
42
- if not all_texts: return None
43
- return FAISS.from_texts(all_texts, OpenAIEmbeddings())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  # 4. ๋ถ„์„ ํ•จ์ˆ˜
46
  def process_screening(country, excel_file):
47
- if not excel_file: return None, "โŒ ์—‘์…€ ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."
48
- if country == "ํด๋” ์—†์Œ": return None, "โŒ ๊ตญ๊ฐ€ ํด๋”๋ฅผ ๋จผ์ € ์ƒ์„ฑํ•˜๊ณ  PDF๋ฅผ ๋„ฃ์–ด์ฃผ์„ธ์š”."
49
-
50
- # 1) ํ•ด๋‹น ๊ตญ๊ฐ€ DB ๊ตฌ์ถ•
51
- vector_db = build_database(country)
52
- if not vector_db: return None, f"โŒ {country} ํด๋” ๋‚ด์— ๋ถ„์„ํ•  PDF ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค."
53
-
54
- # 2) ๋ชจ๋ธ ์„ค์ •
55
- llm = ChatOpenAI(model_name="gpt-4-turbo", temperature=0)
56
-
57
- # 3) ์—‘์…€ ์ฝ๊ธฐ
58
- df = pd.read_excel(excel_file.name)
59
-
60
- results = []
61
- for name in df.iloc[:, 0]:
62
- ing_name = str(name)
63
- # ์œ ์‚ฌ ๋ฌธ๊ตฌ ๊ฒ€์ƒ‰
64
- docs = vector_db.similarity_search(ing_name, k=3)
65
- context = "\n".join([d.page_content for d in docs])
66
-
67
- prompt = f"ํ™”์žฅํ’ˆ ๊ทœ์ œ ์ „๋ฌธ๊ฐ€๋กœ์„œ ์•„๋ž˜ ๊ทœ์ œ ์›๋ฌธ ๋‚ด์šฉ์„ ์ฐธ๊ณ ํ•ด '{ing_name}'์˜ ๊ทœ์ œ ์‚ฌํ•ญ(ํ•œ๋„, ๊ธˆ์ง€์—ฌ๋ถ€ ๋“ฑ)์„ ํŒฉํŠธ ์œ„์ฃผ๋กœ ์งง๊ฒŒ ์š”์•ฝํ•˜์„ธ์š”. ๊ด€๋ จ ๋‚ด์šฉ์ด ์—†๋‹ค๋ฉด '์ •๋ณด ์—†์Œ'์ด๋ผ ๋‹ตํ•˜์„ธ์š”.\n\n{context}"
68
- try:
69
- res = llm.predict(prompt)
70
- results.append(res)
71
- except:
72
- results.append("์—๋Ÿฌ ๋ฐœ์ƒ")
73
-
74
- df['์Šคํฌ๋ฆฌ๋‹ ๊ฒฐ๊ณผ'] = results
75
- out_path = f"reBom_Result_{country}.xlsx"
76
- df.to_excel(out_path, index=False)
77
- return df, out_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
  # 5. UI ๊ตฌ์„ฑ
80
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
81
  gr.Markdown("# ๐Ÿงช reBom Global Regulatory AI")
82
  gr.Markdown("### ๊ตญ๊ฐ€๋ณ„ ํด๋”๋ฅผ ์„ ํƒํ•˜๊ณ  ์„ฑ๋ถ„๋ช… ์—‘์…€์„ ์—…๋กœ๋“œํ•˜์„ธ์š”.")
83
-
84
  with gr.Row():
85
- country_select = gr.Dropdown(choices=get_country_folders(), label="๐ŸŒ ์Šคํฌ๋ฆฌ๋‹ ๊ตญ๊ฐ€ ์„ ํƒ", value=get_country_folders()[0])
86
- refresh_btn = gr.Button("๐Ÿ”„ ํด๋” ์ƒˆ๋กœ๊ณ ์นจ", variant="secondary", scale=0)
87
-
 
 
 
 
 
 
 
 
88
  with gr.Row():
89
  f_in = gr.File(label="์ „์„ฑ๋ถ„ ์—‘์…€ ์—…๋กœ๋“œ (.xlsx)")
90
  btn = gr.Button("๐Ÿš€ ๋ถ„์„ ์‹œ์ž‘", variant="primary")
91
-
92
  with gr.Row():
93
  df_out = gr.Dataframe(label="๊ฒฐ๊ณผ ๋ฏธ๋ฆฌ๋ณด๊ธฐ")
94
  f_out = gr.File(label="๊ฒฐ๊ณผ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ")
95
 
96
- # ํด๋” ๋ชฉ๋ก ์ƒˆ๋กœ๊ณ ์นจ ๊ธฐ๋Šฅ
97
- refresh_btn.click(fn=lambda: gr.update(choices=get_country_folders()), outputs=country_select)
98
- # ๋ถ„์„ ์‹คํ–‰
99
- btn.click(process_screening, inputs=[country_select, f_in], outputs=[df_out, f_out])
 
 
 
 
 
 
 
100
 
101
  demo.launch()
 
2
  import pandas as pd
3
  import pdfplumber
4
  import gradio as gr
5
+
6
+ from langchain_openai import OpenAIEmbeddings, ChatOpenAI
7
  from langchain_community.vectorstores import FAISS
8
  from langchain_text_splitters import RecursiveCharacterTextSplitter
9
 
10
+
11
+ # 1. API ํ‚ค ํ™•์ธ
12
  api_key = os.getenv("OPENAI_API_KEY")
13
+ if not api_key:
14
+ print("โŒ OPENAI_API_KEY๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
15
+ else:
16
+ print("โœ… OPENAI_API_KEY๊ฐ€ ์„ค์ •๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
17
+
18
 
19
+ # 2. ๊ตญ๊ฐ€ ํด๋” ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ
20
  def get_country_folders():
21
  exclude = ['.git', '.cache', '__pycache__', '.ipynb_checkpoints']
22
+ folders = [
23
+ f for f in os.listdir(".")
24
+ if os.path.isdir(f) and f not in exclude
25
+ ]
26
  return folders if folders else ["ํด๋” ์—†์Œ"]
27
 
28
+
29
  # 3. ์„ ํƒ๋œ ๊ตญ๊ฐ€์˜ PDF๋กœ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ƒ์„ฑ
30
  def build_database(country_folder):
31
+ if country_folder == "ํด๋” ์—†์Œ":
32
+ return None
33
+
34
  all_texts = []
35
+ text_splitter = RecursiveCharacterTextSplitter(
36
+ chunk_size=800,
37
+ chunk_overlap=100
38
+ )
39
+
40
  path = f"./{country_folder}"
41
+ files = [
42
+ f for f in os.listdir(path)
43
+ if f.lower().endswith(".pdf")
44
+ ]
45
+
46
+ if not files:
47
+ return None
48
 
49
  for filename in files:
50
  try:
51
  with pdfplumber.open(os.path.join(path, filename)) as pdf:
52
  for page in pdf.pages:
53
  text = page.extract_text()
54
+ if text:
55
+ chunks = text_splitter.split_text(
56
+ f"[์ถœ์ฒ˜: {filename}] {text}"
57
+ )
58
+ all_texts.extend(chunks)
59
+
60
+ except Exception as e:
61
+ print(f"PDF ์ฝ๊ธฐ ์˜ค๋ฅ˜: {filename} / {e}")
62
+ continue
63
+
64
+ if not all_texts:
65
+ return None
66
+
67
+ embeddings = OpenAIEmbeddings(
68
+ model="text-embedding-3-small"
69
+ )
70
+
71
+ return FAISS.from_texts(all_texts, embeddings)
72
+
73
 
74
  # 4. ๋ถ„์„ ํ•จ์ˆ˜
75
  def process_screening(country, excel_file):
76
+ if not excel_file:
77
+ return None, "โŒ ์—‘์…€ ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."
78
+
79
+ if country == "ํด๋” ์—†์Œ":
80
+ return None, "โŒ ๊ตญ๊ฐ€ ํด๋”๋ฅผ ๋จผ์ € ์ƒ์„ฑํ•˜๊ณ  PDF๋ฅผ ๋„ฃ์–ด์ฃผ์„ธ์š”."
81
+
82
+ try:
83
+ vector_db = build_database(country)
84
+
85
+ if not vector_db:
86
+ return None, f"โŒ {country} ํด๋” ๋‚ด์— ๋ถ„์„ํ•  PDF ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค."
87
+
88
+ llm = ChatOpenAI(
89
+ model="gpt-4o-mini",
90
+ temperature=0
91
+ )
92
+
93
+ df = pd.read_excel(excel_file.name)
94
+
95
+ results = []
96
+
97
+ for name in df.iloc[:, 0]:
98
+ ing_name = str(name).strip()
99
+
100
+ if not ing_name or ing_name.lower() == "nan":
101
+ results.append("์„ฑ๋ถ„๋ช… ๏ฟฝ๏ฟฝ์Œ")
102
+ continue
103
+
104
+ try:
105
+ docs = vector_db.similarity_search(ing_name, k=3)
106
+ context = "\n".join([d.page_content for d in docs])
107
+
108
+ prompt = f"""
109
+ ํ™”์žฅํ’ˆ ๊ทœ์ œ ์ „๋ฌธ๊ฐ€๋กœ์„œ ์•„๋ž˜ ๊ทœ์ œ ์›๋ฌธ ๋‚ด์šฉ์„ ์ฐธ๊ณ ํ•ด '{ing_name}'์˜ ๊ทœ์ œ ์‚ฌํ•ญ์„ ๊ฒ€ํ† ํ•˜์„ธ์š”.
110
+
111
+ ๊ฒ€ํ†  ๊ธฐ์ค€:
112
+ - ๊ธˆ์ง€ ์—ฌ๋ถ€
113
+ - ์‚ฌ์šฉ ํ•œ๋„
114
+ - ์‚ฌ์šฉ ์กฐ๊ฑด
115
+ - ๊ด€๋ จ ๋‚ด์šฉ์ด ์—†์œผ๋ฉด '์ •๋ณด ์—†์Œ'์ด๋ผ๊ณ  ๋‹ต๋ณ€
116
+
117
+ ๋‹ต๋ณ€์€ ์งง๊ณ  ํŒฉํŠธ ์œ„์ฃผ๋กœ ์ž‘์„ฑํ•˜์„ธ์š”.
118
+
119
+ [๊ทœ์ œ ์›๋ฌธ]
120
+ {context}
121
+ """
122
+
123
+ res = llm.invoke(prompt)
124
+ results.append(res.content)
125
+
126
+ except Exception as e:
127
+ results.append(f"์—๋Ÿฌ ๋ฐœ์ƒ: {str(e)}")
128
+
129
+ df["์Šคํฌ๋ฆฌ๋‹ ๊ฒฐ๊ณผ"] = results
130
+
131
+ out_path = f"reBom_Result_{country}.xlsx"
132
+ df.to_excel(out_path, index=False)
133
+
134
+ return df, out_path
135
+
136
+ except Exception as e:
137
+ return None, f"โŒ ์ „์ฒด ์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {str(e)}"
138
+
139
 
140
  # 5. UI ๊ตฌ์„ฑ
141
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
142
  gr.Markdown("# ๐Ÿงช reBom Global Regulatory AI")
143
  gr.Markdown("### ๊ตญ๊ฐ€๋ณ„ ํด๋”๋ฅผ ์„ ํƒํ•˜๊ณ  ์„ฑ๋ถ„๋ช… ์—‘์…€์„ ์—…๋กœ๋“œํ•˜์„ธ์š”.")
144
+
145
  with gr.Row():
146
+ country_select = gr.Dropdown(
147
+ choices=get_country_folders(),
148
+ label="๐ŸŒ ์Šคํฌ๋ฆฌ๋‹ ๊ตญ๊ฐ€ ์„ ํƒ",
149
+ value=get_country_folders()[0]
150
+ )
151
+ refresh_btn = gr.Button(
152
+ "๐Ÿ”„ ํด๋” ์ƒˆ๋กœ๊ณ ์นจ",
153
+ variant="secondary",
154
+ scale=0
155
+ )
156
+
157
  with gr.Row():
158
  f_in = gr.File(label="์ „์„ฑ๋ถ„ ์—‘์…€ ์—…๋กœ๋“œ (.xlsx)")
159
  btn = gr.Button("๐Ÿš€ ๋ถ„์„ ์‹œ์ž‘", variant="primary")
160
+
161
  with gr.Row():
162
  df_out = gr.Dataframe(label="๊ฒฐ๊ณผ ๋ฏธ๋ฆฌ๋ณด๊ธฐ")
163
  f_out = gr.File(label="๊ฒฐ๊ณผ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ")
164
 
165
+ refresh_btn.click(
166
+ fn=lambda: gr.update(choices=get_country_folders()),
167
+ outputs=country_select
168
+ )
169
+
170
+ btn.click(
171
+ process_screening,
172
+ inputs=[country_select, f_in],
173
+ outputs=[df_out, f_out]
174
+ )
175
+
176
 
177
  demo.launch()