Donyking1818 commited on
Commit
87f5018
·
verified ·
1 Parent(s): a745b67

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -48
app.py CHANGED
@@ -3,81 +3,88 @@ from transformers import AutoProcessor, AutoModelForImageTextToText
3
  import torch
4
  from PIL import Image
5
 
6
- # 1. Konfigurasi Model
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
- print(f"Loading model ke {device}...")
 
 
 
 
 
 
 
 
14
 
15
- # 2. Load Processor dan Model
 
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"Error loading model: {e}")
26
  raise e
27
 
28
- # 3. Fungsi Inferensi
29
  def run_ocr(image):
30
  if image is None:
31
- return "Tolong upload gambar dulu, Bro."
32
 
33
- # Format pesan khusus GLM-OCR
34
  messages = [
35
  {
36
  "role": "user",
37
  "content": [
38
- {
39
- "type": "image",
40
- "image": image, # Gradio ngasih format PIL Image
41
- },
42
- {
43
- "type": "text",
44
- "text": "Text Recognition:"
45
- }
46
  ],
47
  }
48
  ]
49
 
50
- # Proses input
51
- inputs = processor.apply_chat_template(
52
- messages,
53
- add_generation_prompt=True,
54
- return_dict=True,
55
- return_tensors="pt"
56
- ).to(model.device)
 
57
 
58
- # Generate (OCR)
59
- with torch.no_grad():
60
- generated_ids = model.generate(**inputs, max_new_tokens=2048) # Token bisa dinaikin kalo dokumen panjang
61
-
62
- # Decode hasil jadi teks
63
- output_text = processor.decode(generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
64
-
65
- return output_text
 
66
 
67
- # 4. Bikin Tampilan UI (Gradio)
68
- with gr.Blocks() as demo:
69
- gr.Markdown("# 👁️ GLM-OCR Demo")
70
- gr.Markdown("Upload gambar dokumen, surat, atau teks tulisan tangan. Model ini jago baca layout.")
71
 
72
  with gr.Row():
73
- with gr.Column():
74
- input_img = gr.Image(type="pil", label="Upload Gambar")
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
- btn_submit.click(fn=run_ocr, inputs=input_img, outputs=output_txt)
 
81
 
82
- # Jalankan App
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()