Athspi commited on
Commit
9814147
·
verified ·
1 Parent(s): d61bf06

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -54
app.py CHANGED
@@ -4,11 +4,9 @@ import tempfile
4
  import uuid
5
  import google.generativeai as genai
6
  import requests
7
- import yt_dlp
8
  from flask import Flask, request, render_template, send_from_directory, url_for, flash
9
  from moviepy.video.io.VideoFileClip import VideoFileClip
10
  from moviepy.audio.io.AudioFileClip import AudioFileClip
11
- from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
12
  from werkzeug.utils import secure_filename
13
  from dotenv import load_dotenv
14
 
@@ -55,31 +53,6 @@ Say happily: வணக்கம்! [laugh] எப்படி இருக்
55
 
56
  # --- 3. CORE LOGIC HELPER FUNCTIONS ---
57
 
58
- def download_youtube_video(url, output_folder):
59
- """Downloads a YouTube video to a specified folder using the yt-dlp library."""
60
- print(f"📥 Downloading video from YouTube URL: {url}")
61
- unique_filename = f"{uuid.uuid4()}.mp4"
62
- output_path_template = os.path.join(output_folder, os.path.splitext(unique_filename)[0])
63
- ydl_opts = {
64
- 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
65
- 'outtmpl': output_path_template,
66
- 'merge_output_format': 'mp4',
67
- 'quiet': False,
68
- 'noplaylist': True,
69
- 'progress': True,
70
- }
71
- try:
72
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
73
- ydl.download([url])
74
- downloaded_file_path = f"{output_path_template}.mp4"
75
- if os.path.exists(downloaded_file_path):
76
- print(f"✅ Download complete! File saved to: {downloaded_file_path}")
77
- return downloaded_file_path
78
- raise FileNotFoundError("Downloaded video file not found after yt-dlp process.")
79
- except Exception as e:
80
- print(f"❌ An error occurred during YouTube download: {e}")
81
- raise
82
-
83
  def generate_tamil_script(video_file_path):
84
  """Generates a single, continuous Tamil script from the video using Gemini."""
85
  print("Uploading file to Gemini for transcription...")
@@ -127,57 +100,44 @@ def replace_video_audio(video_path, new_audio_path, output_path):
127
  @app.route('/', methods=['GET'])
128
  def index():
129
  """Renders the main upload page."""
130
- return render_template('index.html', voice_choices=VOICE_CHOICES)
131
 
132
  @app.route('/process', methods=['POST'])
133
  def process_video():
134
- """Handles video input (upload or URL), processing, and renders the result."""
135
  input_video_path, temp_audio_path = None, None
136
  try:
137
- # Handle YouTube URL or file upload
138
- youtube_url = request.form.get('youtube_url', '').strip()
139
- if youtube_url:
140
- input_video_path = download_youtube_video(youtube_url, app.config['UPLOAD_FOLDER'])
141
- filename = os.path.basename(input_video_path)
142
- elif 'video' in request.files and request.files['video'].filename != '':
143
- file = request.files['video']
144
- filename = secure_filename(file.filename)
145
- input_video_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
146
- file.save(input_video_path)
147
- else:
148
- flash("Please either upload a video file or provide a YouTube URL.")
149
- return render_template('index.html', voice_choices=VOICE_CHOICES)
150
-
151
- # Get user preferences
152
  voice_choice = request.form['voice_choice']
153
  is_cheerful = 'cheerful' in request.form
154
  voice_name = VOICE_CHOICES[voice_choice]
155
-
156
- # Generate Tamil script
157
  script = generate_tamil_script(input_video_path)
158
 
159
- # Generate audio track
160
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio:
161
  temp_audio_path = temp_audio.name
162
 
163
  generate_single_audio_track(script, voice_name, is_cheerful, temp_audio_path)
164
-
165
- # Create final video
166
  final_video_name = f"dubbed_{filename}"
167
  final_video_path = os.path.join(app.config['DOWNLOAD_FOLDER'], final_video_name)
168
  replace_video_audio(input_video_path, temp_audio_path, final_video_path)
169
 
170
  flash("Video processing complete!", "success")
171
  return render_template('index.html',
172
- voice_choices=VOICE_CHOICES,
173
- result_video=url_for('serve_video', filename=final_video_name),
174
- script=script)
175
  except Exception as e:
176
  print(f"An error occurred during processing: {e}")
177
  flash(f"An unexpected error occurred: {e}. Please check the console and try again.", "error")
178
- return render_template('index.html', voice_choices=VOICE_CHOICES)
179
  finally:
180
- # Clean up temporary files
181
  if input_video_path and os.path.exists(input_video_path):
182
  os.remove(input_video_path)
183
  if temp_audio_path and os.path.exists(temp_audio_path):
 
4
  import uuid
5
  import google.generativeai as genai
6
  import requests
 
7
  from flask import Flask, request, render_template, send_from_directory, url_for, flash
8
  from moviepy.video.io.VideoFileClip import VideoFileClip
9
  from moviepy.audio.io.AudioFileClip import AudioFileClip
 
10
  from werkzeug.utils import secure_filename
11
  from dotenv import load_dotenv
12
 
 
53
 
54
  # --- 3. CORE LOGIC HELPER FUNCTIONS ---
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  def generate_tamil_script(video_file_path):
57
  """Generates a single, continuous Tamil script from the video using Gemini."""
58
  print("Uploading file to Gemini for transcription...")
 
100
  @app.route('/', methods=['GET'])
101
  def index():
102
  """Renders the main upload page."""
103
+ return render_template('index.html')
104
 
105
  @app.route('/process', methods=['POST'])
106
  def process_video():
107
+ """Handles video upload, processing, and renders the result."""
108
  input_video_path, temp_audio_path = None, None
109
  try:
110
+ if 'video' not in request.files or request.files['video'].filename == '':
111
+ flash("Please upload a video file.")
112
+ return render_template('index.html')
113
+
114
+ file = request.files['video']
115
+ filename = secure_filename(file.filename)
116
+ input_video_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
117
+ file.save(input_video_path)
118
+
 
 
 
 
 
 
119
  voice_choice = request.form['voice_choice']
120
  is_cheerful = 'cheerful' in request.form
121
  voice_name = VOICE_CHOICES[voice_choice]
 
 
122
  script = generate_tamil_script(input_video_path)
123
 
 
124
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio:
125
  temp_audio_path = temp_audio.name
126
 
127
  generate_single_audio_track(script, voice_name, is_cheerful, temp_audio_path)
 
 
128
  final_video_name = f"dubbed_{filename}"
129
  final_video_path = os.path.join(app.config['DOWNLOAD_FOLDER'], final_video_name)
130
  replace_video_audio(input_video_path, temp_audio_path, final_video_path)
131
 
132
  flash("Video processing complete!", "success")
133
  return render_template('index.html',
134
+ result_video=url_for('serve_video', filename=final_video_name),
135
+ script=script)
 
136
  except Exception as e:
137
  print(f"An error occurred during processing: {e}")
138
  flash(f"An unexpected error occurred: {e}. Please check the console and try again.", "error")
139
+ return render_template('index.html')
140
  finally:
 
141
  if input_video_path and os.path.exists(input_video_path):
142
  os.remove(input_video_path)
143
  if temp_audio_path and os.path.exists(temp_audio_path):