Samfredoly commited on
Commit
efe0f7b
·
verified ·
1 Parent(s): e95b4a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -8
app.py CHANGED
@@ -146,19 +146,52 @@ def run_pipeline():
146
  if state.stop_event.is_set(): break
147
 
148
  state.add_log(f"Processing {anime} Episode {episode}...")
149
- captions_data = []
150
  episode_json_path = OUTPUT_DIR / f"{anime}_ep{episode}.json"
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  def get_clip_num(f):
153
  m = CLIP_RE.search(f)
154
  return int(m.group(2)) if m else 0
 
155
  clips.sort(key=get_clip_num)
156
 
157
  token_limit_hit = False
 
 
158
  for clip_path in clips:
159
  if state.stop_event.is_set(): break
160
  filename = Path(clip_path).name
161
  clip_num = get_clip_num(filename)
 
 
 
 
 
162
  local_video = DOWNLOAD_DIR / filename
163
  video_url = f"https://huggingface.co/datasets/{SOURCE_REPO}/resolve/main/{clip_path}"
164
 
@@ -167,8 +200,13 @@ def run_pipeline():
167
  frames = extract_frames(str(local_video))
168
  if frames:
169
  caption = get_caption(client, frames)
170
- captions_data.append({"clip_number": clip_num, "filename": filename, "caption": caption})
171
- state.add_log(f"Captioned clip {clip_num}")
 
 
 
 
 
172
  if local_video.exists(): local_video.unlink()
173
  except ResourceWarning as rw:
174
  state.add_log(f"LIMIT: {rw}")
@@ -183,10 +221,19 @@ def run_pipeline():
183
  state.add_log(f"Error on clip {clip_num}: {e}")
184
  continue
185
 
186
- if captions_data:
187
- with open(episode_json_path, "w") as f:
188
- json.dump({"anime": anime, "episode": episode, "captions": captions_data}, f, indent=2)
189
- upload_to_hf(api, episode_json_path, f"{anime}/{anime}_ep{episode}.json", TARGET_REPO)
 
 
 
 
 
 
 
 
 
190
 
191
  if token_limit_hit:
192
  state.add_log("Stopping due to token limit.")
@@ -224,7 +271,7 @@ async def index():
224
  </head>
225
  <body>
226
  <div class="container">
227
- <h1>AniClips Captioner</h1>
228
  <div class="status">Status: <span id="status-text">Checking...</span></div>
229
  <div class="controls">
230
  <button class="start" onclick="startPipeline()">Start Pipeline</button>
 
146
  if state.stop_event.is_set(): break
147
 
148
  state.add_log(f"Processing {anime} Episode {episode}...")
 
149
  episode_json_path = OUTPUT_DIR / f"{anime}_ep{episode}.json"
150
 
151
+ # 1. Try to download existing JSON from TARGET_REPO if it exists
152
+ existing_captions_map = {}
153
+ highest_clip_num = 0
154
+ remote_json_path = f"{anime}/{anime}_ep{episode}.json"
155
+
156
+ try:
157
+ state.add_log(f"Checking existing JSON in {TARGET_REPO} at {remote_json_path}...")
158
+ downloaded_file = api.hf_hub_download(
159
+ repo_id=TARGET_REPO,
160
+ filename=remote_json_path,
161
+ repo_type="dataset"
162
+ )
163
+ with open(downloaded_file, "r", encoding="utf-8") as f:
164
+ data = json.load(f)
165
+ # Support both lists or dict structures
166
+ captions_list = data.get("captions", []) if isinstance(data, dict) else data
167
+ for item in captions_list:
168
+ c_num = item.get("clip_number")
169
+ if c_num is not None:
170
+ existing_captions_map[c_num] = item
171
+ if c_num > highest_clip_num:
172
+ highest_clip_num = c_num
173
+ state.add_log(f"Found existing JSON! Highest processed clip number: {highest_clip_num}")
174
+ except Exception as e:
175
+ state.add_log(f"No existing JSON found or error downloading: {e}. Starting fresh for this episode.")
176
+
177
  def get_clip_num(f):
178
  m = CLIP_RE.search(f)
179
  return int(m.group(2)) if m else 0
180
+
181
  clips.sort(key=get_clip_num)
182
 
183
  token_limit_hit = False
184
+ new_captions_processed = 0
185
+
186
  for clip_path in clips:
187
  if state.stop_event.is_set(): break
188
  filename = Path(clip_path).name
189
  clip_num = get_clip_num(filename)
190
+
191
+ # 2. Skip clips that have already been processed (<= highest_clip_num)
192
+ if clip_num <= highest_clip_num:
193
+ continue
194
+
195
  local_video = DOWNLOAD_DIR / filename
196
  video_url = f"https://huggingface.co/datasets/{SOURCE_REPO}/resolve/main/{clip_path}"
197
 
 
200
  frames = extract_frames(str(local_video))
201
  if frames:
202
  caption = get_caption(client, frames)
203
+ existing_captions_map[clip_num] = {
204
+ "clip_number": clip_num,
205
+ "filename": filename,
206
+ "caption": caption
207
+ }
208
+ new_captions_processed += 1
209
+ state.add_log(f"Captioned new clip {clip_num}")
210
  if local_video.exists(): local_video.unlink()
211
  except ResourceWarning as rw:
212
  state.add_log(f"LIMIT: {rw}")
 
221
  state.add_log(f"Error on clip {clip_num}: {e}")
222
  continue
223
 
224
+ # 3. Save combined/merged captions back to JSON and upload
225
+ if new_captions_processed > 0 or existing_captions_map:
226
+ # Sort captions by clip_number before saving
227
+ sorted_captions = sorted(existing_captions_map.values(), key=lambda x: x["clip_number"])
228
+ output_data = {
229
+ "anime": anime,
230
+ "episode": episode,
231
+ "captions": sorted_captions
232
+ }
233
+ with open(episode_json_path, "w", encoding="utf-8") as f:
234
+ json.dump(output_data, f, indent=2, ensure_ascii=False)
235
+ upload_to_hf(api, episode_json_path, remote_json_path, TARGET_REPO)
236
+ state.add_log(f"Successfully updated and uploaded JSON for {anime} Ep {episode} (Total captions: {len(sorted_captions)})")
237
 
238
  if token_limit_hit:
239
  state.add_log("Stopping due to token limit.")
 
271
  </head>
272
  <body>
273
  <div class="container">
274
+ <h1>AniClips Captioner (Resume Enabled)</h1>
275
  <div class="status">Status: <span id="status-text">Checking...</span></div>
276
  <div class="controls">
277
  <button class="start" onclick="startPipeline()">Start Pipeline</button>