Beat03 commited on
Commit
e2c5a1e
·
verified ·
1 Parent(s): ad3e865

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +65 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import base64
4
+ import io
5
+ from PIL import Image
6
+ import numpy as np
7
+ from zhipuai import ZhipuAI
8
+
9
+ # Thay API Key của bạn tại đây
10
+ API_KEY = "d659608f7d5d42b1821a9303fc50b618.NesCuIytwpxjxpBJ"
11
+
12
+ # Khởi tạo ZhipuAI client
13
+ client = ZhipuAI(api_key=API_KEY)
14
+
15
+ def extract_text(image):
16
+ if isinstance(image, np.ndarray): # Chuyển NumPy array thành ảnh
17
+ image = Image.fromarray(image)
18
+
19
+ # Chuyển đổi ảnh sang Base64
20
+ buffered = io.BytesIO()
21
+ image.save(buffered, format="PNG")
22
+ image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
23
+
24
+ # Gửi yêu cầu đến GLM-4V
25
+ response = client.chat.completions.create(
26
+ model="glm-4v-plus",
27
+ messages=[
28
+ {
29
+ "role": "user",
30
+ "content": [
31
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_base64}"}},
32
+ {"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."}
33
+ ]
34
+ }
35
+ ]
36
+ )
37
+
38
+ # Xử lý phản hồi từ API
39
+ if response and response.choices:
40
+ text = response.choices[0].message.content
41
+ output_text_file = "output.md"
42
+ with open(output_text_file, "w", encoding="utf-8") as f:
43
+ f.write(text)
44
+
45
+ output_image_file = "output_image.png"
46
+ image.save(output_image_file, format="PNG")
47
+
48
+ return text, output_text_file, output_image_file
49
+ else:
50
+ return "Lỗi: Không nhận được kết quả từ API.", None, None
51
+
52
+ demo = gr.Interface(
53
+ fn=extract_text,
54
+ inputs="image",
55
+ outputs=[
56
+ "text",
57
+ gr.File(label="Tải xuống file văn bản (output.md)"),
58
+ gr.File(label="Tải xuống ảnh gốc (output_image.png)")
59
+ ],
60
+ title="Vietnamese Handwriting OCR",
61
+ description="Upload an image to extract handwritten text using ZhipuAI's GLM-4V model."
62
+ )
63
+
64
+ if __name__ == "__main__":
65
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ zhipuai
3
+ pillow
4
+ numpy
5
+ requests