hivecorp commited on
Commit
889e1fa
·
verified ·
1 Parent(s): 513a56f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -53
app.py CHANGED
@@ -1,55 +1,129 @@
1
  import gradio as gr
2
- from moviepy.editor import VideoFileClip, AudioFileClip, ImageClip
3
-
4
- # Function to generate audio from text (placeholder)
5
- def generate_audio(text, voice, rate, pitch):
6
- # This should generate the audio and return an AudioFileClip
7
- # Implement your audio generation logic here
8
- pass
9
-
10
- # Function to create video from text and background media
11
- def text_to_video(text, voice, rate, pitch, bg_media, video_width, video_height):
12
- # Generate the audio clip
13
- audio_clip = generate_audio(text, voice, rate, pitch) # Ensure this function is defined to generate audio
14
-
15
- # Determine the type of background media and create the appropriate clip
16
- if bg_media.endswith('.mp4'):
17
- bg_clip = VideoFileClip(bg_media).set_duration(audio_clip.duration)
18
- elif bg_media.endswith(('.jpg', '.png', '.jpeg')):
19
- bg_clip = ImageClip(bg_media).set_duration(audio_clip.duration)
20
- else:
21
- return None, "Unsupported media type."
22
-
23
- # Create a final video with audio
24
- final_video = bg_clip.set_audio(audio_clip)
25
-
26
- # Set the final output video file name
27
- output_file = "output_video.mp4"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- # Write the final video to a file
30
- final_video.write_videofile(output_file, codec='libx264')
31
-
32
- return output_file, None
33
-
34
- # Gradio interface
35
- def tts_interface(text, voice, rate, pitch, bg_media):
36
- video, warning = text_to_video(text, voice, rate, pitch, bg_media, None, None)
37
- if warning:
38
- return warning
39
- return video
40
-
41
- iface = gr.Interface(
42
- fn=tts_interface,
43
- inputs=[
44
- gr.Textbox(label="Text"),
45
- gr.Dropdown(label="Voice", choices=["Voice 1", "Voice 2"]), # Update with actual voices
46
- gr.Slider(label="Rate", minimum=0.5, maximum=2.0, step=0.1, value=1.0),
47
- gr.Slider(label="Pitch", minimum=0, maximum=100, step=1, value=50),
48
- gr.File(label="Background Media (Image/Video)")
49
- ],
50
- outputs="file",
51
- title="Text to Video with Audio",
52
- description="Upload an image or video and generate a video with audio from text."
53
- )
54
-
55
- iface.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import edge_tts
3
+ import asyncio
4
+ import tempfile
5
+ import os
6
+ from moviepy.editor import AudioFileClip
7
+ from wand.image import Image
8
+ from wand.drawing import Drawing
9
+ from wand.color import Color
10
+
11
+ # 获取所有可用的语音
12
+ async def get_voices():
13
+ voices = await edge_tts.list_voices()
14
+ return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}
15
+
16
+ # 文字转语音功能
17
+ async def text_to_speech(text, voice, rate, pitch):
18
+ if not text.strip():
19
+ return None, gr.Warning("Please enter the text to convert.")
20
+ if not voice:
21
+ return None, gr.Warning("Please select a voice.")
22
+
23
+ voice_short_name = voice.split(" - ")[0]
24
+ rate_str = f"{rate:+d}%"
25
+ pitch_str = f"{pitch:+d}Hz"
26
+ communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)
27
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
28
+ tmp_path = tmp_file.name
29
+ await communicate.save(tmp_path)
30
+ return tmp_path, None
31
+
32
+ # SRT文件生成
33
+ def generate_srt(pages, audio_clips):
34
+ srt_path = os.path.join(tempfile.gettempdir(), "output_subtitles.srt")
35
+ with open(srt_path, 'w', encoding='utf-8') as srt_file:
36
+ for i, (page, audio_clip) in enumerate(zip(pages, audio_clips)):
37
+ start_time = sum(audio_clip.duration for audio_clip in audio_clips[:i])
38
+ end_time = start_time + audio_clip.duration
39
+
40
+ # Convert to SRT format
41
+ start_time_str = format_srt_time(start_time)
42
+ end_time_str = format_srt_time(end_time)
43
+ srt_file.write(f"{i + 1}\n{start_time_str} --> {end_time_str}\n{page}\n\n")
44
+
45
+ return srt_path
46
+
47
+ def format_srt_time(seconds):
48
+ millis = int((seconds - int(seconds)) * 1000)
49
+ seconds = int(seconds)
50
+ minutes = seconds // 60
51
+ hours = minutes // 60
52
+ minutes %= 60
53
+ seconds %= 60
54
+ return f"{hours:02}:{minutes:02}:{seconds:02},{millis:03}"
55
+
56
+ # 文字转音频和SRT功能
57
+ async def text_to_audio_and_srt(text, voice, rate, pitch):
58
+ # 计算每页可以容纳的行数和每行可以容纳的字符数
59
+ max_chars_per_line = 60 # 适当设置每行最大字符数
60
+ max_lines_per_page = 5 # 每页最大行数
61
+
62
+ # 按页拆分文本
63
+ words = text.split()
64
+ lines = []
65
+ current_line = ""
66
+ pages = []
67
 
68
+ for word in words:
69
+ if len(current_line) + len(word) + 1 > max_chars_per_line:
70
+ lines.append(current_line)
71
+ current_line = word
72
+ if len(lines) == max_lines_per_page:
73
+ pages.append("\n".join(lines))
74
+ lines = []
75
+ else:
76
+ current_line = f"{current_line} {word}".strip()
77
+
78
+ lines.append(current_line)
79
+ if lines:
80
+ pages.append("\n".join(lines))
81
+
82
+ # 为每页生成独立音频
83
+ audio_clips = []
84
+ for page in pages:
85
+ audio_text = page.replace("\n", " ") # 移除换行符以防止 TTS 停顿
86
+ audio, warning = await text_to_speech(audio_text, voice, rate, pitch)
87
+ if warning:
88
+ return None, None, warning
89
+ audio_clip = AudioFileClip(audio)
90
+ audio_clips.append(audio_clip)
91
+
92
+ # 生成SRT文件
93
+ srt_path = generate_srt(pages, audio_clips)
94
+ return audio, srt_path, None
95
+
96
+ # Gradio接口函数
97
+ def tts_interface(text, voice, rate, pitch):
98
+ audio_path, srt_path, warning = asyncio.run(text_to_audio_and_srt(text, voice, rate, pitch))
99
+ return audio_path, srt_path, warning
100
+
101
+ # 创建Gradio应用
102
+ async def create_demo():
103
+ voices = await get_voices()
104
+
105
+ demo = gr.Interface(
106
+ fn=tts_interface,
107
+ inputs=[
108
+ gr.Textbox(label="Input Text", lines=5),
109
+ gr.Dropdown(choices=[""] + list(voices.keys()), label="Select Voice", value=""),
110
+ gr.Slider(minimum=-50, maximum=50, value=0, label="Rate Adjustment (%)", step=1),
111
+ gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch Adjustment (Hz)", step=1),
112
+ ],
113
+ outputs=[
114
+ gr.Audio(label="Generated Audio", type="filepath"),
115
+ gr.File(label="Generated SRT", file_count="single"),
116
+ gr.Markdown(label="Warning", visible=False)
117
+ ],
118
+ title="Edge TTS Text to Speech with Subtitles",
119
+ description="Convert text to speech and generate subtitles (SRT) using Microsoft Edge TTS.",
120
+ analytics_enabled=False,
121
+ allow_flagging=False,
122
+ )
123
+
124
+ return demo
125
+
126
+ # 运行应用
127
+ if __name__ == "__main__":
128
+ demo = asyncio.run(create_demo())
129
+ demo.launch()