Spaces:
Sleeping

vibesync2 / app.py
Shafiq786's picture
Update app.py
080dbbe verified
Raw History Blame Contribute Delete
4.01 kB
import os
import whisper
import threading
import cv2
import numpy as np
from flask import Flask, render_template, request, jsonify, send_file
# --- MoviePy Safe Import ---
try:
from moviepy.editor import VideoFileClip, ImageClip, CompositeVideoClip
except ImportError:
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.video.VideoClip import ImageClip
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
# ---------------------------
app = Flask(__name__)
UPLOAD_FOLDER = '/tmp/uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Whisper Model (Tiny) - Hindi to English translation ke liye
model = whisper.load_model("tiny")
progress_val = 0
def create_text_image(text, width, height, color=(0, 255, 255)):
"""
OpenCV se subtitles aur watermark ki image banana (No ImageMagick needed)
"""
img = np.zeros((height, width, 4), dtype=np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 1.2
thickness = 3
text_size = cv2.getTextSize(text, font, font_scale, thickness)[0]
text_x = (width - text_size[0]) // 2
text_y = (height + text_size[1]) // 2
# Black Outline for readability
cv2.putText(img, text, (text_x, text_y), font, font_scale, (0, 0, 0, 255), thickness + 4, cv2.LINE_AA)
# Main Text
cv2.putText(img, text, (text_x, text_y), font, font_scale, (color[0], color[1], color[2], 255), thickness, cv2.LINE_AA)
return img
def process_video_logic(in_p, out_p):
global progress_val
try:
progress_val = 15
# 1. AI Transcription + Translation
result = model.transcribe(in_p, task="translate")
progress_val = 40
video = VideoFileClip(in_p)
w, h = video.size
clips = [video]
# 2. Add Watermark "KYA NAAM HAI 7"
wm_img = create_text_image("KYA NAAM HAI 7", w, 100, color=(255, 255, 255))
wm_clip = ImageClip(wm_img[:,:,:3]).set_mask(ImageClip(wm_img[:,:,3], ismask=True))
wm_clip = wm_clip.set_duration(video.duration).set_position(('center', h-70)).set_opacity(0.5)
clips.append(wm_clip)
# 3. Add Subtitles
progress_val = 60
for seg in result['segments']:
txt = seg['text'].strip().upper()
if len(txt) > 30: txt = txt[:30] + "..."
sub_img = create_text_image(txt, w, 150)
sub_clip = ImageClip(sub_img[:,:,:3]).set_mask(ImageClip(sub_img[:,:,3], ismask=True))
sub_clip = sub_clip.set_start(seg['start']).set_end(seg['end']).set_position(('center', 'center'))
clips.append(sub_clip)
# 4. Rendering
progress_val = 85
final = CompositeVideoClip(clips)
final.write_videofile(out_p, codec="libx264", audio_codec="aac",
fps=video.fps, preset="ultrafast", threads=4, logger=None)
video.close()
final.close()
progress_val = 100
except Exception as e:
print(f"Error Processing: {e}")
progress_val = -1
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process', methods=['POST'])
def process():
global progress_val
progress_val = 0
if 'video' not in request.files:
return jsonify({"error": "No file"}), 400
vid = request.files['video']
in_p = os.path.join(UPLOAD_FOLDER, "input.mp4")
out_p = os.path.join(UPLOAD_FOLDER, "output.mp4")
if os.path.exists(in_p): os.remove(in_p)
if os.path.exists(out_p): os.remove(out_p)
vid.save(in_p)
threading.Thread(target=process_video_logic, args=(in_p, out_p)).start()
return jsonify({"status": "started"})
@app.route('/progress')
def get_progress():
return jsonify({"progress": progress_val})
@app.route('/download')
def download():
return send_file(os.path.join(UPLOAD_FOLDER, "output.mp4"), as_attachment=True)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)