protae5544 commited on
Commit
107f2cd
·
verified ·
1 Parent(s): fe3ba7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -48
app.py CHANGED
@@ -2,22 +2,23 @@ import base64
2
  from io import BytesIO
3
  import json
4
  import os
 
5
  from openai import OpenAI
6
  from dotenv import load_dotenv
7
  from typhoon_ocr import prepare_ocr_messages
8
  import gradio as gr
9
  from PIL import Image
10
 
11
- # โหลด environment variables จาก .env
12
  load_dotenv()
13
 
14
- # ตั้งค่า OpenAI (ใช้ API ของ Typhoon OCR)
15
  openai = OpenAI(
16
  base_url=os.getenv("TYPHOON_BASE_URL"),
17
  api_key=os.getenv("TYPHOON_API_KEY")
18
  )
19
 
20
- # ตั้งค่า Theme (ใช้ของเดิม)
21
  theme = gr.themes.Soft(
22
  primary_hue=gr.themes.Color(
23
  c50="#f7f7fd",
@@ -40,61 +41,122 @@ theme = gr.themes.Soft(
40
  OUTPUT_FILE = "ocr_results.txt"
41
 
42
  def save_ocr_result(text):
43
- """บันทึกผลลัพธ์ OCR แบบต่อเนื่องในไฟล์เดียว พร้อมเว้น 2 บรรทัดระหว่างข้อมูล"""
44
  with open(OUTPUT_FILE, "a", encoding="utf-8") as f:
45
  f.write(text + "\n\n")
46
  return OUTPUT_FILE
47
 
48
  def clear_output_file():
49
- """ล้างไฟล์ผลลัพธ์เก่า (เรียกครั้งเดียวเมื่อเริ่มใช้งานใหม่)"""
50
  with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
51
  f.write("")
52
 
53
- def process_pdf(pdf_or_image_file, task_type, page_number):
 
 
 
 
 
 
 
54
  if pdf_or_image_file is None:
55
  return None, "No file uploaded"
56
 
57
  orig_filename = pdf_or_image_file.name
 
 
58
 
59
  try:
60
- # ใช้ prepare_ocr_messages ตามเดิม
61
- messages = prepare_ocr_messages(
62
- pdf_or_image_path=orig_filename,
63
- task_type=task_type,
64
- target_image_dim=1800,
65
- target_text_length=8000,
66
- page_num=page_number if page_number else 1
67
- )
68
-
69
- # ดึงภาพจากผลลัพธ์
70
- image_url = messages[0]["content"][1]["image_url"]["url"]
71
- image_base64 = image_url.replace("data:image/png;base64,", "")
72
- image_pil = Image.open(BytesIO(base64.b64decode(image_base64)))
73
-
74
- # ส่งไป API
75
- response = openai.chat.completions.create(
76
- model=os.getenv("TYPHOON_OCR_MODEL"),
77
- messages=messages,
78
- max_tokens=16384,
79
- extra_body={
80
- "repetition_penalty": 1.2,
81
- "temperature": 0.1,
82
- "top_p": 0.6,
83
- },
84
- )
85
- text_output = response.choices[0].message.content
86
-
87
- # ดึง natural_text
88
- try:
89
- json_data = json.loads(text_output)
90
- markdown_out = json_data.get('natural_text', "").replace("<figure>", "").replace("</figure>", "")
91
- except Exception as e:
92
- markdown_out = f"⚠️ Could not extract `natural_text` from output.\nError: {str(e)}"
93
-
94
- # บันทึกผลลัพธ์ต่อเนื่องในไฟล์
95
- save_ocr_result(markdown_out)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- return image_pil, markdown_out, gr.File.update(value=OUTPUT_FILE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
  except Exception as e:
100
  return None, f"Error processing file: {str(e)}", None
@@ -148,9 +210,6 @@ with gr.Blocks(theme=theme) as demo:
148
  font-size: 12px;
149
  }
150
  """
151
- # เลือกเพจ
152
- page_number = gr.Number(label="📄 Page Number (for PDFs only)", value=1, minimum=1, step=1)
153
-
154
  # ปุ่มรัน
155
  run_button = gr.Button("🚀 Run")
156
 
@@ -167,11 +226,11 @@ with gr.Blocks(theme=theme) as demo:
167
  # เชื่อมต่อ UI กับฟังก์ชัน
168
  run_button.click(
169
  fn=process_pdf,
170
- inputs=[pdf_input, task_dropdown, page_number],
171
  outputs=[image_output, markdown_output, download_button]
172
  )
173
 
174
- # เรียกครั้งเดียวเมื่อเริ่มเพื่อล้างไฟล์เก่า
175
  clear_output_file()
176
 
177
  # รันแอป
 
2
  from io import BytesIO
3
  import json
4
  import os
5
+ import PyPDF2 # เพิ่มไลบรารีสำหรับอ่าน PDF
6
  from openai import OpenAI
7
  from dotenv import load_dotenv
8
  from typhoon_ocr import prepare_ocr_messages
9
  import gradio as gr
10
  from PIL import Image
11
 
12
+ # โหลด environment variables
13
  load_dotenv()
14
 
15
+ # ตั้งค่า OpenAI API
16
  openai = OpenAI(
17
  base_url=os.getenv("TYPHOON_BASE_URL"),
18
  api_key=os.getenv("TYPHOON_API_KEY")
19
  )
20
 
21
+ # ตั้งค่า Theme (เดิม)
22
  theme = gr.themes.Soft(
23
  primary_hue=gr.themes.Color(
24
  c50="#f7f7fd",
 
41
  OUTPUT_FILE = "ocr_results.txt"
42
 
43
  def save_ocr_result(text):
44
+ """บันทึกผลลัพธ์ OCR แบบต่อเนื่องในไฟล์เดียว"""
45
  with open(OUTPUT_FILE, "a", encoding="utf-8") as f:
46
  f.write(text + "\n\n")
47
  return OUTPUT_FILE
48
 
49
  def clear_output_file():
50
+ """ล้างไฟล์ผลลัพธ์เก่า"""
51
  with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
52
  f.write("")
53
 
54
+ def get_pdf_page_count(pdf_path):
55
+ """หาจำนวนหน้าของ PDF"""
56
+ with open(pdf_path, 'rb') as f:
57
+ reader = PyPDF2.PdfReader(f)
58
+ return len(reader.pages)
59
+ return 0
60
+
61
+ def process_pdf(pdf_or_image_file, task_type):
62
  if pdf_or_image_file is None:
63
  return None, "No file uploaded"
64
 
65
  orig_filename = pdf_or_image_file.name
66
+ combined_text = ""
67
+ image_pil = None # ใช้เก็บภาพหน้าแรกของ PDF
68
 
69
  try:
70
+ # ตรวจสอบว่าเป็น PDF หรือไม่
71
+ if orig_filename.lower().endswith(".pdf"):
72
+ total_pages = get_pdf_page_count(orig_filename)
73
+
74
+ if total_pages == 0:
75
+ return None, "ไม่สามารถอ่านจำนวนหน้าของ PDF ได้"
76
+
77
+ # ประมวลผลทุกหน้า
78
+ for page_num in range(1, total_pages + 1):
79
+ # เตรียมข้อมูลสำหรับ OCR
80
+ messages = prepare_ocr_messages(
81
+ pdf_or_image_path=orig_filename,
82
+ task_type=task_type,
83
+ target_image_dim=1800,
84
+ target_text_length=8000,
85
+ page_num=page_num
86
+ )
87
+
88
+ # ดึงภาพหน้าแรก
89
+ if page_num == 1:
90
+ image_url = messages[0]["content"][1]["image_url"]["url"]
91
+ image_base64 = image_url.replace("data:image/png;base64,", "")
92
+ image_pil = Image.open(BytesIO(base64.b64decode(image_base64)))
93
+
94
+ # ส่งไป API
95
+ response = openai.chat.completions.create(
96
+ model=os.getenv("TYPHOON_OCR_MODEL"),
97
+ messages=messages,
98
+ max_tokens=16384,
99
+ extra_body={
100
+ "repetition_penalty": 1.2,
101
+ "temperature": 0.1,
102
+ "top_p": 0.6,
103
+ },
104
+ )
105
+ text_output = response.choices[0].message.content
106
+
107
+ # ดึง natural_text
108
+ try:
109
+ json_data = json.loads(text_output)
110
+ markdown_out = json_data.get('natural_text', "").replace("<figure>", "").replace("</figure>", "")
111
+ except Exception as e:
112
+ markdown_out = f"⚠️ Could not extract `natural_text` from output.\nError: {str(e)}"
113
+
114
+ # รวมผลลัพธ์ทุกหน้า
115
+ combined_text += f"[Page {page_num}]\n{markdown_out}\n\n"
116
+
117
+ # บันทึกผลลัพธ์ทั้งหมดลงไฟล์
118
+ save_ocr_result(combined_text)
119
+ return image_pil, combined_text, gr.File.update(value=OUTPUT_FILE)
120
 
121
+ # หากเป็นไฟล์ภาพ
122
+ else:
123
+ # ประมวลผลหน้าเดียว
124
+ messages = prepare_ocr_messages(
125
+ pdf_or_image_path=orig_filename,
126
+ task_type=task_type,
127
+ target_image_dim=1800,
128
+ target_text_length=8000,
129
+ page_num=1
130
+ )
131
+
132
+ # ดึงภาพ
133
+ image_url = messages[0]["content"][1]["image_url"]["url"]
134
+ image_base64 = image_url.replace("data:image/png;base64,", "")
135
+ image_pil = Image.open(BytesIO(base64.b64decode(image_base64)))
136
+
137
+ # ส่งไป API
138
+ response = openai.chat.completions.create(
139
+ model=os.getenv("TYPHOON_OCR_MODEL"),
140
+ messages=messages,
141
+ max_tokens=16384,
142
+ extra_body={
143
+ "repetition_penalty": 1.2,
144
+ "temperature": 0.1,
145
+ "top_p": 0.6,
146
+ },
147
+ )
148
+ text_output = response.choices[0].message.content
149
+
150
+ # ดึง natural_text
151
+ try:
152
+ json_data = json.loads(text_output)
153
+ markdown_out = json_data.get('natural_text', "").replace("<figure>", "").replace("</figure>", "")
154
+ except Exception as e:
155
+ markdown_out = f"⚠️ Could not extract `natural_text` from output.\nError: {str(e)}"
156
+
157
+ # บันทึกผลลัพธ์ลงไฟล์
158
+ save_ocr_result(markdown_out)
159
+ return image_pil, markdown_out, gr.File.update(value=OUTPUT_FILE)
160
 
161
  except Exception as e:
162
  return None, f"Error processing file: {str(e)}", None
 
210
  font-size: 12px;
211
  }
212
  """
 
 
 
213
  # ปุ่มรัน
214
  run_button = gr.Button("🚀 Run")
215
 
 
226
  # เชื่อมต่อ UI กับฟังก์ชัน
227
  run_button.click(
228
  fn=process_pdf,
229
+ inputs=[pdf_input, task_dropdown],
230
  outputs=[image_output, markdown_output, download_button]
231
  )
232
 
233
+ # เริ่มต้นใหม่ (ล้างไฟล์ผลลัพธ์เก่า)
234
  clear_output_file()
235
 
236
  # รันแอป