shaheerawan3 commited on
Commit
220da35
Β·
verified Β·
1 Parent(s): 1d08da9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -134
app.py CHANGED
@@ -1,40 +1,13 @@
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"])
@@ -62,16 +35,16 @@ with tab1:
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)
@@ -83,132 +56,121 @@ with tab1:
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)
 
1
  import streamlit as st
2
  import json
3
+ from gradio_client import Client
4
  import time
5
 
6
  st.set_page_config(page_title="AI Video Ad Generator", page_icon="🎬", layout="wide")
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  # Main title
9
  st.title("🎬 AI Video Advertisement Generator")
10
+ st.markdown("Generate professional video ads from JSON using free community GPU models")
11
 
12
  # Tabs
13
  tab1, tab2 = st.tabs(["πŸŽ₯ Generate Video", "πŸ“– Guide"])
 
35
  height=300
36
  )
37
 
38
+ # Model selection
39
+ with st.expander("βš™οΈ Model Settings"):
40
+ model_space = st.selectbox(
41
+ "Model Space",
42
+ [
43
+ "THUDM/CogVideoX-5B",
44
+ "THUDM/CogVideoX-2B"
45
+ ],
46
+ help="CogVideoX models via community Spaces"
47
  )
 
 
 
48
 
49
  # Generate button
50
  generate_btn = st.button("🎬 Generate Video Ad", type="primary", use_container_width=True)
 
56
 
57
  # Generation logic
58
  if generate_btn:
59
+ try:
60
+ # Parse JSON
61
+ ad_config = json.loads(json_input)
62
+
63
+ # Build cinematic prompt from JSON
64
+ prompt = f"""Professional commercial advertisement video showcasing {ad_config.get('product', 'product')},
 
 
 
65
  {ad_config.get('visual_style', 'cinematic')} style, {ad_config.get('camera_movement', 'smooth camera movement')},
66
  {ad_config.get('lighting', 'professional lighting')}, {ad_config.get('background', 'modern background')},
67
  {ad_config.get('mood', 'premium')} aesthetic, product-focused hero shot,
68
  {', '.join(ad_config.get('key_features', []))}, commercial quality, 4K resolution,
69
  professional advertising photography, luxury brand style, high-end production value"""
70
+
71
+ status_placeholder.info(f"🎨 Connecting to {model_space}...")
72
+
73
+ with st.spinner("🎬 Generating video... This takes 60-120 seconds"):
74
+ try:
75
+ # Try to connect to community Space
76
+ client = Client(model_space)
77
+
78
+ # Generate video
79
+ result = client.predict(
 
 
 
 
 
80
  prompt=prompt,
81
+ api_name="/predict"
82
  )
 
 
 
 
 
 
 
83
 
84
+ status_placeholder.success("βœ… Video generated successfully!")
85
+
86
+ # Display video
87
+ if isinstance(result, str):
88
+ video_placeholder.video(result)
89
+
90
+ with open(result, "rb") as f:
91
+ video_bytes = f.read()
92
+
93
+ st.download_button(
94
+ label="⬇️ Download Video",
95
+ data=video_bytes,
96
+ file_name=f"ad_{ad_config.get('product', 'video').replace(' ', '_')}.mp4",
97
+ mime="video/mp4",
98
+ use_container_width=True
99
+ )
100
+
101
+ # Show generated prompt
102
+ with st.expander("πŸ“ Generated Prompt"):
103
+ st.text(prompt)
104
+
105
+ except Exception as api_error:
106
+ status_placeholder.error(f"""
107
+ ⚠️ **Free GPU queue is full or Space unavailable**
108
 
109
+ **Alternative Options:**
110
+ 1. Try again in a few minutes (queue clears)
111
+ 2. Use a paid service like Replicate or Fal.ai
112
+ 3. Deploy your own GPU Space (requires payment)
113
+
114
+ Technical error: {str(api_error)}
115
+ """)
116
+
117
+ except json.JSONDecodeError:
118
+ st.error("❌ Invalid JSON format. Please check your input.")
119
+ except Exception as e:
120
+ st.error(f"❌ Error: {str(e)}")
121
 
122
  with tab2:
123
  st.markdown("""
124
+ ## 🎯 How It Works
 
 
 
 
 
125
 
126
+ This app calls **community-hosted HuggingFace Spaces** with free GPU access.
 
127
 
128
+ ### ⚠️ Important Limitations
 
 
 
 
 
 
 
 
129
 
130
+ - **Queue wait times**: Popular Spaces have queues (2-5 minutes)
131
+ - **Availability**: Spaces may go offline
132
+ - **Generation time**: 60-120 seconds per video
133
+ - **Video length**: 5-10 seconds maximum
134
 
135
+ ### πŸ”„ If Generation Fails
136
 
137
+ The free models have limited capacity. Options:
 
 
138
 
139
+ 1. **Wait and retry** - Queues clear quickly
140
+ 2. **Use paid APIs**:
141
+ - Replicate.com ($0.01-0.05/video)
142
+ - Fal.ai ($0.05-0.15/video)
143
+ - Runway ML (paid plans)
144
+ 3. **Self-host** with your own GPU Space
145
 
146
+ ### πŸ’‘ JSON Configuration
 
 
 
 
147
 
 
 
 
148
  ```json
149
  {
150
+ "product": "What you're advertising",
151
+ "visual_style": "cinematic/dynamic/elegant",
152
+ "camera_movement": "rotation/zoom/pan",
153
+ "lighting": "dramatic/soft/studio",
154
+ "background": "gradient/solid/abstract",
155
+ "mood": "premium/energetic/calm",
156
+ "key_features": ["feature1", "feature2"]
157
  }
158
  ```
159
 
160
+ ### πŸš€ For Production Use
161
+
162
+ Free models are **NOT suitable for production**. Consider:
163
+
164
+ - **Replicate API** - Pay per generation, reliable
165
+ - **Runway ML** - Professional video generation
166
+ - **Luma Dream Machine** - High quality, paid
167
+ - **Self-hosted GPU** - Full control, requires infrastructure
 
 
168
  """)
169
 
170
  # Footer
171
  st.divider()
172
  st.markdown("""
173
  <div style='text-align: center; color: #666;'>
174
+ <p>⚠️ Using free community Spaces - expect wait times and availability issues</p>
175
  </div>
176
  """, unsafe_allow_html=True)