Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,109 +7,138 @@ import gradio as gr
|
|
| 7 |
from ultralytics import YOLO
|
| 8 |
from paddleocr import PaddleOCR
|
| 9 |
|
| 10 |
-
# 1) Load models
|
| 11 |
yolo = YOLO("models/best.pt")
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
| 15 |
use_textline_orientation=False,
|
| 16 |
-
lang="en"
|
|
|
|
|
|
|
| 17 |
)
|
| 18 |
|
| 19 |
-
# 2) Turkish plate formatter
|
| 20 |
def format_turkish_plate(s: str) -> str:
|
| 21 |
s = re.sub(r'[^A-Z0-9]', '', s.upper())
|
| 22 |
m = re.match(r'^(\d{2})([A-Z]{1,3})(\d{2,4})$', s)
|
| 23 |
return f"{m.group(1)} {m.group(2)} {m.group(3)}" if m else "Unknown"
|
| 24 |
|
| 25 |
-
# 3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def run_image(img, conf=0.25):
|
|
|
|
| 27 |
bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
|
| 28 |
-
res = yolo(bgr, conf=conf)[0]
|
| 29 |
out = bgr.copy()
|
| 30 |
|
| 31 |
-
for box
|
| 32 |
-
|
| 33 |
-
x1,y1,x2,y2 = box.astype(int)
|
| 34 |
crop = out[y1:y2, x1:x2]
|
| 35 |
-
if crop.size==0:
|
| 36 |
-
|
| 37 |
-
plate_img = cv2.resize(crop, (128,32))
|
| 38 |
-
recs = ocr.ocr(plate_img, cls=False)
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
|
|
|
|
| 45 |
plate = format_turkish_plate(raw)
|
| 46 |
-
label = f"{plate} ({
|
| 47 |
|
| 48 |
-
|
| 49 |
-
cv2.
|
|
|
|
| 50 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
|
| 51 |
|
| 52 |
return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), f"{len(res.boxes)} plate(s) detected"
|
| 53 |
|
| 54 |
-
#
|
| 55 |
def run_video(video_file, conf=0.25):
|
| 56 |
cap = cv2.VideoCapture(video_file)
|
| 57 |
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 58 |
-
w
|
|
|
|
| 59 |
outfp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
|
| 60 |
writer = cv2.VideoWriter(outfp, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w,h))
|
| 61 |
-
records, idx = [], 0
|
| 62 |
|
|
|
|
|
|
|
| 63 |
while True:
|
| 64 |
ret, frame = cap.read()
|
| 65 |
-
if not ret:
|
| 66 |
-
|
| 67 |
-
|
|
|
|
| 68 |
|
| 69 |
res = yolo(frame, conf=conf)[0]
|
| 70 |
for (x1,y1,x2,y2) in res.boxes.xyxy.cpu().numpy().astype(int):
|
| 71 |
crop = frame[y1:y2, x1:x2]
|
| 72 |
-
if crop.size==0:
|
| 73 |
-
|
| 74 |
-
recs = ocr.ocr(plate_img, cls=False)
|
| 75 |
-
|
| 76 |
-
if recs and recs[0]:
|
| 77 |
-
_, (raw, ocr_score) = recs[0]
|
| 78 |
-
else:
|
| 79 |
-
raw, ocr_score = "", 0.0
|
| 80 |
|
|
|
|
|
|
|
|
|
|
| 81 |
plate = format_turkish_plate(raw)
|
| 82 |
if plate != "Unknown":
|
| 83 |
-
records.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
cv2.rectangle(frame, (x1,y1),(x2,y2), (0,255,0), 2)
|
| 86 |
-
cv2.putText(frame, plate, (x1,y1-5),
|
| 87 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
|
| 88 |
|
| 89 |
writer.write(frame)
|
| 90 |
|
| 91 |
-
cap.release()
|
|
|
|
| 92 |
with open("output.json","w") as f:
|
| 93 |
json.dump(records, f, indent=2)
|
| 94 |
-
return outfp
|
| 95 |
|
| 96 |
-
|
|
|
|
|
|
|
| 97 |
with gr.Blocks() as demo:
|
| 98 |
gr.Markdown("## π License Plate Detection + Recognition")
|
|
|
|
| 99 |
with gr.Row():
|
| 100 |
with gr.Column():
|
| 101 |
-
img_in = gr.Image(type="numpy")
|
| 102 |
-
vid_in = gr.File(label="Video (.mp4)")
|
| 103 |
-
conf = gr.Slider(0,1,0.25,0.01)
|
| 104 |
b1 = gr.Button("Run Image")
|
| 105 |
b2 = gr.Button("Run Video")
|
| 106 |
with gr.Column():
|
| 107 |
-
img_out = gr.Image(type="numpy")
|
| 108 |
-
vid_out = gr.Video()
|
| 109 |
-
status = gr.Textbox()
|
| 110 |
|
| 111 |
b1.click(run_image, [img_in,conf], [img_out,status])
|
| 112 |
b2.click(run_video, [vid_in,conf], [vid_out,status])
|
| 113 |
|
| 114 |
if __name__=="__main__":
|
| 115 |
-
demo.launch()
|
|
|
|
| 7 |
from ultralytics import YOLO
|
| 8 |
from paddleocr import PaddleOCR
|
| 9 |
|
| 10 |
+
# βββ 1) Load models βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
yolo = YOLO("models/best.pt")
|
| 12 |
+
|
| 13 |
+
# Recognition-only PaddleOCR: no det_model_dir, so ocr.ocr() only runs the recognizer + cls
|
| 14 |
+
ocr = PaddleOCR(
|
| 15 |
+
det_model_dir=None, # disable PaddleOCRβs own detector entirely
|
| 16 |
+
rec_model_dir="models/ocr_model", # your trained CRNN weights
|
| 17 |
use_textline_orientation=False,
|
| 18 |
+
lang="en",
|
| 19 |
+
use_angle_cls=True, # flip/rotation correction
|
| 20 |
+
use_space_char=True # allow spaces
|
| 21 |
)
|
| 22 |
|
| 23 |
+
# βββ 2) Turkish plate formatter ββββββββββββββββββββββββββββββββββββ
|
| 24 |
def format_turkish_plate(s: str) -> str:
|
| 25 |
s = re.sub(r'[^A-Z0-9]', '', s.upper())
|
| 26 |
m = re.match(r'^(\d{2})([A-Z]{1,3})(\d{2,4})$', s)
|
| 27 |
return f"{m.group(1)} {m.group(2)} {m.group(3)}" if m else "Unknown"
|
| 28 |
|
| 29 |
+
# βββ 3) Flatten OCR result & pick min confidence βββββββββββββββββββ
|
| 30 |
+
def parse_ocr(recs):
|
| 31 |
+
"""
|
| 32 |
+
recs from ocr.ocr(crop, cls=True) comes back as:
|
| 33 |
+
[ # list per text-line
|
| 34 |
+
[ <coords>, (<text>, <score>) ],
|
| 35 |
+
[ <coords>, (<text>, <score>) ],
|
| 36 |
+
...
|
| 37 |
+
]
|
| 38 |
+
We join all <text> pieces, and take the min score across them.
|
| 39 |
+
"""
|
| 40 |
+
if not recs or not recs[0]:
|
| 41 |
+
return "", 0.0
|
| 42 |
+
lines = recs[0]
|
| 43 |
+
texts = [line[1][0] for line in lines]
|
| 44 |
+
scores = [line[1][1] for line in lines]
|
| 45 |
+
return "".join(texts), float(min(scores))
|
| 46 |
+
|
| 47 |
+
# βββ 4) Single-image inference βββββββββββββββββββββββββββββββββββββ
|
| 48 |
def run_image(img, conf=0.25):
|
| 49 |
+
# convert to BGR for YOLO
|
| 50 |
bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
|
| 51 |
+
res = yolo(bgr, conf=conf)[0] # detect plates
|
| 52 |
out = bgr.copy()
|
| 53 |
|
| 54 |
+
for box in res.boxes.xyxy.cpu().numpy().astype(int):
|
| 55 |
+
x1,y1,x2,y2 = box
|
|
|
|
| 56 |
crop = out[y1:y2, x1:x2]
|
| 57 |
+
if crop.size == 0:
|
| 58 |
+
continue
|
|
|
|
|
|
|
| 59 |
|
| 60 |
+
# resize for CRNN
|
| 61 |
+
plate_img = cv2.resize(crop, (128, 32))
|
| 62 |
+
# recognize only (no internal detection)
|
| 63 |
+
recs = ocr.ocr(plate_img, cls=True)
|
| 64 |
|
| 65 |
+
raw, score = parse_ocr(recs)
|
| 66 |
plate = format_turkish_plate(raw)
|
| 67 |
+
label = f"{plate} ({score:.2f})"
|
| 68 |
|
| 69 |
+
# draw box + label
|
| 70 |
+
cv2.rectangle(out, (x1,y1), (x2,y2), (0,255,0), 2)
|
| 71 |
+
cv2.putText(out, label, (x1, y1-5),
|
| 72 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
|
| 73 |
|
| 74 |
return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), f"{len(res.boxes)} plate(s) detected"
|
| 75 |
|
| 76 |
+
# βββ 5) Video inference ββββββββββββββββββββββββββββββββββββββββββββ
|
| 77 |
def run_video(video_file, conf=0.25):
|
| 78 |
cap = cv2.VideoCapture(video_file)
|
| 79 |
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 80 |
+
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 81 |
+
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 82 |
outfp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
|
| 83 |
writer = cv2.VideoWriter(outfp, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w,h))
|
|
|
|
| 84 |
|
| 85 |
+
records = []
|
| 86 |
+
frame_idx = 0
|
| 87 |
while True:
|
| 88 |
ret, frame = cap.read()
|
| 89 |
+
if not ret:
|
| 90 |
+
break
|
| 91 |
+
frame_idx += 1
|
| 92 |
+
t = frame_idx / fps
|
| 93 |
|
| 94 |
res = yolo(frame, conf=conf)[0]
|
| 95 |
for (x1,y1,x2,y2) in res.boxes.xyxy.cpu().numpy().astype(int):
|
| 96 |
crop = frame[y1:y2, x1:x2]
|
| 97 |
+
if crop.size == 0:
|
| 98 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
plate_img = cv2.resize(crop, (128,32))
|
| 101 |
+
recs = ocr.ocr(plate_img, cls=True)
|
| 102 |
+
raw, score = parse_ocr(recs)
|
| 103 |
plate = format_turkish_plate(raw)
|
| 104 |
if plate != "Unknown":
|
| 105 |
+
records.append({
|
| 106 |
+
"time_s": round(t,2),
|
| 107 |
+
"plate": plate,
|
| 108 |
+
"conf": round(score,3)
|
| 109 |
+
})
|
| 110 |
|
| 111 |
cv2.rectangle(frame, (x1,y1),(x2,y2), (0,255,0), 2)
|
| 112 |
+
cv2.putText(frame, plate, (x1, y1-5),
|
| 113 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
|
| 114 |
|
| 115 |
writer.write(frame)
|
| 116 |
|
| 117 |
+
cap.release()
|
| 118 |
+
writer.release()
|
| 119 |
with open("output.json","w") as f:
|
| 120 |
json.dump(records, f, indent=2)
|
|
|
|
| 121 |
|
| 122 |
+
return outfp, "Done"
|
| 123 |
+
|
| 124 |
+
# βββ 6) Gradio UI ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 125 |
with gr.Blocks() as demo:
|
| 126 |
gr.Markdown("## π License Plate Detection + Recognition")
|
| 127 |
+
|
| 128 |
with gr.Row():
|
| 129 |
with gr.Column():
|
| 130 |
+
img_in = gr.Image(type="numpy", label="Upload Image")
|
| 131 |
+
vid_in = gr.File(label="Upload Video (.mp4)")
|
| 132 |
+
conf = gr.Slider(0,1,0.25,0.01, label="YOLO Confidence")
|
| 133 |
b1 = gr.Button("Run Image")
|
| 134 |
b2 = gr.Button("Run Video")
|
| 135 |
with gr.Column():
|
| 136 |
+
img_out = gr.Image(type="numpy", label="Annotated Image")
|
| 137 |
+
vid_out = gr.Video(label="Annotated Video")
|
| 138 |
+
status = gr.Textbox(label="Status / JSON Path")
|
| 139 |
|
| 140 |
b1.click(run_image, [img_in,conf], [img_out,status])
|
| 141 |
b2.click(run_video, [vid_in,conf], [vid_out,status])
|
| 142 |
|
| 143 |
if __name__=="__main__":
|
| 144 |
+
demo.launch()
|