muddasser commited on
Commit
a76e52e
·
verified ·
1 Parent(s): 9e47172

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -45
app.py CHANGED
@@ -1,54 +1,19 @@
1
  import torch
2
  from ultralytics import YOLO
3
  import gradio as gr
4
- import easyocr
5
- import numpy as np
6
- from PIL import Image
7
- import ultralytics.nn.tasks as tasks
8
 
9
- # Allowlist the YOLOv8 DetectionModel class so PyTorch 2.6 can unpickle it safely
10
- torch.serialization.add_safe_globals([tasks.DetectionModel])
11
 
12
- # Load YOLO model (trusted official weights from Ultralytics)
13
- WEIGHTS_PATH = "yolov8n.pt" # Should be in your Space folder or auto-downloaded
14
- model = YOLO(WEIGHTS_PATH, task="detect")
15
 
16
- # Initialize EasyOCR
17
- reader = easyocr.Reader(['en'], gpu=False)
18
 
19
- def detect_and_read(image):
20
- # Run YOLO detection
21
  results = model(image)
22
- detections = results[0].boxes.xyxy.cpu().numpy() # x1, y1, x2, y2
23
- labels = results[0].names
24
-
25
- output_data = []
26
- img_pil = Image.fromarray(image)
27
-
28
- for i, box in enumerate(detections):
29
- x1, y1, x2, y2 = [int(v) for v in box[:4]]
30
- cropped_img = img_pil.crop((x1, y1, x2, y2))
31
-
32
- # OCR
33
- ocr_result = reader.readtext(np.array(cropped_img))
34
- text = " ".join([res[1] for res in ocr_result])
35
-
36
- output_data.append({
37
- "bbox": (x1, y1, x2, y2),
38
- "label": labels[int(results[0].boxes.cls[i])],
39
- "text": text
40
- })
41
-
42
- return output_data
43
-
44
- # Gradio UI
45
- demo = gr.Interface(
46
- fn=detect_and_read,
47
- inputs=gr.Image(type="numpy"),
48
- outputs="json",
49
- title="YOLOv8 + EasyOCR",
50
- description="Object detection with YOLOv8 and OCR with EasyOCR"
51
- )
52
 
53
- if __name__ == "__main__":
54
- demo.launch()
 
1
  import torch
2
  from ultralytics import YOLO
3
  import gradio as gr
 
 
 
 
4
 
5
+ # Trusted YOLO weights path
6
+ WEIGHTS_PATH = "/app/yolov8n.pt"
7
 
8
+ # Allow loading full model (Option 1 from error)
9
+ torch.serialization.add_safe_globals([YOLO])
 
10
 
11
+ model = YOLO(WEIGHTS_PATH, task="detect")
 
12
 
13
+ def detect_objects(image):
 
14
  results = model(image)
15
+ annotated = results[0].plot()
16
+ return annotated
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ demo = gr.Interface(fn=detect_objects, inputs="image", outputs="image")
19
+ demo.launch(server_name="0.0.0.0", server_port=7860)