Aliashraf commited on
Commit
11461c8
·
verified ·
1 Parent(s): f404377

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -40
app.py CHANGED
@@ -1,15 +1,19 @@
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.responses import FileResponse
3
- from gtts import gTTS
4
- import cv2
5
- import numpy as np
6
  from PIL import Image, ImageDraw, ImageFont
 
7
  import os
8
  from concurrent.futures import ThreadPoolExecutor
9
  import asyncio
 
10
 
11
  app = FastAPI()
12
 
 
 
 
13
  # Function to split the script into smaller chunks
14
  def split_script(script: str, max_words: int = 30):
15
  words = script.split()
@@ -19,10 +23,10 @@ def split_script(script: str, max_words: int = 30):
19
  # Function to create a video segment from a script chunk
20
  def create_video_segment(script_chunk: str, background_color: str, text_color: str, font_size: int):
21
  try:
22
- # Step 1: Convert script chunk to audio using gTTS
23
- tts = gTTS(script_chunk)
24
  audio_file = f"output_audio_{os.urandom(4).hex()}.mp3"
25
- tts.save(audio_file)
 
26
 
27
  # Step 2: Create a blank image with text
28
  width, height = 1280, 720 # HD resolution
@@ -45,53 +49,34 @@ def create_video_segment(script_chunk: str, background_color: str, text_color: s
45
  text_y = (height - text_height) // 2
46
  draw.text((text_x, text_y), script_chunk, font=font, fill=text_color_rgb)
47
 
48
- # Convert the image to a numpy array for OpenCV
49
  frame = np.array(image)
50
- frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
51
 
52
- # Step 3: Create a video segment with the image and audio
53
  video_segment_file = f"video_segment_{os.urandom(4).hex()}.mp4"
54
- fps = 24
55
- fourcc = cv2.VideoWriter_fourcc(*"mp4v")
56
- video_writer = cv2.VideoWriter(video_segment_file, fourcc, fps, (width, height))
57
-
58
- # Calculate the number of frames based on audio duration
59
- audio_duration = len(script_chunk.split()) * 0.5 # Approximate duration (adjust as needed)
60
- num_frames = int(audio_duration * fps)
61
-
62
- # Write the frames to the video
63
- for _ in range(num_frames):
64
- video_writer.write(frame)
65
-
66
- # Release the video writer
67
- video_writer.release()
68
-
69
- # Step 4: Add audio to the video segment using ffmpeg (if available)
70
- if os.path.exists(audio_file):
71
- final_video_segment_file = f"final_{video_segment_file}"
72
- os.system(f"ffmpeg -i {video_segment_file} -i {audio_file} -c:v copy -c:a aac {final_video_segment_file}")
73
- os.remove(video_segment_file)
74
- os.remove(audio_file)
75
- return final_video_segment_file
76
- else:
77
- return video_segment_file
78
  except Exception as e:
79
  raise HTTPException(status_code=500, detail=str(e))
80
 
81
  # Function to combine video segments into a single video
82
  def combine_video_segments(video_segment_files: list, output_file: str = "final_output_video.mp4"):
83
  try:
84
- with open("video_list.txt", "w") as f:
85
- for segment in video_segment_files:
86
- f.write(f"file '{segment}'\n")
87
-
88
- # Combine video segments using ffmpeg
89
- os.system(f"ffmpeg -f concat -safe 0 -i video_list.txt -c copy {output_file}")
90
 
91
  # Clean up video segments
92
  for segment in video_segment_files:
93
  os.remove(segment)
94
- os.remove("video_list.txt")
95
 
96
  return output_file
97
  except Exception as e:
 
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.responses import FileResponse
3
+ import pyttsx3 # Faster TTS library
4
+ import moviepy.editor as mp # Efficient video generation
 
5
  from PIL import Image, ImageDraw, ImageFont
6
+ import numpy as np
7
  import os
8
  from concurrent.futures import ThreadPoolExecutor
9
  import asyncio
10
+ from io import BytesIO
11
 
12
  app = FastAPI()
13
 
14
+ # Initialize pyttsx3 TTS engine
15
+ engine = pyttsx3.init()
16
+
17
  # Function to split the script into smaller chunks
18
  def split_script(script: str, max_words: int = 30):
19
  words = script.split()
 
23
  # Function to create a video segment from a script chunk
24
  def create_video_segment(script_chunk: str, background_color: str, text_color: str, font_size: int):
25
  try:
26
+ # Step 1: Convert script chunk to audio using pyttsx3
 
27
  audio_file = f"output_audio_{os.urandom(4).hex()}.mp3"
28
+ engine.save_to_file(script_chunk, audio_file)
29
+ engine.runAndWait()
30
 
31
  # Step 2: Create a blank image with text
32
  width, height = 1280, 720 # HD resolution
 
49
  text_y = (height - text_height) // 2
50
  draw.text((text_x, text_y), script_chunk, font=font, fill=text_color_rgb)
51
 
52
+ # Convert the image to a numpy array for moviepy
53
  frame = np.array(image)
 
54
 
55
+ # Step 3: Create a video segment with the image and audio using moviepy
56
  video_segment_file = f"video_segment_{os.urandom(4).hex()}.mp4"
57
+ clip = mp.ImageClip(frame).set_duration(len(script_chunk.split()) * 0.5) # Approximate duration
58
+ audio_clip = mp.AudioFileClip(audio_file)
59
+ final_clip = clip.set_audio(audio_clip)
60
+ final_clip.write_videofile(video_segment_file, fps=24)
61
+
62
+ # Clean up temporary audio file
63
+ os.remove(audio_file)
64
+
65
+ return video_segment_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  except Exception as e:
67
  raise HTTPException(status_code=500, detail=str(e))
68
 
69
  # Function to combine video segments into a single video
70
  def combine_video_segments(video_segment_files: list, output_file: str = "final_output_video.mp4"):
71
  try:
72
+ # Combine video segments using moviepy
73
+ clips = [mp.VideoFileClip(segment) for segment in video_segment_files]
74
+ final_clip = mp.concatenate_videoclips(clips)
75
+ final_clip.write_videofile(output_file)
 
 
76
 
77
  # Clean up video segments
78
  for segment in video_segment_files:
79
  os.remove(segment)
 
80
 
81
  return output_file
82
  except Exception as e: