shaheerawan3 commited on
Commit
2fa08f1
·
verified ·
1 Parent(s): 10f5b02

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -0
app.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from pathlib import Path
3
+ import requests
4
+ import json
5
+ from typing import List, Dict, Optional
6
+ from dataclasses import dataclass
7
+ from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip, AudioFileClip, ColorClip
8
+ import textwrap
9
+ from PIL import Image
10
+ import io
11
+ import random
12
+ from transformers import pipeline
13
+ import os
14
+
15
+ @dataclass
16
+ class ContentTheme:
17
+ name: str
18
+ keywords: List[str]
19
+ prompts: List[str]
20
+
21
+ THEMES = [
22
+ ContentTheme(
23
+ name="Discipline & Success",
24
+ keywords=["discipline", "success", "achievement", "goals"],
25
+ prompts=[
26
+ "Share a powerful insight about the role of discipline in achieving success",
27
+ "Explain how successful people maintain their daily routines",
28
+ "Describe the connection between self-discipline and reaching goals"
29
+ ]
30
+ ),
31
+ ContentTheme(
32
+ name="Psychology & Mindset",
33
+ keywords=["psychology", "mindset", "growth", "mental-strength"],
34
+ prompts=[
35
+ "Reveal a psychological principle that can transform someone's life",
36
+ "Explain a cognitive bias that holds people back",
37
+ "Share a mindset shift that leads to breakthrough success"
38
+ ]
39
+ ),
40
+ ContentTheme(
41
+ name="Motivation & Drive",
42
+ keywords=["motivation", "inspiration", "drive", "ambition"],
43
+ prompts=[
44
+ "Generate a powerful quote about never giving up",
45
+ "Share an insight about maintaining motivation during tough times",
46
+ "Explain what separates winners from losers in life"
47
+ ]
48
+ )
49
+ ]
50
+
51
+ class ContentGenerator:
52
+ def __init__(self, pixabay_api_key: str, elevenlabs_api_key: str):
53
+ self.pixabay_api_key = pixabay_api_key
54
+ self.elevenlabs_api_key = elevenlabs_api_key
55
+ self.generator = pipeline('text-generation', model='gpt2')
56
+
57
+ def generate_text_content(self, theme: ContentTheme) -> Dict[str, str]:
58
+ """Generate AI text content based on theme"""
59
+ prompt = random.choice(theme.prompts)
60
+ main_text = self.generator(prompt, max_length=100, num_return_sequences=1)[0]['generated_text']
61
+
62
+ # Generate an accompanying quote
63
+ quote_prompt = f"Generate an inspirational quote about {random.choice(theme.keywords)}"
64
+ quote = self.generator(quote_prompt, max_length=50, num_return_sequences=1)[0]['generated_text']
65
+
66
+ return {
67
+ "main_text": main_text,
68
+ "quote": quote
69
+ }
70
+
71
+ def fetch_background_media(self, theme: ContentTheme) -> str:
72
+ """Fetch background image/video from Pixabay"""
73
+ keyword = random.choice(theme.keywords)
74
+ url = f"https://pixabay.com/api/videos/?key={self.pixabay_api_key}&q={keyword}"
75
+ response = requests.get(url)
76
+ data = response.json()
77
+
78
+ if data["hits"]:
79
+ video_url = data["hits"][0]["videos"]["medium"]["url"]
80
+ # Download video
81
+ video_response = requests.get(video_url)
82
+ with open("temp_background.mp4", "wb") as f:
83
+ f.write(video_response.content)
84
+ return "temp_background.mp4"
85
+ return None
86
+
87
+ def generate_voiceover(self, text: str, output_path: str = "voiceover.mp3"):
88
+ """Generate voiceover using ElevenLabs"""
89
+ url = "https://api.elevenlabs.io/v1/text-to-speech"
90
+ headers = {
91
+ "Authorization": f"Bearer {self.elevenlabs_api_key}",
92
+ "Content-Type": "application/json"
93
+ }
94
+ data = {
95
+ "text": text,
96
+ "voice_settings": {
97
+ "stability": 0.5,
98
+ "similarity_boost": 0.5
99
+ }
100
+ }
101
+
102
+ response = requests.post(url, json=data, headers=headers)
103
+ if response.status_code == 200:
104
+ with open(output_path, "wb") as f:
105
+ f.write(response.content)
106
+ return output_path
107
+ return None
108
+
109
+ def create_video(self,
110
+ background_path: str,
111
+ text_content: Dict[str, str],
112
+ audio_path: str,
113
+ output_path: str = "output.mp4"):
114
+ """Create final video with all elements"""
115
+ # Load background
116
+ background = VideoFileClip(background_path).resize(width=1080)
117
+ duration = 15 # Standard Instagram Reels duration
118
+
119
+ # Create text clips
120
+ main_text = TextClip(
121
+ txt=textwrap.fill(text_content["main_text"], width=30),
122
+ fontsize=40,
123
+ color='white',
124
+ font='Arial-Bold',
125
+ stroke_color='black',
126
+ stroke_width=2
127
+ ).set_position(('center', 'center')).set_duration(duration)
128
+
129
+ quote = TextClip(
130
+ txt=textwrap.fill(text_content["quote"], width=35),
131
+ fontsize=30,
132
+ color='white',
133
+ font='Arial',
134
+ stroke_color='black',
135
+ stroke_width=1
136
+ ).set_position(('center', 0.8), relative=True).set_duration(duration)
137
+
138
+ # Compose video
139
+ video = CompositeVideoClip([
140
+ background,
141
+ main_text,
142
+ quote
143
+ ])
144
+
145
+ # Add audio
146
+ if audio_path:
147
+ audio = AudioFileClip(audio_path)
148
+ video = video.set_audio(audio)
149
+
150
+ # Write final video
151
+ video.write_videofile(output_path, fps=30)
152
+ return output_path
153
+
154
+ def main():
155
+ st.title("Advanced Instagram Content Generator")
156
+
157
+ # API Keys (in practice, these should be in environment variables)
158
+ pixabay_api_key = st.sidebar.text_input("Pixabay API Key", type="password")
159
+ elevenlabs_api_key = st.sidebar.text_input("ElevenLabs API Key", type="password")
160
+
161
+ theme_names = [theme.name for theme in THEMES]
162
+ selected_theme_name = st.selectbox("Select Content Theme", theme_names)
163
+ selected_theme = next(theme for theme in THEMES if theme.name == selected_theme_name)
164
+
165
+ if st.button("Generate Content"):
166
+ if not pixabay_api_key or not elevenlabs_api_key:
167
+ st.error("Please provide both API keys")
168
+ return
169
+
170
+ with st.spinner("Generating your content..."):
171
+ generator = ContentGenerator(pixabay_api_key, elevenlabs_api_key)
172
+
173
+ # Generate all content components
174
+ text_content = generator.generate_text_content(selected_theme)
175
+ background_path = generator.fetch_background_media(selected_theme)
176
+ voiceover_path = generator.generate_voiceover(text_content["main_text"])
177
+
178
+ if all([background_path, voiceover_path]):
179
+ output_path = generator.create_video(
180
+ background_path,
181
+ text_content,
182
+ voiceover_path
183
+ )
184
+
185
+ # Show preview and download button
186
+ st.video(output_path)
187
+ with open(output_path, "rb") as file:
188
+ st.download_button(
189
+ label="Download Video",
190
+ data=file,
191
+ file_name="instagram_content.mp4",
192
+ mime="video/mp4"
193
+ )
194
+ else:
195
+ st.error("Error generating content. Please try again.")
196
+
197
+ if __name__ == "__main__":
198
+ main()