shaheerawan3 commited on
Commit
868c32d
Β·
verified Β·
1 Parent(s): 021a685

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +212 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,214 @@
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 streamlit as st
2
+ import json
3
+ from huggingface_hub import InferenceClient
4
+ import time
5
 
6
+ st.set_page_config(page_title="AI Video Ad Generator", page_icon="🎬", layout="wide")
7
+
8
+ # Initialize session state
9
+ if 'api_token' not in st.session_state:
10
+ st.session_state.api_token = ""
11
+
12
+ # Sidebar - API Token
13
+ with st.sidebar:
14
+ st.header("πŸ”‘ Configuration")
15
+ api_token = st.text_input(
16
+ "HuggingFace API Token",
17
+ type="password",
18
+ value=st.session_state.api_token,
19
+ help="Get your token from https://huggingface.co/settings/tokens"
20
+ )
21
+ if api_token:
22
+ st.session_state.api_token = api_token
23
+
24
+ st.divider()
25
+ st.markdown("### πŸ“‹ JSON Structure")
26
+ st.code("""{
27
+ "product": "laptop",
28
+ "style": "cinematic",
29
+ "mood": "premium",
30
+ "duration": "short",
31
+ "camera": "rotating",
32
+ "lighting": "studio"
33
+ }""", language="json")
34
+
35
+ # Main title
36
+ st.title("🎬 AI Video Advertisement Generator")
37
+ st.markdown("Generate professional video ads from JSON specifications using state-of-the-art AI")
38
+
39
+ # Tabs
40
+ tab1, tab2 = st.tabs(["πŸŽ₯ Generate Video", "πŸ“– Guide"])
41
+
42
+ with tab1:
43
+ col1, col2 = st.columns([1, 1])
44
+
45
+ with col1:
46
+ st.subheader("Input Configuration")
47
+
48
+ # JSON Input
49
+ json_input = st.text_area(
50
+ "Ad Specification (JSON)",
51
+ value="""{
52
+ "product": "premium laptop",
53
+ "brand_style": "modern tech",
54
+ "visual_style": "cinematic commercial",
55
+ "camera_movement": "smooth 360 rotation",
56
+ "lighting": "dramatic studio backlight",
57
+ "background": "gradient dark to light",
58
+ "mood": "premium luxury",
59
+ "key_features": ["ultra-thin", "metallic finish", "glowing edges"],
60
+ "duration": "5 seconds"
61
+ }""",
62
+ height=300
63
+ )
64
+
65
+ # Advanced settings
66
+ with st.expander("βš™οΈ Advanced Settings"):
67
+ model_choice = st.selectbox(
68
+ "Model",
69
+ ["tencent/HunyuanVideo", "THUDM/CogVideoX-5b", "genmo/mochi-1-preview"],
70
+ help="HunyuanVideo: Best quality | CogVideoX: Longer videos | Mochi: Fastest"
71
+ )
72
+
73
+ resolution = st.selectbox("Resolution", ["720p", "1080p"], index=0)
74
+ fps = st.slider("FPS", 24, 30, 24)
75
+
76
+ # Generate button
77
+ generate_btn = st.button("🎬 Generate Video Ad", type="primary", use_container_width=True)
78
+
79
+ with col2:
80
+ st.subheader("Generated Video")
81
+ video_placeholder = st.empty()
82
+ status_placeholder = st.empty()
83
+
84
+ # Generation logic
85
+ if generate_btn:
86
+ if not st.session_state.api_token:
87
+ st.error("⚠️ Please enter your HuggingFace API token in the sidebar")
88
+ else:
89
+ try:
90
+ # Parse JSON
91
+ ad_config = json.loads(json_input)
92
+
93
+ # Build cinematic prompt from JSON
94
+ prompt = f"""Professional commercial advertisement video showcasing {ad_config.get('product', 'product')},
95
+ {ad_config.get('visual_style', 'cinematic')} style, {ad_config.get('camera_movement', 'smooth camera movement')},
96
+ {ad_config.get('lighting', 'professional lighting')}, {ad_config.get('background', 'modern background')},
97
+ {ad_config.get('mood', 'premium')} aesthetic, product-focused hero shot,
98
+ {', '.join(ad_config.get('key_features', []))}, commercial quality, 4K resolution,
99
+ professional advertising photography, luxury brand style, high-end production value"""
100
+
101
+ status_placeholder.info(f"🎨 Generating with {model_choice}...")
102
+
103
+ # Initialize client
104
+ client = InferenceClient(token=st.session_state.api_token)
105
+
106
+ # Progress simulation
107
+ progress_bar = st.progress(0)
108
+ for i in range(100):
109
+ time.sleep(0.3)
110
+ progress_bar.progress(i + 1)
111
+
112
+ # Generate video
113
+ with st.spinner("🎬 Creating your video ad... (this may take 30-60 seconds)"):
114
+ video_bytes = client.text_to_video(
115
+ prompt=prompt,
116
+ model=model_choice
117
+ )
118
+
119
+ progress_bar.empty()
120
+ status_placeholder.success("βœ… Video generated successfully!")
121
+
122
+ # Display video
123
+ with col2:
124
+ video_placeholder.video(video_bytes)
125
+
126
+ st.download_button(
127
+ label="⬇️ Download Video",
128
+ data=video_bytes,
129
+ file_name=f"ad_{ad_config.get('product', 'video').replace(' ', '_')}.mp4",
130
+ mime="video/mp4",
131
+ use_container_width=True
132
+ )
133
+
134
+ # Show generated prompt
135
+ with st.expander("πŸ“ Generated Prompt"):
136
+ st.text(prompt)
137
+
138
+ except json.JSONDecodeError:
139
+ st.error("❌ Invalid JSON format. Please check your input.")
140
+ except Exception as e:
141
+ st.error(f"❌ Error: {str(e)}")
142
+ status_placeholder.empty()
143
+
144
+ with tab2:
145
+ st.markdown("""
146
+ ## 🎯 How to Use
147
+
148
+ ### 1️⃣ Get API Token
149
+ - Visit [HuggingFace Tokens](https://huggingface.co/settings/tokens)
150
+ - Create a new token with "read" permissions
151
+ - Paste it in the sidebar
152
+
153
+ ### 2️⃣ Configure Your Ad
154
+ Define your video ad using JSON with these properties:
155
+
156
+ - **product**: What you're advertising
157
+ - **brand_style**: Your brand aesthetic (modern, minimal, bold)
158
+ - **visual_style**: Video style (cinematic, dynamic, elegant)
159
+ - **camera_movement**: How camera moves (rotation, zoom, pan)
160
+ - **lighting**: Lighting setup (dramatic, soft, studio)
161
+ - **background**: Background style (gradient, solid, abstract)
162
+ - **mood**: Overall feeling (premium, energetic, calm)
163
+ - **key_features**: List of product highlights
164
+ - **duration**: Video length preference
165
+
166
+ ### 3️⃣ Generate
167
+ Click "Generate Video Ad" and wait 30-60 seconds
168
+
169
+ ### 🎨 Model Comparison
170
+
171
+ - **HunyuanVideo**: Best quality, photorealistic, 5-6 seconds
172
+ - **CogVideoX**: Good quality, longer duration, 10+ seconds
173
+ - **Mochi**: Fastest generation, 3-5 seconds, lightweight
174
+
175
+ ### πŸ’‘ Tips for Best Results
176
+
177
+ - Be specific about visual style and camera movement
178
+ - Include 3-5 key features maximum
179
+ - Use cinematic/commercial terminology
180
+ - Describe lighting and mood clearly
181
+ - Keep product name concise
182
+
183
+ ### ⚑ Example JSON Templates
184
+
185
+ **Tech Product:**
186
+ ```json
187
+ {
188
+ "product": "smartphone",
189
+ "visual_style": "Apple-style commercial",
190
+ "camera_movement": "slow orbit around device",
191
+ "lighting": "soft gradient backlight",
192
+ "mood": "minimalist premium"
193
+ }
194
+ ```
195
+
196
+ **Fashion/Lifestyle:**
197
+ ```json
198
+ {
199
+ "product": "luxury watch",
200
+ "visual_style": "high-fashion editorial",
201
+ "camera_movement": "close-up macro details",
202
+ "lighting": "dramatic side lighting",
203
+ "mood": "elegant timeless"
204
+ }
205
+ ```
206
+ """)
207
+
208
+ # Footer
209
+ st.divider()
210
+ st.markdown("""
211
+ <div style='text-align: center; color: #666;'>
212
+ <p>Powered by HuggingFace Inference API | Free GPU-accelerated video generation</p>
213
+ </div>
214
+ """, unsafe_allow_html=True)