Upload đồ_án_1_vietnamese_handwriting_ocr.py
Browse files
đồ_án_1_vietnamese_handwriting_ocr.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Đồ Án 1: Vietnamese Handwriting OCR
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1uop763iLeIFAxJrgOT0E00LyrK1tuXMH
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
!pip install gradio
|
| 11 |
+
!pip install zhipuai
|
| 12 |
+
|
| 13 |
+
import gradio as gr
|
| 14 |
+
import requests
|
| 15 |
+
import base64
|
| 16 |
+
import io
|
| 17 |
+
from PIL import Image
|
| 18 |
+
import numpy as np
|
| 19 |
+
from zhipuai import ZhipuAI
|
| 20 |
+
|
| 21 |
+
# Thay API Key của bạn tại đây
|
| 22 |
+
API_KEY = "d659608f7d5d42b1821a9303fc50b618.NesCuIytwpxjxpBJ"
|
| 23 |
+
|
| 24 |
+
# Khởi tạo ZhipuAI client
|
| 25 |
+
client = ZhipuAI(api_key=API_KEY)
|
| 26 |
+
|
| 27 |
+
def extract_text(image):
|
| 28 |
+
if isinstance(image, np.ndarray): # Chuyển NumPy array thành ảnh
|
| 29 |
+
image = Image.fromarray(image)
|
| 30 |
+
|
| 31 |
+
# Chuyển đổi ảnh sang Base64
|
| 32 |
+
buffered = io.BytesIO()
|
| 33 |
+
image.save(buffered, format="PNG")
|
| 34 |
+
image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 35 |
+
|
| 36 |
+
# Gửi yêu cầu đến GLM-4V
|
| 37 |
+
response = client.chat.completions.create(
|
| 38 |
+
model="glm-4v-plus",
|
| 39 |
+
messages=[
|
| 40 |
+
{
|
| 41 |
+
"role": "user",
|
| 42 |
+
"content": [
|
| 43 |
+
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_base64}"}},
|
| 44 |
+
{"type": "text", "text": "Hãy trích xuất toàn bộ chữ viết tay trong ảnh, giữ nguyên dấu câu, giữ dấu của từng chữ, khoảng cách dòng, và chính tả như trong ảnh."}
|
| 45 |
+
]
|
| 46 |
+
}
|
| 47 |
+
]
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# Xử lý phản hồi từ API
|
| 51 |
+
if response and response.choices:
|
| 52 |
+
text = response.choices[0].message.content
|
| 53 |
+
with open("output.md", "w", encoding="utf-8") as f:
|
| 54 |
+
f.write(text)
|
| 55 |
+
return text
|
| 56 |
+
else:
|
| 57 |
+
return "Lỗi: Không nhận được kết quả từ API."
|
| 58 |
+
|
| 59 |
+
# Giao diện Gradio
|
| 60 |
+
demo = gr.Interface(
|
| 61 |
+
fn=extract_text,
|
| 62 |
+
inputs="image",
|
| 63 |
+
outputs="text",
|
| 64 |
+
title="Vietnamese Handwriting OCR ",
|
| 65 |
+
description="Upload an image to extract handwritten text using ZhipuAI's GLM-4V model."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
demo.launch(debug=True)
|