Update app.py
Browse files4 unmodified lines56789101150 unmodified lines62636465666768697071727374751 unmodified line777879808182832 unmodified lines8687888990919220 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391404 unmodified linesimport base64from pathlib import Path# 1. โหลดโมเดล OpenThai 2.0 จาก Hugging Face อัตโนมัติ (ขนาดจิ๋ว ~4 MB)from huggingface_hub import snapshot_downloadprint("Downloading / verifying OpenThai 2.0 OCR Text model...")50 unmodified lines"elapsed": elapsed}# 2. ทำ REST API รองรับการยิงจาก Vercelfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewareimport gradio as grapi_app = FastAPI()api_app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,1 unmodified lineallow_headers=["*"],)@api_app.get("/health")def health():return {"status": "ready",2 unmodified lines"device": "CPU"}@api_app.post("/ocr")async def ocr_endpoint(request: Request):try:body = await request.json()20 unmodified linesexcept Exception as e:return {"success": False, "error": str(e)}# 3. หน้าตาหน้าเว็บ Gradio สำหรับทดสอบผ่านเบราว์เซอร์def gradio_ocr_handler(file):if file is None:return "กรุณาอัปโหลดไฟล์ PDF หรือรูปภาพ"filepath = file.name if hasattr(file, "name") else filewith open(filepath, "rb") as f:data = f.read()if filepath.lower().endswith(".pdf") or data.startswith(b"%PDF"):res = process_pdf_bytes(data)else:res = process_image_bytes(data)return res.get("text", "")with gr.Blocks(title="OpenThai 2.0 OCR Engine") as demo:gr.Markdown("# 🇹🇭 OpenThai 2.0 OCR Text Engine (iApp)")gr.Markdown("โมเดลอ่านเอกสารภาษาไทยและอังกฤษความเร็วสูง (~0.39 วินาที/หน้า) รันบน CPU ฟรี 100%")with gr.Row():with gr.Column():file_input = gr.File(label="อัปโหลดไฟล์ PDF หรือรูปภาพผลตรวจ", file_types=[".pdf", ".png", ".jpg", ".jpeg"])btn = gr.Button("⚡ ดึงข้อความภาษาไทย (OCR)", variant="primary")with gr.Column():text_output = gr.Textbox(label="ข้อความที่สกัดได้ (Text Output)", lines=18)btn.click(fn=gradio_ocr_handler, inputs=file_input, outputs=text_output)app = gr.mount_gradio_app(api_app, demo, path="/")4 unmodified lines56789101150 unmodified lines6263646566676869707172737475767778798081828384858687888990919293949596971 unmodified line991001011021031041052 unmodified lines10810911011111211311420 unmodified lines1351361371381391404 unmodified linesimport base64from pathlib import Path# 1. โหลดโมเดล OpenThai 2.0 จาก Hugging Face อัตโนมัติfrom huggingface_hub import snapshot_downloadprint("Downloading / verifying OpenThai 2.0 OCR Text model...")50 unmodified lines"elapsed": elapsed}# 2. ทำหน้าเว็บ Gradio UI สำหรับทดสอบผ่านเบราว์เซอร์import gradio as grfrom fastapi import Requestfrom fastapi.middleware.cors import CORSMiddlewaredef gradio_ocr_handler(file):if file is None:return "กรุณาอัปโหลดไฟล์ PDF หรือรูปภาพ"filepath = file.name if hasattr(file, "name") else filewith open(filepath, "rb") as f:data = f.read()if filepath.lower().endswith(".pdf") or data.startswith(b"%PDF"):res = process_pdf_bytes(data)else:res = process_image_bytes(data)return res.get("text", "")with gr.Blocks(title="OpenThai 2.0 OCR Engine") as demo:gr.Markdown("# 🇹🇭 OpenThai 2.0 OCR Text Engine (iApp)")gr.Markdown("โมเดลอ่านเอกสารภาษาไทยและอังกฤษความเร็วสูง (~0.39 วินาที/หน้า) รันบน CPU ฟรี 100%")with gr.Row():with gr.Column():file_input = gr.File(label="อัปโหลดไฟล์ PDF หรือรูปภาพผลตรวจ", file_types=[".pdf", ".png", ".jpg", ".jpeg"])btn = gr.Button("⚡ ดึงข้อความภาษาไทย (OCR)", variant="primary")with gr.Column():text_output = gr.Textbox(label="ข้อความที่สกัดได้ (Text Output)", lines=18)btn.click(fn=gradio_ocr_handler, inputs=file_input, outputs=text_output)# 3. แนบ REST API สำหรับให้ Vercel ยิงเข้ามาที่ /health และ /ocrdemo.app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,1 unmodified lineallow_headers=["*"],)@demo.app.get("/health")def health():return {"status": "ready",2 unmodified lines"device": "CPU"}@demo.app.post("/ocr")async def ocr_endpoint(request: Request):try:body = await request.json()20 unmodified linesexcept Exception as e:return {"success": False, "error": str(e)}# 4. สั่ง launch เพื่อเปิดเซิร์ฟเวอร์ค้างไว้ที่พอร์ต 7860if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)
app.py+33-33