YUVALON commited on
Commit
6365245
Β·
verified Β·
1 Parent(s): e27c9f5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +229 -0
app.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import pipeline, set_seed
4
+ import re
5
+ import random
6
+
7
+ # Set up the text generation pipeline
8
+ try:
9
+ # Try to use GPU if available, otherwise fallback to CPU
10
+ device = 0 if torch.cuda.is_available() else -1
11
+ generator = pipeline(
12
+ "text-generation",
13
+ model="gpt2-medium",
14
+ device=device,
15
+ pad_token_id=50256
16
+ )
17
+ except Exception as e:
18
+ print(f"Error loading model: {e}")
19
+ # Fallback to CPU with smaller model
20
+ generator = pipeline(
21
+ "text-generation",
22
+ model="gpt2",
23
+ device=-1,
24
+ pad_token_id=50256
25
+ )
26
+
27
+ def clean_caption(text):
28
+ """Clean and format the generated caption"""
29
+ # Remove the prompt part
30
+ lines = text.split('\n')
31
+ caption_lines = []
32
+
33
+ for line in lines:
34
+ line = line.strip()
35
+ if line and not line.startswith('Photo:') and not line.startswith('Caption:'):
36
+ caption_lines.append(line)
37
+
38
+ if caption_lines:
39
+ caption = caption_lines[0]
40
+ # Remove extra quotes or incomplete sentences
41
+ caption = re.sub(r'^["\']|["\']$', '', caption)
42
+ # Ensure it doesn't end mid-sentence
43
+ if caption and caption[-1] not in '.!?':
44
+ # Find the last complete sentence
45
+ sentences = re.split(r'[.!?]', caption)
46
+ if len(sentences) > 1:
47
+ caption = '.'.join(sentences[:-1]) + '.'
48
+ else:
49
+ caption = caption + '.'
50
+ return caption
51
+ return ""
52
+
53
+ def generate_instagram_caption(description):
54
+ """Generate an Instagram-style caption based on the photo description"""
55
+ if not description.strip():
56
+ return "Please enter a description of your photo!"
57
+
58
+ # Set a random seed for variety
59
+ set_seed(random.randint(1, 1000))
60
+
61
+ # Create Instagram-style prompts
62
+ prompts = [
63
+ f"Photo: {description}\nInstagram Caption: Living my best life",
64
+ f"Photo: {description}\nInstagram Caption: When life gives you",
65
+ f"Photo: {description}\nInstagram Caption: Just another day in paradise",
66
+ f"Photo: {description}\nInstagram Caption: Feeling grateful for",
67
+ f"Photo: {description}\nInstagram Caption: Making memories with",
68
+ f"Photo: {description}\nInstagram Caption: Can't get enough of",
69
+ f"Photo: {description}\nInstagram Caption: Sunday vibes",
70
+ f"Photo: {description}\nInstagram Caption: Good times and tan lines",
71
+ f"Photo: {description}\nInstagram Caption: Chasing sunsets and dreams",
72
+ f"Photo: {description}\nInstagram Caption: Life is better when you're"
73
+ ]
74
+
75
+ # Randomly select a prompt style
76
+ prompt = random.choice(prompts)
77
+
78
+ try:
79
+ # Generate text
80
+ generated = generator(
81
+ prompt,
82
+ max_length=len(prompt.split()) + 25, # Keep it short
83
+ num_return_sequences=1,
84
+ temperature=0.8,
85
+ do_sample=True,
86
+ top_p=0.9,
87
+ repetition_penalty=1.1,
88
+ pad_token_id=50256
89
+ )
90
+
91
+ # Extract and clean the caption
92
+ full_text = generated[0]['generated_text']
93
+ caption = clean_caption(full_text.replace(prompt, "").strip())
94
+
95
+ if not caption:
96
+ # Fallback captions if generation fails
97
+ fallback_captions = [
98
+ f"✨ {description} moments ✨",
99
+ f"Living for these {description} vibes 🌟",
100
+ f"Just me and my {description} mood πŸ“Έ",
101
+ f"When {description} hits different πŸ’«",
102
+ f"Grateful for {description} days like these πŸ™",
103
+ f"Making memories with {description} energy ⭐",
104
+ f"Can't get enough of this {description} life 🌈",
105
+ f"Sunday vibes: {description} edition πŸŒ…",
106
+ f"Chasing dreams and {description} scenes 🎨",
107
+ f"Life is better with {description} moments πŸ’•"
108
+ ]
109
+ caption = random.choice(fallback_captions)
110
+
111
+ # Add some popular hashtags occasionally
112
+ if random.random() < 0.3: # 30% chance to add hashtags
113
+ hashtags = ["#vibes", "#mood", "#life", "#grateful", "#memories", "#blessed", "#goodtimes", "#livingmybestlife"]
114
+ selected_tags = random.sample(hashtags, min(2, len(hashtags)))
115
+ caption += " " + " ".join(selected_tags)
116
+
117
+ return caption
118
+
119
+ except Exception as e:
120
+ print(f"Generation error: {e}")
121
+ return f"✨ {description} vibes ✨ #mood #life"
122
+
123
+ # Create the Gradio interface
124
+ with gr.Blocks(
125
+ theme=gr.themes.Soft(),
126
+ css="""
127
+ .main-header {
128
+ text-align: center;
129
+ background: linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1);
130
+ -webkit-background-clip: text;
131
+ -webkit-text-fill-color: transparent;
132
+ font-size: 2.5em;
133
+ font-weight: bold;
134
+ margin-bottom: 0.5em;
135
+ }
136
+ .subtitle {
137
+ text-align: center;
138
+ color: #666;
139
+ font-size: 1.1em;
140
+ margin-bottom: 2em;
141
+ }
142
+ .generate-btn {
143
+ background: linear-gradient(45deg, #ff6b6b, #4ecdc4) !important;
144
+ border: none !important;
145
+ color: white !important;
146
+ font-weight: bold !important;
147
+ font-size: 1.1em !important;
148
+ padding: 12px 24px !important;
149
+ border-radius: 25px !important;
150
+ transition: all 0.3s ease !important;
151
+ }
152
+ .generate-btn:hover {
153
+ transform: translateY(-2px) !important;
154
+ box-shadow: 0 5px 15px rgba(0,0,0,0.2) !important;
155
+ }
156
+ """
157
+ ) as demo:
158
+
159
+ gr.HTML('<h1 class="main-header">πŸ“Έ Instacap – AI Instagram Caption Generator</h1>')
160
+ gr.HTML('<p class="subtitle">Transform your photo descriptions into engaging Instagram captions!</p>')
161
+
162
+ with gr.Row():
163
+ with gr.Column(scale=1):
164
+ description_input = gr.Textbox(
165
+ label="Describe your photo",
166
+ placeholder="E.g., sunset beach picnic, cozy vibe",
167
+ lines=3,
168
+ max_lines=5
169
+ )
170
+
171
+ generate_btn = gr.Button(
172
+ "Generate Caption ✨",
173
+ variant="primary",
174
+ elem_classes="generate-btn"
175
+ )
176
+
177
+ with gr.Column(scale=1):
178
+ caption_output = gr.Textbox(
179
+ label="Your Instagram Caption",
180
+ lines=4,
181
+ max_lines=6,
182
+ interactive=False,
183
+ show_copy_button=True
184
+ )
185
+
186
+ # Add some example inputs
187
+ gr.Examples(
188
+ examples=[
189
+ ["sunset beach picnic, cozy vibe"],
190
+ ["coffee shop laptop work, productive morning"],
191
+ ["hiking mountain trail, adventure time"],
192
+ ["cozy rainy day reading, warm blanket"],
193
+ ["friends dinner party, laughter and good food"],
194
+ ["morning yoga session, peaceful zen"],
195
+ ["city skyline night view, urban lights"],
196
+ ["homemade cooking, delicious comfort food"]
197
+ ],
198
+ inputs=description_input,
199
+ outputs=caption_output,
200
+ fn=generate_instagram_caption,
201
+ cache_examples=False
202
+ )
203
+
204
+ # Connect the button to the function
205
+ generate_btn.click(
206
+ fn=generate_instagram_caption,
207
+ inputs=description_input,
208
+ outputs=caption_output
209
+ )
210
+
211
+ # Also trigger on Enter key
212
+ description_input.submit(
213
+ fn=generate_instagram_caption,
214
+ inputs=description_input,
215
+ outputs=caption_output
216
+ )
217
+
218
+ gr.HTML(
219
+ """
220
+ <div style="text-align: center; margin-top: 2em; color: #888; font-size: 0.9em;">
221
+ <p>πŸ’‘ Tip: Be specific with your descriptions for better captions!</p>
222
+ <p>🎨 Each generation creates a unique caption with different vibes</p>
223
+ </div>
224
+ """
225
+ )
226
+
227
+ # Launch the app
228
+ if __name__ == "__main__":
229
+ demo.launch()