sam12345324 commited on
Commit
c2781b0
·
verified ·
1 Parent(s): 0fb853c

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +118 -0
main.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # main.py
2
+ import gradio as gr
3
+ from fastapi import FastAPI, File, UploadFile, Form
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ import uvicorn
6
+ import os
7
+ import tempfile
8
+ import shutil
9
+ import traceback
10
+ import logging
11
+ from merge_utils import merge_videos_and_audios # move your merge logic to merge_utils.py for clean code!
12
+
13
+ # Setup logging
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # --- FASTAPI SETUP ---
18
+ fastapi_app = FastAPI(title="Video & Audio Merger API")
19
+
20
+ # CORS for n8n to call the API
21
+ fastapi_app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"], # You can restrict to your domain if needed
24
+ allow_credentials=True,
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+ # FastAPI endpoint to accept binary files from n8n
30
+ @fastapi_app.post("/merge")
31
+ async def merge_endpoint(
32
+ files: list[UploadFile] = File(...),
33
+ orig_vol: float = Form(1.0),
34
+ music_vol: float = Form(0.5),
35
+ ):
36
+ try:
37
+ logger.info(f"Received {len(files)} files from n8n")
38
+
39
+ # Save files to temp dir
40
+ temp_dir = tempfile.mkdtemp()
41
+ saved_files = []
42
+
43
+ for upload_file in files:
44
+ filename = os.path.basename(upload_file.filename)
45
+ file_path = os.path.join(temp_dir, filename)
46
+ with open(file_path, "wb") as f:
47
+ content = await upload_file.read()
48
+ f.write(content)
49
+ saved_files.append(file_path)
50
+ logger.info(f"Saved file: {file_path}")
51
+
52
+ # Split files into video and audio
53
+ video_files = [f for f in saved_files if f.lower().endswith(".mp4")]
54
+ audio_files = [f for f in saved_files if f.lower().endswith((".mp3", ".wav"))]
55
+
56
+ # Run merge
57
+ output_path = merge_videos_and_audios(
58
+ video_files=video_files,
59
+ audio_files=audio_files,
60
+ orig_vol=orig_vol,
61
+ music_vol=music_vol,
62
+ temp_dir=temp_dir,
63
+ )
64
+
65
+ # Return result as path or error
66
+ if isinstance(output_path, str) and output_path.startswith("Error"):
67
+ return {"success": False, "error": output_path}
68
+
69
+ # Move output to persistent location (optional)
70
+ public_output_dir = "./outputs"
71
+ os.makedirs(public_output_dir, exist_ok=True)
72
+ final_output_path = os.path.join(public_output_dir, os.path.basename(output_path))
73
+ shutil.move(output_path, final_output_path)
74
+ logger.info(f"Final output moved to {final_output_path}")
75
+
76
+ return {
77
+ "success": True,
78
+ "output_url": f"/outputs/{os.path.basename(final_output_path)}"
79
+ }
80
+
81
+ except Exception as e:
82
+ error_msg = f"Exception: {str(e)}\n{traceback.format_exc()}"
83
+ logger.error(error_msg)
84
+ return {"success": False, "error": error_msg}
85
+
86
+ # --- GRADIO SETUP ---
87
+ with gr.Blocks(title="Video and Audio Merger UI") as gradio_app:
88
+ gr.Markdown("## Video and Audio Merger")
89
+ file_input = gr.File(label="Upload Files", type="binary", file_count="multiple")
90
+ orig_vol_input = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="Original Video Audio Volume")
91
+ music_vol_input = gr.Slider(minimum=0.0, maximum=1.0, value=0.5, step=0.05, label="Background Audio Volume")
92
+ output_video = gr.Video(label="Merged Video")
93
+ output_audio = gr.Audio(label="Merged Audio")
94
+ merge_button = gr.Button("Merge Files")
95
+
96
+ def gradio_merge_files(file_binaries, orig_vol, music_vol):
97
+ # You can call your existing function here (same as before)
98
+ pass # Keep your old gradio_merge_files() here!
99
+
100
+ merge_button.click(
101
+ fn=gradio_merge_files,
102
+ inputs=[file_input, orig_vol_input, music_vol_input],
103
+ outputs=[output_video, output_audio],
104
+ )
105
+
106
+ # --- COMBINE BOTH ---
107
+ if __name__ == "__main__":
108
+ import threading
109
+
110
+ # Run FastAPI server in background
111
+ def run_fastapi():
112
+ uvicorn.run(fastapi_app, host="0.0.0.0", port=8000)
113
+
114
+ threading.Thread(target=run_fastapi).start()
115
+
116
+ # Run Gradio app on another port (HuggingFace will pick this)
117
+ gradio_app.queue(api_open=True)
118
+ gradio_app.launch(server_port=7860, share=True)