danielhshi8224 commited on
Commit
a063f92
·
1 Parent(s): 6c3c94e

add robust logging

Browse files
Files changed (1) hide show
  1. app.py +110 -1
app.py CHANGED
@@ -80,6 +80,13 @@ def detect_objects_batch(files, conf=0.25, iou=0.25):
80
  if not files:
81
  return [], [], None
82
 
 
 
 
 
 
 
 
83
  try:
84
  ymodel = _load_yolo()
85
  except Exception as e:
@@ -87,9 +94,99 @@ def detect_objects_batch(files, conf=0.25, iou=0.25):
87
  return [], [], None
88
 
89
  gallery, table_rows = [], []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  for f in files[:MAX_BATCH]:
92
- path = getattr(f, "name", None) or getattr(f, "path", None) or f
 
 
 
 
 
 
 
 
 
 
 
93
  try:
94
  results = ymodel.predict(source=path, conf=conf, iou=iou, imgsz=640, verbose=False)
95
  except Exception as e:
@@ -191,6 +288,18 @@ def detect_objects_batch(files, conf=0.25, iou=0.25):
191
  print("Failed to write CSV:", e)
192
  csv_path = None
193
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  return gallery, table_rows, csv_path
195
 
196
  # ---------- UI ----------
 
80
  if not files:
81
  return [], [], None
82
 
83
+ # Diagnostic: list incoming file objects/paths (useful when Gradio passes blob paths)
84
+ try:
85
+ incoming = [getattr(f, 'name', None) or getattr(f, 'path', None) or str(f) for f in files]
86
+ print('[DETECT] incoming files:', incoming)
87
+ except Exception:
88
+ print('[DETECT] incoming files: (unreadable)')
89
+
90
  try:
91
  ymodel = _load_yolo()
92
  except Exception as e:
 
94
  return [], [], None
95
 
96
  gallery, table_rows = [], []
97
+ _created_temp_files = []
98
+
99
+ def _ensure_path(fileobj):
100
+ """Return a filesystem path suitable for YOLO.predict.
101
+ Handles:
102
+ - strings that are existing paths
103
+ - Gradio 'blob' temp paths without extension
104
+ - file-like objects (have .read())
105
+ - bytes
106
+ If we create a temp file, record it in _created_temp_files for cleanup.
107
+ """
108
+ # If it's already a readable path string
109
+ if isinstance(fileobj, str) and os.path.exists(fileobj):
110
+ return fileobj
111
+
112
+ # If object has .path attribute pointing to an existing file
113
+ try:
114
+ p = getattr(fileobj, 'path', None)
115
+ if p and os.path.exists(p):
116
+ return p
117
+ except Exception:
118
+ pass
119
+
120
+ # If object has a name attribute that's a path
121
+ try:
122
+ n = getattr(fileobj, 'name', None)
123
+ if n and isinstance(n, str) and os.path.exists(n):
124
+ return n
125
+ except Exception:
126
+ pass
127
+
128
+ # Read bytes from file-like or bytes object
129
+ data = None
130
+ try:
131
+ if hasattr(fileobj, 'read'):
132
+ # file-like
133
+ data = fileobj.read()
134
+ elif isinstance(fileobj, (bytes, bytearray)):
135
+ data = bytes(fileobj)
136
+ except Exception:
137
+ data = None
138
+
139
+ # If fileobj is a string but file doesn't exist, try reading it
140
+ if data is None and isinstance(fileobj, str):
141
+ try:
142
+ with open(fileobj, 'rb') as fh:
143
+ data = fh.read()
144
+ except Exception:
145
+ data = None
146
+
147
+ if data is None:
148
+ # give up and return the original object
149
+ return fileobj
150
+
151
+ # Detect image format via PIL
152
+ from io import BytesIO
153
+ try:
154
+ bio = BytesIO(data)
155
+ img = Image.open(bio)
156
+ fmt = (img.format or 'JPEG').lower()
157
+ except Exception:
158
+ # fallback: try imghdr
159
+ try:
160
+ import imghdr
161
+ fmt = imghdr.what(None, data) or 'jpeg'
162
+ except Exception:
163
+ fmt = 'jpeg'
164
+
165
+ suffix = '.' + (fmt if not fmt.startswith('.') else fmt)
166
+ try:
167
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix, prefix='gr_blob_', dir=BASE_DIR)
168
+ tmp.write(data)
169
+ tmp.flush(); tmp.close()
170
+ _created_temp_files.append(tmp.name)
171
+ print(f"[DETECT] wrote temp file: {tmp.name} (fmt={fmt})")
172
+ return tmp.name
173
+ except Exception as e:
174
+ print('[DETECT] failed to write temp file from upload:', e)
175
+ return fileobj
176
 
177
  for f in files[:MAX_BATCH]:
178
+ path = _ensure_path(f)
179
+ try:
180
+ # Diagnostic: show resolved path and file info
181
+ try:
182
+ exists = os.path.exists(path)
183
+ size = os.path.getsize(path) if exists else None
184
+ except Exception:
185
+ exists = False
186
+ size = None
187
+ print(f"[DETECT] resolved path={path!r}, exists={exists}, size={size}")
188
+ except Exception:
189
+ pass
190
  try:
191
  results = ymodel.predict(source=path, conf=conf, iou=iou, imgsz=640, verbose=False)
192
  except Exception as e:
 
288
  print("Failed to write CSV:", e)
289
  csv_path = None
290
 
291
+ # cleanup created temp files
292
+ try:
293
+ for p in _created_temp_files:
294
+ try:
295
+ if os.path.exists(p):
296
+ os.remove(p)
297
+ print(f"[DETECT] removed temp file: {p}")
298
+ except Exception:
299
+ pass
300
+ except Exception:
301
+ pass
302
+
303
  return gallery, table_rows, csv_path
304
 
305
  # ---------- UI ----------