Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -9,17 +9,14 @@ import cv2
|
|
9 |
import numpy as np
|
10 |
from PIL import Image
|
11 |
import gradio as gr
|
12 |
-
from roboflow import Roboflow,
|
13 |
|
14 |
|
15 |
def parse_roboflow_url(url: str):
|
16 |
-
"""
|
17 |
-
Extract (workspace, project slug, version) from any Roboflow URL.
|
18 |
-
"""
|
19 |
parsed = urlparse(url)
|
20 |
parts = parsed.path.strip('/').split('/')
|
21 |
-
ws
|
22 |
-
proj
|
23 |
try:
|
24 |
ver = int(parts[-1])
|
25 |
except ValueError:
|
@@ -28,14 +25,13 @@ def parse_roboflow_url(url: str):
|
|
28 |
|
29 |
|
30 |
def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1, 0.1)):
|
31 |
-
|
32 |
-
rf = Roboflow(api_key=api_key)
|
33 |
workspace, proj_name, ver = parse_roboflow_url(dataset_url)
|
34 |
-
version_obj
|
35 |
-
dataset
|
36 |
-
root
|
37 |
|
38 |
-
#
|
39 |
ann_file = None
|
40 |
for dp, _, files in os.walk(root):
|
41 |
for f in files:
|
@@ -52,7 +48,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
52 |
cat_ids = sorted(c['id'] for c in coco.get('categories', []))
|
53 |
id_to_index = {cid: idx for idx, cid in enumerate(cat_ids)}
|
54 |
|
55 |
-
#
|
56 |
out_root = tempfile.mkdtemp(prefix="yolov8_")
|
57 |
flat_img = os.path.join(out_root, "flat_images")
|
58 |
flat_lbl = os.path.join(out_root, "flat_labels")
|
@@ -76,7 +72,6 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
76 |
)
|
77 |
annos.setdefault(img_id, []).append(line)
|
78 |
|
79 |
-
# --- map filenames to their disk paths
|
80 |
name_to_id = {img['file_name']: img['id'] for img in coco['images']}
|
81 |
file_paths = {}
|
82 |
for dp, _, files in os.walk(root):
|
@@ -84,7 +79,6 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
84 |
if f in name_to_id:
|
85 |
file_paths[f] = os.path.join(dp, f)
|
86 |
|
87 |
-
# --- copy images and write YOLO .txt labels
|
88 |
for fname, img_id in name_to_id.items():
|
89 |
src = file_paths.get(fname)
|
90 |
if not src:
|
@@ -93,7 +87,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
93 |
with open(os.path.join(flat_lbl, fname.rsplit('.',1)[0] + ".txt"), 'w') as lf:
|
94 |
lf.write("\n".join(annos.get(img_id, [])))
|
95 |
|
96 |
-
#
|
97 |
all_files = sorted(f for f in os.listdir(flat_img)
|
98 |
if f.lower().endswith(('.jpg','.png','.jpeg')))
|
99 |
random.shuffle(all_files)
|
@@ -108,7 +102,6 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
108 |
"test": all_files[n_train+n_valid:]
|
109 |
}
|
110 |
|
111 |
-
# --- arrange into Roboflow‑friendly folder tree
|
112 |
for split, files in splits.items():
|
113 |
idir = os.path.join(out_root, "images", split)
|
114 |
ldir = os.path.join(out_root, "labels", split)
|
@@ -124,7 +117,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
124 |
shutil.rmtree(flat_img)
|
125 |
shutil.rmtree(flat_lbl)
|
126 |
|
127 |
-
#
|
128 |
before, after = [], []
|
129 |
sample = random.sample(list(name_to_id.keys()), min(5, len(name_to_id)))
|
130 |
for fname in sample:
|
@@ -152,7 +145,6 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
152 |
before.append(Image.fromarray(seg_vis))
|
153 |
after.append(Image.fromarray(box_vis))
|
154 |
|
155 |
-
# return samples + local folder + the two slugs we need downstream
|
156 |
return before, after, out_root, proj_name + "-detection", workspace
|
157 |
|
158 |
|
@@ -167,11 +159,10 @@ def upload_and_train_detection(
|
|
167 |
rf = Roboflow(api_key=api_key)
|
168 |
ws = rf.workspace(workspace)
|
169 |
|
170 |
-
#
|
171 |
try:
|
172 |
proj = ws.project(project_slug)
|
173 |
-
except
|
174 |
-
# only create if truly “not found”
|
175 |
if "does not exist" in str(e):
|
176 |
proj = ws.create_project(
|
177 |
project_slug,
|
@@ -182,7 +173,7 @@ def upload_and_train_detection(
|
|
182 |
else:
|
183 |
raise
|
184 |
|
185 |
-
#
|
186 |
ws.upload_dataset(
|
187 |
dataset_path,
|
188 |
project_slug,
|
@@ -190,7 +181,6 @@ def upload_and_train_detection(
|
|
190 |
project_type=project_type
|
191 |
)
|
192 |
|
193 |
-
# --- spin up a new version and start training
|
194 |
version_num = proj.generate_version(settings={
|
195 |
"augmentation": {},
|
196 |
"preprocessing": {},
|
@@ -210,11 +200,9 @@ with gr.Blocks() as app:
|
|
210 |
run_btn = gr.Button("Convert to BBoxes")
|
211 |
before_g = gr.Gallery(columns=5, label="Before")
|
212 |
after_g = gr.Gallery(columns=5, label="After")
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
slug_state = gr.Textbox(visible=False) # project‑slug e.g. "myproj-detection"
|
217 |
-
ws_state = gr.Textbox(visible=False) # workspace name
|
218 |
|
219 |
run_btn.click(
|
220 |
convert_seg_to_bbox,
|
|
|
9 |
import numpy as np
|
10 |
from PIL import Image
|
11 |
import gradio as gr
|
12 |
+
from roboflow import Roboflow # removed RoboflowError, just import Roboflow
|
13 |
|
14 |
|
15 |
def parse_roboflow_url(url: str):
|
|
|
|
|
|
|
16 |
parsed = urlparse(url)
|
17 |
parts = parsed.path.strip('/').split('/')
|
18 |
+
ws = parts[0]
|
19 |
+
proj = parts[1]
|
20 |
try:
|
21 |
ver = int(parts[-1])
|
22 |
except ValueError:
|
|
|
25 |
|
26 |
|
27 |
def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1, 0.1)):
|
28 |
+
rf = Roboflow(api_key=api_key)
|
|
|
29 |
workspace, proj_name, ver = parse_roboflow_url(dataset_url)
|
30 |
+
version_obj = rf.workspace(workspace).project(proj_name).version(ver)
|
31 |
+
dataset = version_obj.download("coco-segmentation")
|
32 |
+
root = dataset.location
|
33 |
|
34 |
+
# find COCO JSON
|
35 |
ann_file = None
|
36 |
for dp, _, files in os.walk(root):
|
37 |
for f in files:
|
|
|
48 |
cat_ids = sorted(c['id'] for c in coco.get('categories', []))
|
49 |
id_to_index = {cid: idx for idx, cid in enumerate(cat_ids)}
|
50 |
|
51 |
+
# flatten & convert
|
52 |
out_root = tempfile.mkdtemp(prefix="yolov8_")
|
53 |
flat_img = os.path.join(out_root, "flat_images")
|
54 |
flat_lbl = os.path.join(out_root, "flat_labels")
|
|
|
72 |
)
|
73 |
annos.setdefault(img_id, []).append(line)
|
74 |
|
|
|
75 |
name_to_id = {img['file_name']: img['id'] for img in coco['images']}
|
76 |
file_paths = {}
|
77 |
for dp, _, files in os.walk(root):
|
|
|
79 |
if f in name_to_id:
|
80 |
file_paths[f] = os.path.join(dp, f)
|
81 |
|
|
|
82 |
for fname, img_id in name_to_id.items():
|
83 |
src = file_paths.get(fname)
|
84 |
if not src:
|
|
|
87 |
with open(os.path.join(flat_lbl, fname.rsplit('.',1)[0] + ".txt"), 'w') as lf:
|
88 |
lf.write("\n".join(annos.get(img_id, [])))
|
89 |
|
90 |
+
# split
|
91 |
all_files = sorted(f for f in os.listdir(flat_img)
|
92 |
if f.lower().endswith(('.jpg','.png','.jpeg')))
|
93 |
random.shuffle(all_files)
|
|
|
102 |
"test": all_files[n_train+n_valid:]
|
103 |
}
|
104 |
|
|
|
105 |
for split, files in splits.items():
|
106 |
idir = os.path.join(out_root, "images", split)
|
107 |
ldir = os.path.join(out_root, "labels", split)
|
|
|
117 |
shutil.rmtree(flat_img)
|
118 |
shutil.rmtree(flat_lbl)
|
119 |
|
120 |
+
# prepare visuals
|
121 |
before, after = [], []
|
122 |
sample = random.sample(list(name_to_id.keys()), min(5, len(name_to_id)))
|
123 |
for fname in sample:
|
|
|
145 |
before.append(Image.fromarray(seg_vis))
|
146 |
after.append(Image.fromarray(box_vis))
|
147 |
|
|
|
148 |
return before, after, out_root, proj_name + "-detection", workspace
|
149 |
|
150 |
|
|
|
159 |
rf = Roboflow(api_key=api_key)
|
160 |
ws = rf.workspace(workspace)
|
161 |
|
162 |
+
# get‑or‑create project by inspecting exception text
|
163 |
try:
|
164 |
proj = ws.project(project_slug)
|
165 |
+
except Exception as e:
|
|
|
166 |
if "does not exist" in str(e):
|
167 |
proj = ws.create_project(
|
168 |
project_slug,
|
|
|
173 |
else:
|
174 |
raise
|
175 |
|
176 |
+
# upload & train
|
177 |
ws.upload_dataset(
|
178 |
dataset_path,
|
179 |
project_slug,
|
|
|
181 |
project_type=project_type
|
182 |
)
|
183 |
|
|
|
184 |
version_num = proj.generate_version(settings={
|
185 |
"augmentation": {},
|
186 |
"preprocessing": {},
|
|
|
200 |
run_btn = gr.Button("Convert to BBoxes")
|
201 |
before_g = gr.Gallery(columns=5, label="Before")
|
202 |
after_g = gr.Gallery(columns=5, label="After")
|
203 |
+
ds_state = gr.Textbox(visible=False)
|
204 |
+
slug_state = gr.Textbox(visible=False)
|
205 |
+
ws_state = gr.Textbox(visible=False)
|
|
|
|
|
206 |
|
207 |
run_btn.click(
|
208 |
convert_seg_to_bbox,
|