YUVALON commited on
Commit
3776c4a
Β·
verified Β·
1 Parent(s): dba8fe8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -18
app.py CHANGED
@@ -26,28 +26,221 @@ except Exception as e:
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):
 
26
 
27
  def clean_caption(text):
28
  """Clean and format the generated caption"""
29
+ # Remove the prompt part and get first line
30
  lines = text.split('\n')
 
 
31
  for line in lines:
32
  line = line.strip()
33
  if line and not line.startswith('Photo:') and not line.startswith('Caption:'):
34
+ # Remove extra quotes
35
+ caption = re.sub(r'^["\']|["\']
36
+
37
+ def generate_instagram_caption(description):
38
+ """Generate 5 clever Instagram-style captions based on the photo description"""
39
+ if not description.strip():
40
+ return "Please enter a description of your photo!"
41
+
42
+ # Set a random seed for variety
43
+ set_seed(random.randint(1, 10000))
44
+
45
+ # Create multiple clever Instagram-style prompts
46
+ prompt_templates = [
47
+ f"Photo: {description}\nWitty Instagram caption: Just",
48
+ f"Photo: {description}\nClever Instagram caption: When",
49
+ f"Photo: {description}\nFunny Instagram caption: Living",
50
+ f"Photo: {description}\nSassy Instagram caption: Feeling",
51
+ f"Photo: {description}\nCute Instagram caption: Making",
52
+ f"Photo: {description}\nInspiring Instagram caption: Chasing",
53
+ f"Photo: {description}\nCool Instagram caption: Caught",
54
+ f"Photo: {description}\nRelatable Instagram caption: That",
55
+ f"Photo: {description}\nTrendy Instagram caption: Current",
56
+ f"Photo: {description}\nPlayful Instagram caption: Plot"
57
+ ]
58
+
59
+ captions = []
60
+
61
+ # Generate 5 different captions
62
+ for i in range(5):
63
+ # Use different prompts for variety
64
+ prompt = random.choice(prompt_templates)
65
+
66
+ try:
67
+ generated = generator(
68
+ prompt,
69
+ max_length=len(prompt.split()) + 15, # Keep it very short
70
+ num_return_sequences=1,
71
+ temperature=0.9,
72
+ do_sample=True,
73
+ top_p=0.95,
74
+ repetition_penalty=1.2,
75
+ pad_token_id=50256
76
+ )
77
+
78
+ full_text = generated[0]['generated_text']
79
+ caption = clean_caption(full_text.replace(prompt, "").strip())
80
+
81
+ if caption and len(caption) > 10: # Make sure it's substantial
82
+ captions.append(caption)
83
+
84
+ except Exception as e:
85
+ print(f"Generation error: {e}")
86
+ continue
87
+
88
+ # Fill with clever fallback captions if we don't have enough
89
+ clever_fallbacks = [
90
+ f"✨ {description} kind of day ✨",
91
+ f"Plot twist: {description} was exactly what I needed",
92
+ f"Current mood: {description} energy",
93
+ f"Just me living my {description} dreams",
94
+ f"When life gives you {description}, make memories",
95
+ f"Serving {description} realness",
96
+ f"That {description} life chose me",
97
+ f"POV: You're living for {description} moments",
98
+ f"Main character energy: {description} edition",
99
+ f"No caption needed, just {description} vibes",
100
+ f"Caught in 4K living my {description} fantasy",
101
+ f"This is what {description} happiness looks like",
102
+ f"Manifesting more {description} energy",
103
+ f"When the {description} hits different",
104
+ f"Today's agenda: {description} and good vibes",
105
+ f"Reminder: {description} days are the best days",
106
+ f"Living proof that {description} is everything",
107
+ f"My {description} era is here to stay",
108
+ f"Just another {description} adventure",
109
+ f"Grateful for {description} moments like these"
110
+ ]
111
+
112
+ # Add fallbacks if we need more captions
113
+ while len(captions) < 5:
114
+ fallback = random.choice(clever_fallbacks)
115
+ if fallback not in captions:
116
+ captions.append(fallback)
117
+
118
+ # Return top 5 captions
119
+ final_captions = captions[:5]
120
+
121
+ # Format as numbered list
122
+ result = ""
123
+ for i, caption in enumerate(final_captions, 1):
124
+ result += f"{i}. {caption}\n"
125
+
126
+ return result.strip()
127
+
128
+ # Create the Gradio interface
129
+ with gr.Blocks(
130
+ theme=gr.themes.Soft(),
131
+ css="""
132
+ .main-header {
133
+ text-align: center;
134
+ background: linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1);
135
+ -webkit-background-clip: text;
136
+ -webkit-text-fill-color: transparent;
137
+ font-size: 2.5em;
138
+ font-weight: bold;
139
+ margin-bottom: 0.5em;
140
+ }
141
+ .subtitle {
142
+ text-align: center;
143
+ color: #666;
144
+ font-size: 1.1em;
145
+ margin-bottom: 2em;
146
+ }
147
+ .generate-btn {
148
+ background: linear-gradient(45deg, #ff6b6b, #4ecdc4) !important;
149
+ border: none !important;
150
+ color: white !important;
151
+ font-weight: bold !important;
152
+ font-size: 1.1em !important;
153
+ padding: 12px 24px !important;
154
+ border-radius: 25px !important;
155
+ transition: all 0.3s ease !important;
156
+ }
157
+ .generate-btn:hover {
158
+ transform: translateY(-2px) !important;
159
+ box-shadow: 0 5px 15px rgba(0,0,0,0.2) !important;
160
+ }
161
+ """
162
+ ) as demo:
163
+
164
+ gr.HTML('<h1 class="main-header">πŸ“Έ Instacap – AI Instagram Caption Generator</h1>')
165
+ gr.HTML('<p class="subtitle">Transform your photo descriptions into engaging Instagram captions!</p>')
166
+
167
+ with gr.Row():
168
+ with gr.Column(scale=1):
169
+ description_input = gr.Textbox(
170
+ label="Describe your photo",
171
+ placeholder="E.g., sunset beach picnic, cozy vibe",
172
+ lines=3,
173
+ max_lines=5
174
+ )
175
+
176
+ generate_btn = gr.Button(
177
+ "Generate Caption ✨",
178
+ variant="primary",
179
+ elem_classes="generate-btn"
180
+ )
181
+
182
+ with gr.Column(scale=1):
183
+ caption_output = gr.Textbox(
184
+ label="Your 5 Instagram Caption Options",
185
+ lines=8,
186
+ max_lines=10,
187
+ interactive=False,
188
+ show_copy_button=True
189
+ )
190
+
191
+ # Add some example inputs
192
+ gr.Examples(
193
+ examples=[
194
+ ["sunset beach picnic, cozy vibe"],
195
+ ["coffee shop laptop work, productive morning"],
196
+ ["hiking mountain trail, adventure time"],
197
+ ["cozy rainy day reading, warm blanket"],
198
+ ["friends dinner party, laughter and good food"],
199
+ ["morning yoga session, peaceful zen"],
200
+ ["city skyline night view, urban lights"],
201
+ ["homemade cooking, delicious comfort food"]
202
+ ],
203
+ inputs=description_input,
204
+ outputs=caption_output,
205
+ fn=generate_instagram_caption,
206
+ cache_examples=False
207
+ )
208
+
209
+ # Connect the button to the function
210
+ generate_btn.click(
211
+ fn=generate_instagram_caption,
212
+ inputs=description_input,
213
+ outputs=caption_output
214
+ )
215
+
216
+ # Also trigger on Enter key
217
+ description_input.submit(
218
+ fn=generate_instagram_caption,
219
+ inputs=description_input,
220
+ outputs=caption_output
221
+ )
222
+
223
+ gr.HTML(
224
+ """
225
+ <div style="text-align: center; margin-top: 2em; color: #888; font-size: 0.9em;">
226
+ <p>πŸ’‘ Tip: Be specific with your descriptions for better captions!</p>
227
+ <p>🎨 Get 5 unique one-liner captions each time you generate</p>
228
+ <p>πŸ“‹ Copy your favorite caption and paste it on Instagram!</p>
229
+ </div>
230
+ """
231
+ )
232
+
233
+ # Launch the app
234
+ if __name__ == "__main__":
235
+ demo.launch(), '', line)
236
+ # Keep it short - cut at first sentence if too long
237
+ if len(caption) > 80:
238
+ sentences = re.split(r'[.!?]', caption)
239
+ if sentences[0]:
240
+ caption = sentences[0].strip()
241
+ if caption and caption[-1] not in '.!?':
242
+ caption += '.'
243
+ return caption
244
  return ""
245
 
246
  def generate_instagram_caption(description):