lerpong commited on
Commit
c9e96af
·
verified ·
1 Parent(s): 3f0f7f4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -33
app.py CHANGED
@@ -5,7 +5,7 @@ import time
5
  import base64
6
  from pathlib import Path
7
 
8
- # 1. โหลดโมเดล OpenThai 2.0 จาก Hugging Face อัตโนมัติ (ขนาดจิ๋ว ~4 MB)
9
  from huggingface_hub import snapshot_download
10
 
11
  print("Downloading / verifying OpenThai 2.0 OCR Text model...")
@@ -62,14 +62,36 @@ def process_pdf_bytes(pdf_bytes: bytes) -> dict:
62
  "elapsed": elapsed
63
  }
64
 
65
- # 2. ทำ REST API รองรับการยิงจาก Vercel
66
- from fastapi import FastAPI, Request
67
- from fastapi.middleware.cors import CORSMiddleware
68
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- api_app = FastAPI()
 
 
 
 
 
 
 
 
 
71
 
72
- api_app.add_middleware(
 
73
  CORSMiddleware,
74
  allow_origins=["*"],
75
  allow_credentials=True,
@@ -77,7 +99,7 @@ api_app.add_middleware(
77
  allow_headers=["*"],
78
  )
79
 
80
- @api_app.get("/health")
81
  def health():
82
  return {
83
  "status": "ready",
@@ -86,7 +108,7 @@ def health():
86
  "device": "CPU"
87
  }
88
 
89
- @api_app.post("/ocr")
90
  async def ocr_endpoint(request: Request):
91
  try:
92
  body = await request.json()
@@ -113,28 +135,6 @@ async def ocr_endpoint(request: Request):
113
  except Exception as e:
114
  return {"success": False, "error": str(e)}
115
 
116
- # 3. หน้าตาหน้าเว็บ Gradio สำหรับทดสอบผ่านเบราว์เซอร์
117
- def gradio_ocr_handler(file):
118
- if file is None:
119
- return "กรุณาอัปโหลดไฟล์ PDF หรือรูปภาพ"
120
- filepath = file.name if hasattr(file, "name") else file
121
- with open(filepath, "rb") as f:
122
- data = f.read()
123
- if filepath.lower().endswith(".pdf") or data.startswith(b"%PDF"):
124
- res = process_pdf_bytes(data)
125
- else:
126
- res = process_image_bytes(data)
127
- return res.get("text", "")
128
-
129
- with gr.Blocks(title="OpenThai 2.0 OCR Engine") as demo:
130
- gr.Markdown("# 🇹🇭 OpenThai 2.0 OCR Text Engine (iApp)")
131
- gr.Markdown("โมเดลอ่านเอกสารภาษาไทยและอังกฤษความเร็วสูง (~0.39 วินาที/หน้า) รันบน CPU ฟรี 100%")
132
- with gr.Row():
133
- with gr.Column():
134
- file_input = gr.File(label="อัปโหลดไฟล์ PDF หรือรูปภาพผลตรวจ", file_types=[".pdf", ".png", ".jpg", ".jpeg"])
135
- btn = gr.Button("⚡ ดึงข้อความภาษาไทย (OCR)", variant="primary")
136
- with gr.Column():
137
- text_output = gr.Textbox(label="ข้อความที่สกัดได้ (Text Output)", lines=18)
138
- btn.click(fn=gradio_ocr_handler, inputs=file_input, outputs=text_output)
139
-
140
- app = gr.mount_gradio_app(api_app, demo, path="/")
 
5
  import base64
6
  from pathlib import Path
7
 
8
+ # 1. โหลดโมเดล OpenThai 2.0 จาก Hugging Face อัตโนมัติ
9
  from huggingface_hub import snapshot_download
10
 
11
  print("Downloading / verifying OpenThai 2.0 OCR Text model...")
 
62
  "elapsed": elapsed
63
  }
64
 
65
+ # 2. ทำหน้าเว็บ Gradio UI สำหรับทดสอบผ่านเบราว์เซอร์
 
 
66
  import gradio as gr
67
+ from fastapi import Request
68
+ from fastapi.middleware.cors import CORSMiddleware
69
+
70
+ def gradio_ocr_handler(file):
71
+ if file is None:
72
+ return "กรุณาอัปโหลดไฟล์ PDF หรือรูปภาพ"
73
+ filepath = file.name if hasattr(file, "name") else file
74
+ with open(filepath, "rb") as f:
75
+ data = f.read()
76
+ if filepath.lower().endswith(".pdf") or data.startswith(b"%PDF"):
77
+ res = process_pdf_bytes(data)
78
+ else:
79
+ res = process_image_bytes(data)
80
+ return res.get("text", "")
81
 
82
+ with gr.Blocks(title="OpenThai 2.0 OCR Engine") as demo:
83
+ gr.Markdown("# 🇹🇭 OpenThai 2.0 OCR Text Engine (iApp)")
84
+ gr.Markdown("โมเดลอ่านเอกสารภาษาไทยและอังกฤษความเร็วสูง (~0.39 วินาที/หน้า) รันบน CPU ฟรี 100%")
85
+ with gr.Row():
86
+ with gr.Column():
87
+ file_input = gr.File(label="อัปโหลดไฟล์ PDF หรือรูปภาพผลตรวจ", file_types=[".pdf", ".png", ".jpg", ".jpeg"])
88
+ btn = gr.Button("⚡ ดึงข้อความภาษาไทย (OCR)", variant="primary")
89
+ with gr.Column():
90
+ text_output = gr.Textbox(label="ข้อความที่สกัดได้ (Text Output)", lines=18)
91
+ btn.click(fn=gradio_ocr_handler, inputs=file_input, outputs=text_output)
92
 
93
+ # 3. แนบ REST API สำหรับให้ Vercel ยิงเข้ามาที่ /health และ /ocr
94
+ demo.app.add_middleware(
95
  CORSMiddleware,
96
  allow_origins=["*"],
97
  allow_credentials=True,
 
99
  allow_headers=["*"],
100
  )
101
 
102
+ @demo.app.get("/health")
103
  def health():
104
  return {
105
  "status": "ready",
 
108
  "device": "CPU"
109
  }
110
 
111
+ @demo.app.post("/ocr")
112
  async def ocr_endpoint(request: Request):
113
  try:
114
  body = await request.json()
 
135
  except Exception as e:
136
  return {"success": False, "error": str(e)}
137
 
138
+ # 4. สั่ง launch เพื่อเปิดเซิร์ฟเวอร์ค้างไว้ที่พอร์ต 7860
139
+ if __name__ == "__main__":
140
+ demo.launch(server_name="0.0.0.0", server_port=7860)