Og2 commited on
Commit
321ccc6
·
verified ·
1 Parent(s): 09d4424

Update app.py

Browse files

extract and store frames

Files changed (1) hide show
  1. app.py +53 -0
app.py CHANGED
@@ -506,6 +506,59 @@ async def list_videos():
506
  except Exception as e:
507
  raise HTTPException(status_code=500, detail=f"Failed to fetch videos: {str(e)}")
508
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
 
510
  @app.get("/get-video-frames/")
511
  async def get_video_frames(file_name: str, frame_id: int) -> dict:
 
506
  except Exception as e:
507
  raise HTTPException(status_code=500, detail=f"Failed to fetch videos: {str(e)}")
508
 
509
+ @app.post("/extract-and-store-frames/")
510
+ async def extract_and_store_frames(file_name: str):
511
+ try:
512
+ # URL du fichier vidéo dans le dataset
513
+ video_url = f"https://huggingface.co/datasets/{DATASET_REPO}/resolve/main/{file_name}"
514
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
515
+ response = requests.get(video_url, headers=headers)
516
+
517
+ if response.status_code != 200:
518
+ raise HTTPException(status_code=404, detail="Vidéo introuvable dans le dataset")
519
+
520
+ # Charger la vidéo en mémoire
521
+ video_bytes = io.BytesIO(response.content)
522
+ temp_video_path = "/tmp/temp_video.mp4"
523
+ with open(temp_video_path, "wb") as f:
524
+ f.write(video_bytes.getvalue())
525
+
526
+ cap = cv2.VideoCapture(temp_video_path)
527
+ if not cap.isOpened():
528
+ raise HTTPException(status_code=500, detail="Impossible de charger la vidéo")
529
+
530
+ frame_size = (128, 128)
531
+ video_stem = Path(file_name).stem
532
+ frames_dir = f"frames/{video_stem}/"
533
+ os.makedirs(frames_dir, exist_ok=True)
534
+
535
+ frame_id = 0
536
+ while True:
537
+ ret, frame = cap.read()
538
+ if not ret:
539
+ break
540
+
541
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
542
+ img = Image.fromarray(frame_rgb).resize(frame_size)
543
+ frame_filename = f"{frames_dir}{video_stem}_{frame_id}.png"
544
+ img.save(frame_filename)
545
+ frame_id += 1
546
+
547
+ cap.release()
548
+
549
+ # Upload frames to Hugging Face dataset
550
+ for frame_file in os.listdir(frames_dir):
551
+ frame_path = os.path.join(frames_dir, frame_file)
552
+ hf_api.upload_file(path_or_fileobj=frame_path,
553
+ path_in_repo=f"frames/{video_stem}/{frame_file}",
554
+ repo_id=DATASET_REPO,
555
+ repo_type="dataset",
556
+ token=HF_TOKEN)
557
+
558
+ return {"status": "success", "message": f"{frame_id} frames extraites et stockées."}
559
+ except Exception as e:
560
+ raise HTTPException(status_code=500, detail=f"Erreur lors de l'extraction des frames : {str(e)}")
561
+
562
 
563
  @app.get("/get-video-frames/")
564
  async def get_video_frames(file_name: str, frame_id: int) -> dict: