MatteoFasulo commited on
Commit
6ee0331
Β·
verified Β·
1 Parent(s): 4ea4aa0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +289 -0
app.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+ from pathlib import Path
5
+ import asyncio
6
+ import platform
7
+ from argparse import Namespace
8
+
9
+ import edge_tts
10
+ import streamlit as st
11
+ import pandas as pd
12
+
13
+ from src.video_creator import VideoCreator
14
+ from utils import rgb_to_bgr
15
+
16
+ result = None
17
+
18
+
19
+ async def generate_video(
20
+ model,
21
+ tts_voice,
22
+ sub_position,
23
+ font,
24
+ font_color,
25
+ font_size,
26
+ url,
27
+ non_english,
28
+ upload_tiktok,
29
+ verbose,
30
+ video_json,
31
+ background_tab,
32
+ video_num,
33
+ max_words,
34
+ *args,
35
+ **kwargs):
36
+
37
+ args = Namespace(
38
+ model=model,
39
+ tts=tts_voice.split('|')[0].strip(),
40
+ font=font,
41
+ font_color=rgb_to_bgr(font_color.lower()),
42
+ font_size=font_size,
43
+ sub_position=sub_position,
44
+ url=url,
45
+ non_english=non_english,
46
+ upload_tiktok=upload_tiktok,
47
+ verbose=verbose,
48
+ mp4_background=background_tab,
49
+ max_words=max_words
50
+ )
51
+
52
+ async def get_video(video_data, args):
53
+ with st.status("Generating video...", expanded=False) as status:
54
+ video_creator = VideoCreator(video_data, args)
55
+
56
+ status.update(label="Downloading video...")
57
+ video_creator.download_video()
58
+
59
+ status.update(label="Loading model...")
60
+ video_creator.load_model()
61
+
62
+ status.update(label="Creating text...")
63
+ video_creator.create_text()
64
+
65
+ status.update(label="Generating audio...")
66
+ await video_creator.text_to_speech()
67
+
68
+ status.update(label="Generating transcription...")
69
+ video_creator.generate_transcription()
70
+
71
+ status.update(label="Selecting background...")
72
+ video_creator.select_background()
73
+
74
+ status.update(label="Integrating subtitles...")
75
+ video_creator.integrate_subtitles()
76
+
77
+ if upload_tiktok:
78
+ status.update(label="Uploading to TikTok...")
79
+ video_creator.upload_to_tiktok()
80
+
81
+ status.update(label="Video generated!",
82
+ state="complete", expanded=False)
83
+ return str(video_creator.mp4_final_video)
84
+
85
+ tasks = [get_video(video_json[i], args)
86
+ for i, name in enumerate(video_num)]
87
+ results = await asyncio.gather(*tasks)
88
+
89
+ if len(results) == 1:
90
+ return results[0]
91
+
92
+ else:
93
+ return results[-1]
94
+
95
+
96
+ @st.cache_data
97
+ def json_to_df(json_file):
98
+ return pd.read_json(json_file)
99
+
100
+
101
+ @st.cache_data
102
+ def df_to_json(df):
103
+ try:
104
+ # Convert the DataFrame to a JSON string
105
+ json_str = df.to_json(orient='records', indent=4, force_ascii=False)
106
+
107
+ # raise an error if the dataframe has no rows (at least one is required)
108
+ if df.shape[0] == 0:
109
+ st.error("You must add at least one video to the JSON")
110
+ return
111
+
112
+ # Save the JSON string to a file
113
+ with open('video.json', 'w', encoding='UTF-8') as f:
114
+ f.write(json_str)
115
+
116
+ st.success("JSON saved successfully!")
117
+
118
+ except ValueError as e:
119
+ st.error("You must fill all the fields in the JSON")
120
+ except Exception as e:
121
+ st.error(f"Error saving JSON: {e}")
122
+
123
+
124
+ # Streamlit Config
125
+ st.set_page_config(
126
+ page_title="Whisper-TikTok",
127
+ page_icon="πŸ’¬",
128
+ layout="wide",
129
+ initial_sidebar_state="expanded",
130
+ menu_items={
131
+ 'Get Help': 'https://github.com/MatteoFasulo/Whisper-TikTok',
132
+ 'Report a bug': "https://github.com/MatteoFasulo/Whisper-TikTok/issues",
133
+ 'About':
134
+ """
135
+ # Whisper-TikTok
136
+ Whisper-TikTok is an innovative AI-powered tool that leverages the prowess of Edge TTS, OpenAI-Whisper, and FFMPEG to craft captivating TikTok videos also with a web application interface!
137
+
138
+ Mantainer: https://github.com/MatteoFasulo
139
+
140
+ If you find a bug or if you just have questions about the project feel free to reach me at https://github.com/MatteoFasulo/Whisper-TikTok
141
+ Any contribution to this project is welcome to improve the quality of work!
142
+ """
143
+ }
144
+ )
145
+
146
+ st.page_link("pages/reddit.py", label="Reddit", icon="πŸ€–")
147
+ st.page_link("https://github.com/MatteoFasulo/Whisper-TikTok",
148
+ label="GitHub", icon="🌎")
149
+
150
+
151
+ async def main():
152
+
153
+ st.title("πŸ† Whisper-TikTok πŸš€")
154
+ st.write("Create a TikTok video with text-to-speech of Microsoft Edge's TTS and subtitles of Whisper model.")
155
+
156
+ st.subheader("JSON Editor", help="Here you can edit the JSON file with the videos. Copy-and-paste is supported and compatible with Google Sheets, Excel, and others. You can do bulk-editing by dragging the handle on a cell (similar to Excel)!")
157
+ st.write("ℹ️ The JSON file is saved automatically when you click the button below. Every time you edit the JSON file, you must click the button to save the changes otherwise they will be lost.")
158
+ edited_df = st.data_editor(json_to_df('video.json'),
159
+ num_rows="dynamic")
160
+ st.button("Save JSON", on_click=df_to_json, args=(
161
+ edited_df,), help="Save the JSON file with the videos")
162
+
163
+ st.divider()
164
+
165
+ with st.sidebar:
166
+ model = st.selectbox(
167
+ "Whisper Model", ["tiny", "base", "small", "medium", "large"], index=2, help="The model used to generate the subtitles. The bigger the model, the better the results, but the slower the generation. The tiny model is recommended for testing purposes. Medium model is enough for good results in many languages.")
168
+
169
+ with st.expander("ℹ️ How to use"):
170
+ st.write(
171
+ """
172
+ 1. Choose the video to generate using the dropdown menu.
173
+ 2. Choose the model to use for the subtitles.
174
+ 3. Choose the voice to use for the text-to-speech.
175
+ 4. Choose the background video to use for the TikTok video.
176
+ 5. Choose the position of the subtitles.
177
+ 6. Choose the font, font color, and font size for the subtitles.
178
+ 7. Choose the URL of the background video to use for the TikTok video.
179
+ 8. Check the "Non-english" checkbox if you want to generate a video in a non-english language.
180
+ 9. Check the "Upload to TikTok" checkbox if you want to upload the video to TikTok using the TikTok session cookie. For this step it is required to have a TikTok account and to be logged in on your browser. Then the required cookies.txt file can be generated using this guide
181
+ """)
182
+
183
+ LEFT, RIGHT = st.columns(2)
184
+
185
+ with LEFT:
186
+ st.subheader("General settings")
187
+ tts_voice = st.selectbox(
188
+ "TTS Voice",
189
+ [f"{i['ShortName']} | {i['Gender']} | Tags: {i['VoiceTag']['VoicePersonalities']}" for i in await edge_tts.list_voices()], index=111, help="The voice used to generate the audio. The voice must be in the same language as the subtitles."
190
+ )
191
+
192
+ left, mid, right = st.columns(3)
193
+
194
+ with left:
195
+ # Subtitle font
196
+ font = st.selectbox(
197
+ "Subtitle font", ["Lexend Bold", "Lexend Regular", "Arial", "Roboto", "Big Condensed Black"], index=0, help="The font used for the subtitles.")
198
+ with mid:
199
+ # Subtitle font size
200
+ font_size = st.slider(
201
+ "Subtitle font size", 15, 50, 21, help="The font size for the subtitles. It is recommended to use a font size between 18 and 21.")
202
+ with right:
203
+ # Subtitle font color
204
+ font_color = st.color_picker(
205
+ "Subtitle font color", "#fff000", help="The color of the subtitles.")
206
+
207
+ # Subtitle position
208
+ left, right = st.columns(2)
209
+ with left:
210
+ sub_position = st.slider(
211
+ "Subtitle alignment (position)", 1, 9, 5, help="The position of the subtitles. 1 is the bottom left corner, 5 is the center, 9 is the top right corner. This is the alignment feature of FFMPEG subtitles.")
212
+ with right:
213
+ max_words = st.number_input(
214
+ "Maximum number of words per line", min_value=2, max_value=5, value=2, step=1, help="The maximum number of words per line for the subtitles. This is the feature for stable whisper model. It is recommended to use a value between 2 and 3.")
215
+
216
+ # Background Video URL
217
+ url = st.text_input(
218
+ "URL Background Video", "https://www.youtube.com/watch?v=dQw4w9WgXcQ", help="The URL of the background video to use for the TikTok video", placeholder="https://www.youtube.com/watch?v=intRX7BRA90")
219
+
220
+ left, mid, right = st.columns(3)
221
+
222
+ with left:
223
+ # Non-english
224
+ non_english = st.checkbox(
225
+ "Non-english", help="Check this if you want to generate a video in a non-english language")
226
+
227
+ with mid:
228
+ # Upload to TikTok
229
+ upload_tiktok = st.checkbox(
230
+ "Upload to TikTok", help="Upload the video to TikTok using the TikTok session cookie. For this step it is required to have a TikTok account and to be logged in on your browser. Then the required cookies.txt file can be generated using this guide (https://github.com/kairi003/Get-cookies.txt-LOCALLY). The cookies.txt file must be placed in the root folder of the project.")
231
+
232
+ with right:
233
+ # Verbose
234
+ verbose = st.checkbox(
235
+ "Verbose", help="Print the output of the commands used to create the video on your terminal. Useful for debugging.")
236
+
237
+ st.divider()
238
+
239
+ st.subheader("Video settings")
240
+
241
+ st.write("JSON file with the videos")
242
+ with open('video.json', encoding='utf-8') as fh:
243
+ video_json = st.json(json.load(fh), expanded=False)
244
+
245
+ # Get the list of files in "background"
246
+ folder_path = Path("background").absolute()
247
+ files = folder_path.glob('*.mp4')
248
+ files = [file.name for file in files]
249
+
250
+ # Create a Dropdown with the list of files
251
+ background_tab = st.selectbox(
252
+ "Your Backgrounds", files, index=0, help="The background video to use for the TikTok video")
253
+
254
+ # Choose which video to generate
255
+ videos = json.load(open("video.json"))
256
+
257
+ video_num = st.multiselect(
258
+ "Video",
259
+ options=videos,
260
+ format_func=lambda video: f"{video['series']} - {video['part']}",
261
+ default=[videos[0]],
262
+ help="The video to generate. If you want to generate multiple videos, select them as a multiselect."
263
+ )
264
+
265
+ if st.button("Generate Video"):
266
+ if not video_num:
267
+ st.error("You must select at least one video to generate")
268
+ return
269
+ global result
270
+ result = await generate_video(model, tts_voice, sub_position, font, font_color, font_size,
271
+ url, non_english, upload_tiktok, verbose, videos, background_tab, video_num, max_words)
272
+
273
+ with RIGHT:
274
+ if result:
275
+ # Put the video in a container
276
+ st.video(result)
277
+
278
+ if __name__ == "__main__":
279
+
280
+ if platform.system() == 'Windows':
281
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
282
+
283
+ loop = asyncio.new_event_loop()
284
+
285
+ loop.run_until_complete(main())
286
+
287
+ loop.close()
288
+
289
+ sys.exit(0)