wuhp commited on
Commit
eecca4c
·
verified ·
1 Parent(s): 6c1d7d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -20
app.py CHANGED
@@ -9,7 +9,7 @@ import cv2
9
  import numpy as np
10
  from PIL import Image
11
  import gradio as gr
12
- from roboflow import Roboflow, RoboflowError
13
 
14
 
15
  def parse_roboflow_url(url: str):
@@ -29,7 +29,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str):
29
  """
30
  Download a segmentation dataset from Roboflow,
31
  convert masks → YOLOv8 bboxes,
32
- and return (before, after) galleries + local YOLOdataset path + auto slug.
33
  """
34
  rf = Roboflow(api_key=api_key)
35
  ws_name, seg_proj_slug, ver = parse_roboflow_url(dataset_url)
@@ -37,7 +37,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str):
37
  dataset = version_obj.download("coco-segmentation")
38
  root = dataset.location
39
 
40
- # --- find annotation JSON ---
41
  ann_file = None
42
  for dp, _, files in os.walk(root):
43
  for f in files:
@@ -62,14 +62,14 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str):
62
  cat_ids = sorted(c["id"] for c in coco.get("categories", []))
63
  id_to_index = {cid: idx for idx, cid in enumerate(cat_ids)}
64
 
65
- # --- prepare YOLOv8 folders ---
66
  out_root = tempfile.mkdtemp(prefix="yolov8_")
67
  img_out = os.path.join(out_root, "images")
68
  lbl_out = os.path.join(out_root, "labels")
69
  os.makedirs(img_out, exist_ok=True)
70
  os.makedirs(lbl_out, exist_ok=True)
71
 
72
- # --- convert seg → bbox labels ---
73
  annos = {}
74
  for a in coco["annotations"]:
75
  pid = a["image_id"]
@@ -82,7 +82,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str):
82
  line = f"{id_to_index[a['category_id']]} {cx/iw:.6f} {cy/ih:.6f} {w/iw:.6f} {h/ih:.6f}"
83
  annos.setdefault(pid, []).append(line)
84
 
85
- # --- locate images and write label files ---
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):
@@ -100,7 +100,7 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str):
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 ---
104
  before, after = [], []
105
  sample = random.sample(list(fname2id.keys()), min(5, len(fname2id)))
106
  for fn in sample:
@@ -118,14 +118,14 @@ def convert_seg_to_bbox(api_key: str, dataset_url: str):
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 = int(cxn * iw - w0 / 2)
122
- y0 = int(cyn * ih - h0 / 2)
123
  cv2.rectangle(box_vis, (x0, y0), (x0 + w0, y0 + h0), (0, 255, 0), 2)
124
 
125
  before.append(Image.fromarray(seg_vis))
126
  after.append(Image.fromarray(box_vis))
127
 
128
- # auto‐slug for detection project
129
  detection_slug = f"{seg_proj_slug}-detection"
130
  return before, after, out_root, detection_slug
131
 
@@ -138,17 +138,17 @@ def upload_and_train_detection(api_key: str, project_slug: str, dataset_path: st
138
  rf = Roboflow(api_key=api_key)
139
  ws = rf.workspace()
140
 
141
- # 1) get or create the detection project
142
  try:
143
  proj = ws.project(project_slug)
144
- except RoboflowError:
145
  proj = ws.create_project(
146
  project_name=project_slug,
147
  project_type="object-detection",
148
  project_license="MIT"
149
  )
150
 
151
- # 2) upload the dataset
152
  ws.upload_dataset(
153
  dataset_path,
154
  proj.id,
@@ -159,17 +159,14 @@ def upload_and_train_detection(api_key: str, project_slug: str, dataset_path: st
159
  num_retries=0
160
  )
161
 
162
- # 3) generate a new version (no extra aug/preproc by default)
163
- new_v = proj.generate_version(settings={
164
- "preprocessing": {},
165
- "augmentation": {}
166
- })
167
 
168
- # 4) train it (fast)
169
  version = proj.version(new_v)
170
  version.train(speed="fast")
171
 
172
- # 5) return the hosted inference URL
173
  m = version.model
174
  return f"{m['base_url']}{m['id']}?api_key={api_key}"
175
 
 
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):
 
29
  """
30
  Download a segmentation dataset from Roboflow,
31
  convert masks → YOLOv8 bboxes,
32
+ and return (before, after) galleries + local YOLO dataset path + auto slug.
33
  """
34
  rf = Roboflow(api_key=api_key)
35
  ws_name, seg_proj_slug, ver = parse_roboflow_url(dataset_url)
 
37
  dataset = version_obj.download("coco-segmentation")
38
  root = dataset.location
39
 
40
+ # find the annotation JSON
41
  ann_file = None
42
  for dp, _, files in os.walk(root):
43
  for f in files:
 
62
  cat_ids = sorted(c["id"] for c in coco.get("categories", []))
63
  id_to_index = {cid: idx for idx, cid in enumerate(cat_ids)}
64
 
65
+ # prepare YOLOv8 folders
66
  out_root = tempfile.mkdtemp(prefix="yolov8_")
67
  img_out = os.path.join(out_root, "images")
68
  lbl_out = os.path.join(out_root, "labels")
69
  os.makedirs(img_out, exist_ok=True)
70
  os.makedirs(lbl_out, exist_ok=True)
71
 
72
+ # convert seg → bbox labels
73
  annos = {}
74
  for a in coco["annotations"]:
75
  pid = a["image_id"]
 
82
  line = f"{id_to_index[a['category_id']]} {cx/iw:.6f} {cy/ih:.6f} {w/iw:.6f} {h/ih:.6f}"
83
  annos.setdefault(pid, []).append(line)
84
 
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):
 
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
104
  before, after = [], []
105
  sample = random.sample(list(fname2id.keys()), min(5, len(fname2id)))
106
  for fn in sample:
 
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 = int(cxn * iw - w0/2)
122
+ y0 = int(cyn * ih - h0/2)
123
  cv2.rectangle(box_vis, (x0, y0), (x0 + w0, y0 + h0), (0, 255, 0), 2)
124
 
125
  before.append(Image.fromarray(seg_vis))
126
  after.append(Image.fromarray(box_vis))
127
 
128
+ # auto‐slug for the detection project
129
  detection_slug = f"{seg_proj_slug}-detection"
130
  return before, after, out_root, detection_slug
131
 
 
138
  rf = Roboflow(api_key=api_key)
139
  ws = rf.workspace()
140
 
141
+ # get or create the detection project
142
  try:
143
  proj = ws.project(project_slug)
144
+ except Exception:
145
  proj = ws.create_project(
146
  project_name=project_slug,
147
  project_type="object-detection",
148
  project_license="MIT"
149
  )
150
 
151
+ # upload the dataset
152
  ws.upload_dataset(
153
  dataset_path,
154
  proj.id,
 
159
  num_retries=0
160
  )
161
 
162
+ # generate a new version
163
+ new_v = proj.generate_version(settings={"preprocessing": {}, "augmentation": {}})
 
 
 
164
 
165
+ # train (fast)
166
  version = proj.version(new_v)
167
  version.train(speed="fast")
168
 
169
+ # return the hosted inference URL
170
  m = version.model
171
  return f"{m['base_url']}{m['id']}?api_key={api_key}"
172