Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,81 +3,88 @@ from transformers import AutoProcessor, AutoModelForImageTextToText
|
|
| 3 |
import torch
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
-
# 1. Konfigurasi
|
| 7 |
-
# Pake CPU kalau gak ada GPU, pake cuda kalau ada
|
| 8 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 9 |
-
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
| 10 |
-
|
| 11 |
MODEL_PATH = "zai-org/GLM-OCR"
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
# 2. Load
|
|
|
|
| 16 |
try:
|
| 17 |
-
processor = AutoProcessor.from_pretrained(MODEL_PATH, trust_remote_code=True)
|
| 18 |
model = AutoModelForImageTextToText.from_pretrained(
|
| 19 |
MODEL_PATH,
|
| 20 |
torch_dtype=dtype,
|
| 21 |
device_map="auto",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
trust_remote_code=True
|
| 23 |
)
|
| 24 |
except Exception as e:
|
| 25 |
-
print(f"
|
| 26 |
raise e
|
| 27 |
|
| 28 |
-
# 3.
|
| 29 |
def run_ocr(image):
|
| 30 |
if image is None:
|
| 31 |
-
return "Tolong upload gambar dulu,
|
| 32 |
|
| 33 |
-
# Format
|
| 34 |
messages = [
|
| 35 |
{
|
| 36 |
"role": "user",
|
| 37 |
"content": [
|
| 38 |
-
{
|
| 39 |
-
|
| 40 |
-
"image": image, # Gradio ngasih format PIL Image
|
| 41 |
-
},
|
| 42 |
-
{
|
| 43 |
-
"type": "text",
|
| 44 |
-
"text": "Text Recognition:"
|
| 45 |
-
}
|
| 46 |
],
|
| 47 |
}
|
| 48 |
]
|
| 49 |
|
| 50 |
-
# Proses
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
| 66 |
|
| 67 |
-
# 4.
|
| 68 |
-
with gr.Blocks() as demo:
|
| 69 |
-
gr.Markdown("# 👁️ GLM-OCR Demo")
|
| 70 |
-
gr.Markdown("Upload gambar dokumen
|
| 71 |
|
| 72 |
with gr.Row():
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
btn_submit = gr.Button("Baca Teks (OCR)", variant="primary")
|
| 76 |
-
|
| 77 |
-
with gr.Column():
|
| 78 |
-
output_txt = gr.Textbox(label="Hasil Text / Markdown", lines=20)
|
| 79 |
|
| 80 |
-
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
-
demo.launch()
|
|
|
|
| 3 |
import torch
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
+
# 1. Konfigurasi
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
MODEL_PATH = "zai-org/GLM-OCR"
|
| 8 |
|
| 9 |
+
# Paksa deteksi device yang aman
|
| 10 |
+
if torch.cuda.is_available():
|
| 11 |
+
device = "cuda"
|
| 12 |
+
dtype = torch.float16
|
| 13 |
+
else:
|
| 14 |
+
device = "cpu"
|
| 15 |
+
dtype = torch.float32
|
| 16 |
+
|
| 17 |
+
print(f"⚡ Loading model ke: {device} dengan tipe data: {dtype}")
|
| 18 |
|
| 19 |
+
# 2. Load Model & Processor
|
| 20 |
+
# Kita load model dulu baru processor biar manajemen memori lebih rapi di Space gratisan
|
| 21 |
try:
|
|
|
|
| 22 |
model = AutoModelForImageTextToText.from_pretrained(
|
| 23 |
MODEL_PATH,
|
| 24 |
torch_dtype=dtype,
|
| 25 |
device_map="auto",
|
| 26 |
+
trust_remote_code=True,
|
| 27 |
+
low_cpu_mem_usage=True # IQ move buat hemat RAM
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# Kalo device cpu, pastikan model di float32
|
| 31 |
+
if device == "cpu":
|
| 32 |
+
model = model.float()
|
| 33 |
+
|
| 34 |
+
processor = AutoProcessor.from_pretrained(
|
| 35 |
+
MODEL_PATH,
|
| 36 |
trust_remote_code=True
|
| 37 |
)
|
| 38 |
except Exception as e:
|
| 39 |
+
print(f"❌ FATAL ERROR LOADING MODEL: {e}")
|
| 40 |
raise e
|
| 41 |
|
| 42 |
+
# 3. Logic Inferensi
|
| 43 |
def run_ocr(image):
|
| 44 |
if image is None:
|
| 45 |
+
return "⚠️ Tolong upload gambar dokumennya dulu, Bang."
|
| 46 |
|
| 47 |
+
# Format Prompt
|
| 48 |
messages = [
|
| 49 |
{
|
| 50 |
"role": "user",
|
| 51 |
"content": [
|
| 52 |
+
{"type": "image", "image": image},
|
| 53 |
+
{"type": "text", "text": "Text Recognition:"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
],
|
| 55 |
}
|
| 56 |
]
|
| 57 |
|
| 58 |
+
# Proses
|
| 59 |
+
try:
|
| 60 |
+
inputs = processor.apply_chat_template(
|
| 61 |
+
messages,
|
| 62 |
+
add_generation_prompt=True,
|
| 63 |
+
return_dict=True,
|
| 64 |
+
return_tensors="pt"
|
| 65 |
+
).to(model.device)
|
| 66 |
|
| 67 |
+
# Generate (Batasi token biar gak timeout di CPU)
|
| 68 |
+
with torch.no_grad():
|
| 69 |
+
generated_ids = model.generate(**inputs, max_new_tokens=1024, do_sample=False)
|
| 70 |
+
|
| 71 |
+
output_text = processor.decode(generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
|
| 72 |
+
return output_text
|
| 73 |
+
|
| 74 |
+
except Exception as e:
|
| 75 |
+
return f"Error saat proses OCR: {str(e)}"
|
| 76 |
|
| 77 |
+
# 4. Interface (Gradio)
|
| 78 |
+
with gr.Blocks(title="GLM-OCR by IQ 10M") as demo:
|
| 79 |
+
gr.Markdown("# 👁️ GLM-OCR Demo (CPU/GPU Friendly)")
|
| 80 |
+
gr.Markdown("Upload gambar dokumen. Sabar ya kalau pake CPU (Gratis), prosesnya agak lama.")
|
| 81 |
|
| 82 |
with gr.Row():
|
| 83 |
+
input_img = gr.Image(type="pil", label="Upload Disini", sources=["upload", "clipboard"])
|
| 84 |
+
output_txt = gr.TextArea(label="Hasil OCR", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
btn = gr.Button("🔍 Scan Dokumen", variant="primary")
|
| 87 |
+
btn.click(fn=run_ocr, inputs=input_img, outputs=output_txt)
|
| 88 |
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
demo.launch()
|