wuhp commited on
Commit
533c19c
Β·
verified Β·
1 Parent(s): a711e94

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -24
app.py CHANGED
@@ -27,9 +27,9 @@ def parse_roboflow_url(url: str):
27
 
28
  def convert_seg_to_bbox(api_key: str, dataset_url: str):
29
  """
30
- 1) Download segmentation dataset from Roboflow
31
- 2) Convert masks β†’ YOLOv8 bboxes
32
- Returns before_gallery, after_gallery, local_dataset_path, project_slug
33
  """
34
  rf = Roboflow(api_key=api_key)
35
  ws, proj, ver = parse_roboflow_url(dataset_url)
@@ -85,7 +85,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str):
85
  # locate images and write labels
86
  img_dir = None
87
  for dp, _, files in os.walk(root):
88
- if any(f.lower().endswith(('.jpg','.png','jpeg')) for f in files):
89
  img_dir = dp
90
  break
91
  if not img_dir:
@@ -97,7 +97,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str):
97
  if not os.path.isfile(src):
98
  continue
99
  shutil.copy(src, os.path.join(img_out, fname))
100
- with open(os.path.join(lbl_out, fname.rsplit('.',1)[0] + ".txt"), 'w') as lf:
101
  lf.write("\n".join(annos.get(pid, [])))
102
 
103
  # build preview galleries
@@ -110,54 +110,61 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str):
110
  for a in coco['annotations']:
111
  if a['image_id'] != fname2id[fn]:
112
  continue
113
- pts = np.array(a['segmentation'][0], np.int32).reshape(-1,2)
114
- cv2.polylines(seg_vis, [pts], True, (255,0,0), 2)
115
 
116
  box_vis = img.copy()
117
  for line in annos.get(fname2id[fn], []):
118
  _, cxn, cyn, wnorm, hnorm = map(float, line.split())
119
  iw, ih = images_info[fname2id[fn]]['width'], images_info[fname2id[fn]]['height']
120
- w0, h0 = int(wnorm*iw), int(hnorm*ih)
121
- x0, y0 = int(cxn*iw - w0/2), int(cyn*ih - h0/2)
122
- cv2.rectangle(box_vis, (x0,y0), (x0+w0,y0+h0), (0,255,0), 2)
123
 
124
  before.append(Image.fromarray(seg_vis))
125
  after.append(Image.fromarray(box_vis))
126
 
127
- return before, after, out_root, proj # proj is our slug
 
128
 
129
 
130
  def upload_and_train_detection(api_key: str, project_slug: str, dataset_path: str):
131
  """
132
- 1) Upload local YOLOv8 dataset to Roboflow
133
- 2) Generate & train a new detection version
134
- Returns the hosted inference endpoint URL.
135
  """
136
  rf = Roboflow(api_key=api_key)
137
  ws = rf.workspace()
138
 
139
- # upload dataset
140
  ws.upload_dataset(
141
  dataset_path,
142
  project_slug,
 
143
  project_license="MIT",
144
- project_type="object-detection"
 
 
145
  )
146
 
147
- # generate a new version
148
  proj = ws.project(project_slug)
149
- version_number = proj.generate_version(preprocessing={}, augmentation={})
 
 
 
150
 
151
- # train model (fast)
152
- proj.version(version_number).train(speed="fast")
 
153
 
154
- # fetch hosted endpoint
155
- m = proj.version(str(version_number)).model
156
  return f"{m['base_url']}{m['id']}?api_key={api_key}"
157
 
158
 
159
  with gr.Blocks() as app:
160
- gr.Markdown("## πŸ”„ Segmentation β†’ YOLOv8 Converter + Auto Trainer")
161
 
162
  # Converter UI
163
  api_input = gr.Textbox(label="Roboflow API Key", type="password")
@@ -174,7 +181,7 @@ with gr.Blocks() as app:
174
  outputs=[before_gal, after_gal, state_path, state_slug]
175
  )
176
 
177
- # Train UI
178
  train_btn = gr.Button("Upload & Train Detection Model")
179
  endpoint_text = gr.Textbox(label="Hosted Detection Endpoint URL")
180
 
 
27
 
28
  def convert_seg_to_bbox(api_key: str, dataset_url: str):
29
  """
30
+ Download segmentation dataset from Roboflow,
31
+ convert masks β†’ YOLOv8 bboxes,
32
+ and return before/after galleries plus local path & auto-generated slug.
33
  """
34
  rf = Roboflow(api_key=api_key)
35
  ws, proj, ver = parse_roboflow_url(dataset_url)
 
85
  # locate images and write labels
86
  img_dir = None
87
  for dp, _, files in os.walk(root):
88
+ if any(f.lower().endswith(('.jpg', '.png', 'jpeg')) for f in files):
89
  img_dir = dp
90
  break
91
  if not img_dir:
 
97
  if not os.path.isfile(src):
98
  continue
99
  shutil.copy(src, os.path.join(img_out, fname))
100
+ with open(os.path.join(lbl_out, fname.rsplit('.', 1)[0] + ".txt"), 'w') as lf:
101
  lf.write("\n".join(annos.get(pid, [])))
102
 
103
  # build preview galleries
 
110
  for a in coco['annotations']:
111
  if a['image_id'] != fname2id[fn]:
112
  continue
113
+ pts = np.array(a['segmentation'][0], np.int32).reshape(-1, 2)
114
+ cv2.polylines(seg_vis, [pts], True, (255, 0, 0), 2)
115
 
116
  box_vis = img.copy()
117
  for line in annos.get(fname2id[fn], []):
118
  _, cxn, cyn, wnorm, hnorm = map(float, line.split())
119
  iw, ih = images_info[fname2id[fn]]['width'], images_info[fname2id[fn]]['height']
120
+ w0, h0 = int(wnorm * iw), int(hnorm * ih)
121
+ x0, y0 = int(cxn * iw - w0/2), int(cyn * ih - h0/2)
122
+ cv2.rectangle(box_vis, (x0, y0), (x0 + w0, y0 + h0), (0, 255, 0), 2)
123
 
124
  before.append(Image.fromarray(seg_vis))
125
  after.append(Image.fromarray(box_vis))
126
 
127
+ detection_slug = f"{proj}-detection"
128
+ return before, after, out_root, detection_slug
129
 
130
 
131
  def upload_and_train_detection(api_key: str, project_slug: str, dataset_path: str):
132
  """
133
+ Upload a local YOLOv8 dataset to Roboflow, generate & train a new detection version,
134
+ and return the hosted inference endpoint URL.
 
135
  """
136
  rf = Roboflow(api_key=api_key)
137
  ws = rf.workspace()
138
 
139
+ # 1) upload
140
  ws.upload_dataset(
141
  dataset_path,
142
  project_slug,
143
+ num_workers=10,
144
  project_license="MIT",
145
+ project_type="object-detection",
146
+ batch_name=None,
147
+ num_retries=0
148
  )
149
 
150
+ # 2) generate a new version
151
  proj = ws.project(project_slug)
152
+ new_version = proj.generate_version(settings={
153
+ "preprocessing": {},
154
+ "augmentation": {}
155
+ })
156
 
157
+ # 3) train (fast)
158
+ version = proj.version(new_version)
159
+ version.train(speed="fast")
160
 
161
+ # 4) get endpoint
162
+ m = version.model
163
  return f"{m['base_url']}{m['id']}?api_key={api_key}"
164
 
165
 
166
  with gr.Blocks() as app:
167
+ gr.Markdown("## πŸ”„ Segmentation β†’ YOLOv8 Converter + Auto‑Trainer")
168
 
169
  # Converter UI
170
  api_input = gr.Textbox(label="Roboflow API Key", type="password")
 
181
  outputs=[before_gal, after_gal, state_path, state_slug]
182
  )
183
 
184
+ # Trainer UI
185
  train_btn = gr.Button("Upload & Train Detection Model")
186
  endpoint_text = gr.Textbox(label="Hosted Detection Endpoint URL")
187