YUVALON commited on
Commit
c7bd8fd
Β·
verified Β·
1 Parent(s): 73174c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -178
app.py CHANGED
@@ -1,229 +1,210 @@
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()
 
 
 
 
 
1
  import gradio as gr
2
  import torch
3
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer, set_seed
 
4
  import random
5
+ import re
6
 
7
+ # Load the model and tokenizer
8
+ model_name = "gpt2"
9
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name)
10
+ model = GPT2LMHeadModel.from_pretrained(model_name)
11
+
12
+ # Add padding token
13
+ tokenizer.pad_token = tokenizer.eos_token
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ def clean_caption(caption):
16
  """Clean and format the generated caption"""
17
+ # Remove any leading/trailing whitespace
18
+ caption = caption.strip()
19
+
20
+ # Remove incomplete sentences at the end
21
+ sentences = caption.split('.')
22
+ if len(sentences) > 1:
23
+ caption = sentences[0] + '.'
24
+
25
+ # Ensure it ends with proper punctuation
26
+ if not caption.endswith(('.', '!', '?')):
27
+ caption += '.'
28
+
29
+ # Remove extra spaces
30
+ caption = re.sub(r'\s+', ' ', caption)
31
+
32
+ # Capitalize first letter
33
+ if caption:
34
+ caption = caption[0].upper() + caption[1:]
35
+
36
+ return caption
 
 
 
37
 
38
+ def generate_instagram_captions(description, num_captions=5):
39
+ """Generate Instagram-style captions based on description"""
40
+
41
+ # Different prompt templates for variety
42
+ prompt_templates = [
43
+ f"Instagram caption about {description}:",
44
+ f"Perfect caption for {description}:",
45
+ f"Instagram post about {description}:",
46
+ f"Caption for a photo of {description}:",
47
+ f"Social media caption about {description}:"
 
 
 
 
 
 
 
 
 
 
48
  ]
49
 
50
+ captions = []
 
51
 
52
+ for i in range(num_captions):
53
+ # Use different prompt templates for variety
54
+ prompt = prompt_templates[i % len(prompt_templates)]
55
+
56
+ # Set different seeds for variety
57
+ set_seed(42 + i * 10)
58
+
59
+ # Tokenize the prompt
60
+ inputs = tokenizer.encode(prompt, return_tensors="pt")
61
+
62
  # Generate text
63
+ with torch.no_grad():
64
+ outputs = model.generate(
65
+ inputs,
66
+ max_length=inputs.shape[1] + 50,
67
+ num_return_sequences=1,
68
+ temperature=0.8 + (i * 0.1), # Vary temperature for diversity
69
+ do_sample=True,
70
+ top_p=0.9,
71
+ top_k=50,
72
+ pad_token_id=tokenizer.eos_token_id,
73
+ repetition_penalty=1.2
74
+ )
75
+
76
+ # Decode the generated text
77
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
78
 
79
+ # Extract caption (remove the prompt)
80
+ caption = generated_text.replace(prompt, "").strip()
 
81
 
82
+ # Clean and format the caption
83
+ caption = clean_caption(caption)
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ # Add some Instagram-style elements randomly
86
+ instagram_elements = ["✨", "🌟", "πŸ’«", "πŸ”₯", "πŸ’―", "πŸ™Œ", "❀️", "🌈", "β˜€οΈ", "πŸŒ™"]
87
+ if random.random() < 0.3: # 30% chance to add an emoji
88
+ caption = caption.rstrip('.!?') + f" {random.choice(instagram_elements)}"
 
89
 
90
+ captions.append(caption)
91
+
92
+ return captions
93
+
94
+ def generate_captions_interface(description):
95
+ """Interface function for Gradio"""
96
+ if not description.strip():
97
+ return "Please enter a description to generate captions!"
98
+
99
+ try:
100
+ captions = generate_instagram_captions(description.strip())
101
 
102
+ # Format captions as numbered list
103
+ formatted_captions = []
104
+ for i, caption in enumerate(captions, 1):
105
+ formatted_captions.append(f"{i}. {caption}")
106
+
107
+ return "\n\n".join(formatted_captions)
108
+
109
  except Exception as e:
110
+ return f"Error generating captions: {str(e)}"
 
111
 
112
  # Create the Gradio interface
113
  with gr.Blocks(
114
+ theme=gr.themes.Soft(
115
+ primary_hue="blue",
116
+ secondary_hue="purple"
117
+ ),
118
+ title="πŸ“Έ Instacap – AI Instagram Caption Generator"
119
+ ) as app:
120
+
121
+ gr.Markdown(
122
+ """
123
+ # πŸ“Έ Instacap – AI Instagram Caption Generator
124
+
125
+ Transform your photo descriptions into catchy Instagram captions!
126
+ Simply describe your photo or the vibe you're going for, and get 5 unique, engaging captions.
127
+
128
+ **Examples:** "beach sunset", "coffee and books", "city nightlife", "cozy home vibes"
129
+ """
130
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  with gr.Row():
133
+ with gr.Column(scale=2):
134
  description_input = gr.Textbox(
135
+ label="Photo Description or Vibe",
136
+ placeholder="e.g., beach, sea & sun",
137
+ lines=2,
138
+ max_lines=3
139
  )
140
 
141
  generate_btn = gr.Button(
142
+ "Generate Captions",
143
  variant="primary",
144
+ size="lg"
145
  )
146
 
147
+ with gr.Column(scale=3):
148
+ output_captions = gr.Textbox(
149
+ label="Generated Instagram Captions",
150
+ lines=10,
151
+ max_lines=15,
 
152
  show_copy_button=True
153
  )
154
 
155
+ # Examples section
156
+ gr.Markdown("### πŸ’‘ Try these examples:")
157
+
158
+ examples = [
159
+ "beach sunset vibes",
160
+ "coffee morning routine",
161
+ "city lights at night",
162
+ "cozy reading corner",
163
+ "workout motivation",
164
+ "food photography",
165
+ "travel adventure",
166
+ "friendship moments"
167
+ ]
168
+
169
  gr.Examples(
170
+ examples=examples,
 
 
 
 
 
 
 
 
 
171
  inputs=description_input,
172
+ outputs=output_captions,
173
+ fn=generate_captions_interface,
174
  cache_examples=False
175
  )
176
 
177
+ # Set up the event handlers
178
  generate_btn.click(
179
+ fn=generate_captions_interface,
180
  inputs=description_input,
181
+ outputs=output_captions
182
  )
183
 
 
184
  description_input.submit(
185
+ fn=generate_captions_interface,
186
  inputs=description_input,
187
+ outputs=output_captions
188
  )
189
 
190
+ gr.Markdown(
191
  """
192
+ ---
193
+
194
+ **Tips for better captions:**
195
+ - Be specific with your description
196
+ - Include emotions or moods
197
+ - Mention key visual elements
198
+ - Try different variations of the same concept
199
+
200
+ *Generated captions are AI-created and may need editing for your specific needs.*
201
  """
202
  )
203
 
204
  # Launch the app
205
  if __name__ == "__main__":
206
+ app.launch(
207
+ share=True,
208
+ server_name="0.0.0.0",
209
+ server_port=7860
210
+ )