Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -17,7 +17,7 @@ def parse_roboflow_url(url: str):
|
|
17 |
parsed = urlparse(url)
|
18 |
parts = parsed.path.strip('/').split('/')
|
19 |
workspace = parts[0]
|
20 |
-
project
|
21 |
try:
|
22 |
version = int(parts[-1])
|
23 |
except ValueError:
|
@@ -71,8 +71,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
71 |
)
|
72 |
annos.setdefault(img_id, []).append(line)
|
73 |
|
74 |
-
#
|
75 |
-
out_root = tempfile.mkdtemp(prefix="yolov8_")
|
76 |
name_to_id = {img['file_name']: img['id'] for img in coco['images']}
|
77 |
file_paths = {
|
78 |
f: os.path.join(dp, f)
|
@@ -81,7 +80,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
81 |
if f in name_to_id
|
82 |
}
|
83 |
|
84 |
-
#
|
85 |
all_files = list(name_to_id.keys())
|
86 |
random.shuffle(all_files)
|
87 |
n = len(all_files)
|
@@ -94,7 +93,12 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
94 |
"test": all_files[n_train+n_valid:]
|
95 |
}
|
96 |
|
97 |
-
# create Roboflow‐style
|
|
|
|
|
|
|
|
|
|
|
98 |
for split, files in splits.items():
|
99 |
img_dir = os.path.join(out_root, split, "images")
|
100 |
lbl_dir = os.path.join(out_root, split, "labels")
|
@@ -108,19 +112,17 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
108 |
with open(os.path.join(lbl_dir, fname.rsplit('.',1)[0] + ".txt"), 'w') as f:
|
109 |
f.write(txt)
|
110 |
|
111 |
-
# prepare
|
112 |
before, after = [], []
|
113 |
sample = random.sample(all_files, min(5, len(all_files)))
|
114 |
for fname in sample:
|
115 |
img = cv2.cvtColor(cv2.imread(file_paths[fname]), cv2.COLOR_BGR2RGB)
|
116 |
-
|
117 |
seg_vis = img.copy()
|
118 |
for anno in coco['annotations']:
|
119 |
if anno['image_id'] != name_to_id[fname]:
|
120 |
continue
|
121 |
pts = np.array(anno['segmentation'][0], np.int32).reshape(-1,2)
|
122 |
cv2.polylines(seg_vis, [pts], True, (255,0,0), 2)
|
123 |
-
|
124 |
box_vis = img.copy()
|
125 |
for line in annos.get(name_to_id[fname], []):
|
126 |
_, cxn, cyn, wnorm, hnorm = map(float, line.split())
|
@@ -129,7 +131,6 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str, split_ratios=(0.8, 0.1,
|
|
129 |
x0 = int(cxn*iw - w0/2)
|
130 |
y0 = int(cyn*ih - h0/2)
|
131 |
cv2.rectangle(box_vis, (x0,y0), (x0+w0,y0+h0), (0,255,0), 2)
|
132 |
-
|
133 |
before.append(Image.fromarray(seg_vis))
|
134 |
after.append(Image.fromarray(box_vis))
|
135 |
|
@@ -145,14 +146,14 @@ def upload_and_train_detection(
|
|
145 |
project_type: str = "object-detection"
|
146 |
):
|
147 |
"""
|
148 |
-
Uploads
|
149 |
-
creates
|
150 |
-
Returns the hosted
|
151 |
"""
|
152 |
rf = Roboflow(api_key=api_key)
|
153 |
ws = rf.workspace()
|
154 |
|
155 |
-
# get
|
156 |
try:
|
157 |
proj = ws.project(detection_slug)
|
158 |
except Exception as e:
|
@@ -175,7 +176,7 @@ def upload_and_train_detection(
|
|
175 |
project_type=project_type
|
176 |
)
|
177 |
|
178 |
-
# generate new version (with fallback)
|
179 |
try:
|
180 |
version_num = proj.generate_version(settings={"augmentation": {}, "preprocessing": {}})
|
181 |
except RuntimeError as e:
|
@@ -195,7 +196,7 @@ def upload_and_train_detection(
|
|
195 |
else:
|
196 |
raise
|
197 |
|
198 |
-
# wait
|
199 |
for _ in range(20):
|
200 |
try:
|
201 |
model = proj.version(str(version_num)).train()
|
|
|
17 |
parsed = urlparse(url)
|
18 |
parts = parsed.path.strip('/').split('/')
|
19 |
workspace = parts[0]
|
20 |
+
project = parts[1]
|
21 |
try:
|
22 |
version = int(parts[-1])
|
23 |
except ValueError:
|
|
|
71 |
)
|
72 |
annos.setdefault(img_id, []).append(line)
|
73 |
|
74 |
+
# gather all filenames and paths
|
|
|
75 |
name_to_id = {img['file_name']: img['id'] for img in coco['images']}
|
76 |
file_paths = {
|
77 |
f: os.path.join(dp, f)
|
|
|
80 |
if f in name_to_id
|
81 |
}
|
82 |
|
83 |
+
# split filenames
|
84 |
all_files = list(name_to_id.keys())
|
85 |
random.shuffle(all_files)
|
86 |
n = len(all_files)
|
|
|
93 |
"test": all_files[n_train+n_valid:]
|
94 |
}
|
95 |
|
96 |
+
# create Roboflow‐style dataset folder:
|
97 |
+
# out_root/
|
98 |
+
# train/images, train/labels,
|
99 |
+
# valid/images, valid/labels,
|
100 |
+
# test/images, test/labels
|
101 |
+
out_root = tempfile.mkdtemp(prefix="yolov8_")
|
102 |
for split, files in splits.items():
|
103 |
img_dir = os.path.join(out_root, split, "images")
|
104 |
lbl_dir = os.path.join(out_root, split, "labels")
|
|
|
112 |
with open(os.path.join(lbl_dir, fname.rsplit('.',1)[0] + ".txt"), 'w') as f:
|
113 |
f.write(txt)
|
114 |
|
115 |
+
# prepare a few before/after examples
|
116 |
before, after = [], []
|
117 |
sample = random.sample(all_files, min(5, len(all_files)))
|
118 |
for fname in sample:
|
119 |
img = cv2.cvtColor(cv2.imread(file_paths[fname]), cv2.COLOR_BGR2RGB)
|
|
|
120 |
seg_vis = img.copy()
|
121 |
for anno in coco['annotations']:
|
122 |
if anno['image_id'] != name_to_id[fname]:
|
123 |
continue
|
124 |
pts = np.array(anno['segmentation'][0], np.int32).reshape(-1,2)
|
125 |
cv2.polylines(seg_vis, [pts], True, (255,0,0), 2)
|
|
|
126 |
box_vis = img.copy()
|
127 |
for line in annos.get(name_to_id[fname], []):
|
128 |
_, cxn, cyn, wnorm, hnorm = map(float, line.split())
|
|
|
131 |
x0 = int(cxn*iw - w0/2)
|
132 |
y0 = int(cyn*ih - h0/2)
|
133 |
cv2.rectangle(box_vis, (x0,y0), (x0+w0,y0+h0), (0,255,0), 2)
|
|
|
134 |
before.append(Image.fromarray(seg_vis))
|
135 |
after.append(Image.fromarray(box_vis))
|
136 |
|
|
|
146 |
project_type: str = "object-detection"
|
147 |
):
|
148 |
"""
|
149 |
+
Uploads the converted dataset (with train/valid/test splits) to Roboflow,
|
150 |
+
creates or fetches a detection project, and kicks off training.
|
151 |
+
Returns the hosted model URL.
|
152 |
"""
|
153 |
rf = Roboflow(api_key=api_key)
|
154 |
ws = rf.workspace()
|
155 |
|
156 |
+
# get or create project
|
157 |
try:
|
158 |
proj = ws.project(detection_slug)
|
159 |
except Exception as e:
|
|
|
176 |
project_type=project_type
|
177 |
)
|
178 |
|
179 |
+
# generate new version (with fallback slug bump)
|
180 |
try:
|
181 |
version_num = proj.generate_version(settings={"augmentation": {}, "preprocessing": {}})
|
182 |
except RuntimeError as e:
|
|
|
196 |
else:
|
197 |
raise
|
198 |
|
199 |
+
# wait for generation, then train
|
200 |
for _ in range(20):
|
201 |
try:
|
202 |
model = proj.version(str(version_num)).train()
|