frendyrachman commited on
Commit
1f79c5e
·
verified ·
1 Parent(s): dcfe044

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -46
app.py CHANGED
@@ -1,14 +1,10 @@
1
  import os
2
  import zipfile
3
- import shutil
4
  from ultralytics import YOLO
5
  import cv2
6
  from moviepy.video.io.VideoFileClip import VideoFileClip
7
- from fastapi import FastAPI, File, UploadFile, HTTPException
8
- from fastapi.responses import FileResponse
9
- from fastapi.staticfiles import StaticFiles
10
- from io import BytesIO
11
- import tempfile
12
 
13
  # Directories for uploaded videos and output clips
14
  UPLOAD_FOLDER = 'uploaded_videos'
@@ -17,14 +13,12 @@ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
17
  os.makedirs(OUTPUT_FOLDER, exist_ok=True)
18
 
19
  # Load YOLO model
20
- MODEL_PATH = os.path.join(os.path.dirname(__file__), 'mlbb-ai-clipper-model', 'train_size_n', 'weights', 'best.pt')
21
- model = YOLO(MODEL_PATH)
 
 
22
 
23
- # Create FastAPI instance
24
- app = FastAPI()
25
-
26
- # Mount a static directory to serve the output clips
27
- app.mount("/static", StaticFiles(directory=OUTPUT_FOLDER), name="static")
28
 
29
  def process_video(video_path):
30
  """Process the video to generate highlights"""
@@ -33,7 +27,7 @@ def process_video(video_path):
33
 
34
  cap = cv2.VideoCapture(video_path)
35
  if not cap.isOpened():
36
- raise HTTPException(status_code=400, detail="Cannot open video file")
37
 
38
  frame_rate = cap.get(cv2.CAP_PROP_FPS)
39
  frame_skip = int(frame_rate * 1.5) # Process every 1.5 seconds
@@ -93,50 +87,76 @@ def process_video(video_path):
93
  # Save highlights as video
94
  zip_path = os.path.join(OUTPUT_FOLDER, 'highlights.zip')
95
  clip_count = 0
 
96
 
97
- try:
98
- with zipfile.ZipFile(zip_path, 'w') as zipf:
99
- for moment in highlight_moments:
100
- start_time = max(moment['start'], 0)
101
- end_time = min(moment['end'], VideoFileClip(video_path).duration)
102
 
 
 
103
  # Create a new VideoFileClip for the segment
104
  with VideoFileClip(video_path) as video_segment:
105
  clip = video_segment.subclip(start_time, end_time)
106
  clip_filename = os.path.join(clip_output_folder, f"highlight_{clip_count}.mp4")
107
  clip.write_videofile(clip_filename, codec="libx264", audio_codec="aac")
108
  zipf.write(clip_filename, arcname=f"highlight_{clip_count}.mp4")
109
- clip_count += 1
110
- except Exception as e:
111
- raise HTTPException(status_code=500, detail=f"Error during video processing: {str(e)}")
112
 
113
- return f"Rendering complete. {clip_count} highlights were generated.", zip_path
 
 
114
 
115
- @app.post("/upload-video/")
116
- async def upload_video(file: UploadFile = File(...)):
117
- """Endpoint to upload a video and generate highlights"""
118
  try:
119
- # Save uploaded file
120
- video_path = os.path.join(UPLOAD_FOLDER, file.filename)
121
- with open(video_path, "wb") as f:
122
- f.write(await file.read())
123
-
124
- # Process video and generate highlights
125
- result_message, result_path = process_video(video_path)
126
 
127
- # Return the generated highlights zip file as a response
128
  if result_path.endswith(".zip"):
129
- return FileResponse(result_path, media_type='application/zip', filename="highlights.zip")
130
-
131
- except Exception as e:
132
- raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
133
-
134
- @app.get("/")
135
- async def read_root():
136
- """Root endpoint"""
137
- return {"message": "Welcome to the Mobile Legends AI Highlights Generator API"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
- # Running the app with FastAPI's Uvicorn server
140
  if __name__ == "__main__":
141
- import uvicorn
142
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
  import os
2
  import zipfile
 
3
  from ultralytics import YOLO
4
  import cv2
5
  from moviepy.video.io.VideoFileClip import VideoFileClip
6
+ import gradio as gr
7
+ from huggingface_hub import hf_hub_download
 
 
 
8
 
9
  # Directories for uploaded videos and output clips
10
  UPLOAD_FOLDER = 'uploaded_videos'
 
13
  os.makedirs(OUTPUT_FOLDER, exist_ok=True)
14
 
15
  # Load YOLO model
16
+ MODEL_WEIGHTS = hf_hub_download(
17
+ repo_id="frendyrachman/mlbb-ai-clipper",
18
+ filename="train_size_n/weights/best.pt"
19
+ )
20
 
21
+ model = YOLO(MODEL_WEIGHTS)
 
 
 
 
22
 
23
  def process_video(video_path):
24
  """Process the video to generate highlights"""
 
27
 
28
  cap = cv2.VideoCapture(video_path)
29
  if not cap.isOpened():
30
+ return "Error: Cannot open video file"
31
 
32
  frame_rate = cap.get(cv2.CAP_PROP_FPS)
33
  frame_skip = int(frame_rate * 1.5) # Process every 1.5 seconds
 
87
  # Save highlights as video
88
  zip_path = os.path.join(OUTPUT_FOLDER, 'highlights.zip')
89
  clip_count = 0
90
+ completion_message = ""
91
 
92
+ with zipfile.ZipFile(zip_path, 'w') as zipf:
93
+ for moment in highlight_moments:
94
+ start_time = max(moment['start'], 0)
95
+ end_time = min(moment['end'], VideoFileClip(video_path).duration)
 
96
 
97
+ try:
98
+ clip_count += 1
99
  # Create a new VideoFileClip for the segment
100
  with VideoFileClip(video_path) as video_segment:
101
  clip = video_segment.subclip(start_time, end_time)
102
  clip_filename = os.path.join(clip_output_folder, f"highlight_{clip_count}.mp4")
103
  clip.write_videofile(clip_filename, codec="libx264", audio_codec="aac")
104
  zipf.write(clip_filename, arcname=f"highlight_{clip_count}.mp4")
105
+ except Exception as e:
106
+ print(f"Error saving clip from {start_time} to {end_time}: {e}")
 
107
 
108
+ completion_message = f"Rendering complete. {clip_count} highlights were generated."
109
+ print(completion_message)
110
+ return completion_message, zip_path # Return pesan dan path
111
 
112
+ def gradio_interface(video):
113
+ """Interface function for Gradio"""
 
114
  try:
115
+ if isinstance(video, str):
116
+ file_path = video
117
+ else:
118
+ file_path = os.path.join(UPLOAD_FOLDER, "uploaded_video.mp4")
119
+ video.save(file_path)
 
 
120
 
121
+ result_message, result_path = process_video(file_path)
122
  if result_path.endswith(".zip"):
123
+ return f"{result_message}\n\nDownload Highlights:", result_path
124
+ return "Error processing video"
125
+
126
+ except Exception as e: # Handle all other exceptions
127
+ print(f"Error occurred: {e}")
128
+ return "An unexpected error occurred during processing."
129
+
130
+ # Gradio Interface
131
+ interface = gr.Interface(
132
+ fn=gradio_interface,
133
+ inputs=gr.Video(label="Upload Video (MP4/AVI/MOV/MKV)"),
134
+ outputs=[
135
+ gr.Textbox(label="Status"),
136
+ gr.File(label="Download Highlights ZIP")
137
+ ],
138
+ title="Mobile Legends AI Highlights Generator",
139
+ description=
140
+ """
141
+ Welcome to the Mobile Legends AI Highlights Generator!
142
+
143
+ This tool uses a YOLOv8n model to analyze your gameplay video and generate highlights automatically. If you prefer a larger model, such as YOLOv8m, or want to download the model for local use, please visit the following page:
144
+ [https://huggingface.co/frendyrachman/mlbb-ai-clipper](https://huggingface.co/frendyrachman/mlbb-ai-clipper)
145
+
146
+ **How to use this tool:**
147
+ 1. Upload your gameplay video (formats supported: MP4, AVI, MOV, MKV).
148
+ 2. Click "Submit" and wait for the processing to complete.
149
+ 3. Once done, download the "highlight.zip" file containing your video highlights.
150
+
151
+ **Important Notes:**
152
+ - This tool runs on a free Hugging Face Space with hardware specifications of 2 vCPUs and 16GB RAM.
153
+ - Processing time depends on the following factors:
154
+ - **Video duration:** Longer videos require more time.
155
+ - **Video resolution:** Higher resolutions take longer to process, while lower resolutions may result in reduced clip quality.
156
+ Thank you for using this tool! We hope it enhances your gaming experience.
157
+ """
158
+
159
+ )
160
 
 
161
  if __name__ == "__main__":
162
+ interface.launch()