userIdc2024 commited on
Commit
292ead2
·
verified ·
1 Parent(s): 1df76eb

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +248 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,250 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
 
3
  import streamlit as st
4
+ from functools import lru_cache
5
 
6
+ from audio_gen import audio_generation
7
+ from caption_gen import caption_generation
8
+ from image_gen import image_generation_change_background
9
+ from video_gen import video_generation
10
+ from prompt_generator import generate_segments_payload, VeoInputs
11
+
12
+ from dotenv import load_dotenv
13
+
14
+
15
+ load_dotenv()
16
+
17
+ # --- Logger ---
18
+ logging.basicConfig(
19
+ level=logging.INFO,
20
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
21
+ )
22
+ logger = logging.getLogger("video_generator_tools")
23
+
24
+ st.set_page_config(page_title="Video Generator Tools", layout="wide")
25
+
26
+ def main_app():
27
+ st.title("Video Generator Tools")
28
+
29
+ tabs = st.tabs([
30
+ "JSON Prompt Generator",
31
+ "Video Generation",
32
+ "Audio Generator",
33
+ "Image Generation",
34
+ "Generate Caption",
35
+ ])
36
+
37
+ # JSON Prompt Generator
38
+ with tabs[0]:
39
+ st.subheader("JSON Prompt Generator")
40
+ with st.form("json_prompt_form", clear_on_submit=False):
41
+ script = st.text_area("Script", height=200, placeholder="Paste the full script...")
42
+ style = st.text_input("Style", value="clean, lifestyle UGC")
43
+ json_format = st.selectbox("jsonFormat", ["standard", "compact", "verbose"], index=0)
44
+ continuation = st.toggle("continuationMode", value=True)
45
+ voice_type = st.text_input("voiceType", value="")
46
+ energy_level = st.text_input("energyLevel", value="")
47
+ setting_mode = st.selectbox("settingMode", ["single", "multi"], index=0)
48
+ camera_style = st.text_input("cameraStyle", value="")
49
+ energy_arc = st.text_input("energyArc", value="")
50
+ narrative_style = st.text_input("narrativeStyle", value="")
51
+ accent_region = st.text_input("accentRegion", value="")
52
+ image_upload = st.file_uploader("First frame image (optional)", type=["png", "jpg", "jpeg", "webp"])
53
+ submitted = st.form_submit_button("Generate Segments Payload")
54
+
55
+ if submitted:
56
+ try:
57
+ image_bytes = image_upload.read() if image_upload else None
58
+ logger.info("JSON Prompt: script_len=%d style='%s' jsonFormat='%s' img=%s",
59
+ len(script or ""), style, json_format, bool(image_bytes))
60
+
61
+ inputs = VeoInputs(
62
+ script=script or "",
63
+ style=style or "",
64
+ jsonFormat=json_format,
65
+ continuationMode=continuation,
66
+ voiceType=voice_type or None,
67
+ energyLevel=energy_level or None,
68
+ settingMode=setting_mode,
69
+ cameraStyle=camera_style or None,
70
+ energyArc=energy_arc or None,
71
+ narrativeStyle=narrative_style or None,
72
+ accentRegion=accent_region or None,
73
+ )
74
+
75
+ with st.spinner("Generating segments payload..."):
76
+ payload = generate_segments_payload(inputs, image_path=image_bytes, model="gpt-4o")
77
+ st.success("Segments payload generated")
78
+ st.json(payload)
79
+ st.toast("Segments JSON ready", icon="✅")
80
+ except Exception as e:
81
+ logger.exception("JSON Prompt Generator failed")
82
+ st.error(f"Error: {e}")
83
+
84
+ # Video Generation
85
+ with tabs[1]:
86
+ st.subheader("Video Generation")
87
+ with st.form("video_generation_form", clear_on_submit=False):
88
+ ref_image = st.file_uploader("Upload an image (used as initial frame)", type=["png", "jpg", "jpeg", "webp"])
89
+ prompt = st.text_area("Prompt", height=140, placeholder="Describe the scene, motion, camera, mood…")
90
+ aspect = st.selectbox("Aspect ratio", ["9:16", "16:9"], index=0)
91
+ resolution = st.selectbox("Resolution", ["720p", "1080p"], index=0)
92
+ gen = st.form_submit_button("Generate Video")
93
+
94
+ if gen:
95
+ if not ref_image:
96
+ st.error("Please upload an image.")
97
+ else:
98
+ try:
99
+ image_bytes = ref_image.read()
100
+ logger.info("Video Gen: img_bytes=%d aspect=%s res=%s prompt_len=%d",
101
+ len(image_bytes or b""), aspect, resolution, len(prompt or ""))
102
+
103
+ with st.spinner("Generating video..."):
104
+ url = video_generation(image_bytes, prompt, aspect, resolution)
105
+
106
+ if url:
107
+ st.success("Video generation request created")
108
+ st.video(url)
109
+ st.write(url)
110
+ st.toast("Video ready", icon="🎬")
111
+ else:
112
+ st.error("No video URL returned.")
113
+ logger.warning("Video Gen: empty URL")
114
+ except Exception as e:
115
+ logger.exception("Video Generation failed")
116
+ st.error(f"Error: {e}")
117
+
118
+ # Audio Generator
119
+ with tabs[2]:
120
+ st.subheader("Audio Generator")
121
+ with st.form("audio_generation_form", clear_on_submit=False):
122
+ scripts = st.text_area("Scripts", height=180, placeholder="Enter narration text…")
123
+ voice_id = st.selectbox("Voice ID", ["alloy", "verse", "sonnet", "narrator"], index=0)
124
+ speed = st.slider("Speed", min_value=0.5, max_value=2.0, value=1.0, step=0.1)
125
+ volume = st.slider("Volume", min_value=1.0, max_value=5.0, value=1.0, step=0.5)
126
+ pitch = st.slider("Pitch (semitones)", min_value=-12, max_value=12, value=0, step=1)
127
+ emotion = st.selectbox("Emotion", ["neutral", "confident", "warm", "excited", "serious"], index=0)
128
+ make_audio = st.form_submit_button("Generate Audio")
129
+
130
+ if make_audio:
131
+ if not scripts.strip():
132
+ st.error("Please enter scripts text.")
133
+ else:
134
+ try:
135
+ logger.info("Audio Gen: voice_id=%s speed=%.2f volume=%.2f pitch=%d emotion=%s text_len=%d",
136
+ voice_id, speed, volume, pitch, emotion, len(scripts or ""))
137
+
138
+ with st.spinner("Generating audio..."):
139
+ url = audio_generation(scripts, voice_id, speed, volume, pitch, emotion)
140
+
141
+ if url:
142
+ st.success("Audio generated")
143
+ st.audio(url)
144
+ st.write(url)
145
+ st.toast("Audio ready", icon="🔊")
146
+ else:
147
+ st.error("No audio URL returned.")
148
+ logger.warning("Audio Gen: empty URL")
149
+ except Exception as e:
150
+ logger.exception("Audio Generation failed")
151
+ st.error(f"Error: {e}")
152
+
153
+ # Image Generation (BG Change)
154
+ with tabs[3]:
155
+ st.subheader("Image Generation (for changing character's background)")
156
+ with st.form("image_generation_form", clear_on_submit=False):
157
+ img = st.file_uploader("Input image", type=["png", "jpg", "jpeg", "webp"])
158
+ img_prompt = st.text_input("Prompt", placeholder="New background description, style cues, lighting…")
159
+ ar = st.selectbox("Aspect ratio", ["9:16", "16:9"], index=0)
160
+ gen_img = st.form_submit_button("Generate Image")
161
+
162
+ if gen_img:
163
+ if not img:
164
+ st.error("Please upload an image.")
165
+ else:
166
+ try:
167
+ raw = img.read()
168
+ logger.info("Image Gen: bytes=%d ar=%s prompt_len=%d", len(raw or b""), ar, len(img_prompt or ""))
169
+
170
+ with st.spinner("Generating image..."):
171
+ url = image_generation_change_background(raw, img_prompt, ar)
172
+
173
+ if url:
174
+ st.success("Image processed")
175
+ cols = st.columns(2)
176
+ with cols[0]:
177
+ st.caption("Input")
178
+ st.image(img, use_container_width=True)
179
+ with cols[1]:
180
+ st.caption("Output")
181
+ st.image(url, use_container_width=True)
182
+ st.write(url)
183
+ st.toast("Image ready", icon="🖼️")
184
+ else:
185
+ st.error("No image URL returned.")
186
+ logger.warning("Image Gen: empty URL")
187
+ except Exception as e:
188
+ logger.exception("Image Generation failed")
189
+ st.error(f"Error: {e}")
190
+
191
+ # Generate Caption
192
+ with tabs[4]:
193
+ st.subheader("Generate Caption")
194
+ with st.form("caption_form", clear_on_submit=False):
195
+ cap_video = st.file_uploader("Input video", type=["mp4", "mov", "mkv"])
196
+ cap_size = st.slider("Caption size (characters)", min_value=10, max_value=100, value=30, step=5)
197
+ color = st.text_input("Highlight color (hex)", value="#FFD400")
198
+ make_caps = st.form_submit_button("Generate Captions")
199
+
200
+ if make_caps:
201
+ if not cap_video:
202
+ st.error("Please upload a video.")
203
+ else:
204
+ try:
205
+ vbytes = cap_video.read()
206
+ logger.info("Caption Gen: video_bytes=%d cap_size=%d color=%s",
207
+ len(vbytes or b""), int(cap_size), color)
208
+
209
+ with st.spinner("Generating captions..."):
210
+ url = caption_generation(vbytes, cap_size, color)
211
+
212
+ if url:
213
+ st.success("Captions generated")
214
+ st.video(url)
215
+ st.write(url)
216
+ st.toast("Captioned video ready", icon="🎞️")
217
+ else:
218
+ st.error("No captioned video URL returned.")
219
+ logger.warning("Caption Gen: empty URL")
220
+ except Exception as e:
221
+ logger.exception("Caption Generation failed")
222
+ st.error(f"Error: {e}")
223
+
224
+ @lru_cache(maxsize=1)
225
+ def check_token_cached(user_token: str):
226
+ ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
227
+ if not ACCESS_TOKEN:
228
+ return False, "Server error: Access token not configured."
229
+ if user_token == ACCESS_TOKEN:
230
+ return True, ""
231
+ return False, "Invalid token."
232
+
233
+ def main():
234
+ if "authenticated" not in st.session_state:
235
+ st.session_state["authenticated"] = False
236
+ if not st.session_state["authenticated"]:
237
+ st.markdown("## Access Required")
238
+ token_input = st.text_input("Enter Access Token", type="password")
239
+ if st.button("Unlock App"):
240
+ ok, error_msg = check_token_cached(token_input)
241
+ if ok:
242
+ st.session_state["authenticated"] = True
243
+ st.rerun()
244
+ else:
245
+ st.error(error_msg)
246
+ else:
247
+ main_app()
248
+
249
+ if __name__ == "__main__":
250
+ main()