Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -25,7 +25,6 @@ MEME_TEMPLATES = {
|
|
| 25 |
"One Does Not Simply": "61579",
|
| 26 |
"Batman Slapping Robin": "438680",
|
| 27 |
"Ancient Aliens": "101470",
|
| 28 |
-
"X, X Everywhere": "347390",
|
| 29 |
}
|
| 30 |
|
| 31 |
def generate_meme_text(idea: str, model: str):
|
|
@@ -35,74 +34,57 @@ def generate_meme_text(idea: str, model: str):
|
|
| 35 |
return None, None, error
|
| 36 |
|
| 37 |
try:
|
| 38 |
-
prompt = f"""
|
| 39 |
|
| 40 |
-
|
| 41 |
-
TOP: [setup
|
| 42 |
-
BOTTOM: [punchline
|
| 43 |
|
| 44 |
-
|
| 45 |
-
TOP: When your code works
|
| 46 |
-
BOTTOM: On the first try
|
| 47 |
-
|
| 48 |
-
Now create for: "{idea}"
|
| 49 |
TOP:"""
|
| 50 |
|
| 51 |
-
# Use text_generation instead of chat_completion
|
| 52 |
response = client.text_generation(
|
| 53 |
prompt,
|
| 54 |
model=model,
|
| 55 |
-
max_new_tokens=
|
| 56 |
temperature=0.7,
|
| 57 |
-
do_sample=True,
|
| 58 |
return_full_text=False
|
| 59 |
)
|
| 60 |
|
| 61 |
# Parse response
|
| 62 |
-
|
| 63 |
-
lines = full_response.strip().split('\n')
|
| 64 |
|
| 65 |
top_text = ""
|
| 66 |
bottom_text = ""
|
| 67 |
|
| 68 |
-
for line in
|
| 69 |
line = line.strip()
|
| 70 |
if line.startswith("TOP:"):
|
| 71 |
-
top_text = line.replace("TOP:", "").strip()
|
| 72 |
elif line.startswith("BOTTOM:"):
|
| 73 |
-
bottom_text = line.replace("BOTTOM:", "").strip()
|
| 74 |
-
|
| 75 |
-
# Clean up text
|
| 76 |
-
top_text = top_text.split('\n')[0].strip('[]"\'')
|
| 77 |
-
bottom_text = bottom_text.split('\n')[0].strip('[]"\'')
|
| 78 |
|
|
|
|
| 79 |
if not top_text or not bottom_text:
|
| 80 |
-
# Fallback to simple split
|
| 81 |
words = idea.split()
|
| 82 |
-
mid = len(words) // 2
|
| 83 |
top_text = ' '.join(words[:mid])
|
| 84 |
bottom_text = ' '.join(words[mid:])
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
return top_text, bottom_text, None
|
| 87 |
|
| 88 |
except Exception as e:
|
| 89 |
error_msg = str(e)
|
| 90 |
-
|
| 91 |
-
if "404" in error_msg:
|
| 92 |
-
return None, None, f"❌ Model not available. Try a different model.\n\nError: {error_msg}"
|
| 93 |
-
elif "503" in error_msg:
|
| 94 |
-
return None, None, "❌ Model is loading. Wait 30 seconds and try again."
|
| 95 |
-
elif "429" in error_msg:
|
| 96 |
-
return None, None, "❌ Rate limit. Wait 60 seconds."
|
| 97 |
-
else:
|
| 98 |
-
return None, None, f"❌ Error: {error_msg[:200]}"
|
| 99 |
|
| 100 |
def create_meme(idea: str, template: str, model: str):
|
| 101 |
"""Generate complete meme"""
|
| 102 |
if not idea or len(idea.strip()) < 3:
|
| 103 |
-
return None, "❌ Enter a meme idea
|
| 104 |
-
|
| 105 |
-
status_msg = f"🔄 Generating meme text with AI...\n\nIdea: {idea}\nTemplate: {template}\nModel: {model}"
|
| 106 |
|
| 107 |
# Get AI-generated text
|
| 108 |
top, bottom, error = generate_meme_text(idea, model)
|
|
@@ -137,203 +119,96 @@ def create_meme(idea: str, template: str, model: str):
|
|
| 137 |
with open(temp_path, 'wb') as f:
|
| 138 |
f.write(img_response.content)
|
| 139 |
|
| 140 |
-
return temp_path, f"""✅
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
💡 Right-click image to save or share!"""
|
| 151 |
else:
|
| 152 |
-
return None, f"✅ Meme created!\n\
|
| 153 |
else:
|
| 154 |
-
|
| 155 |
-
return None, f"❌ ImgFlip API Error: {error_msg}\n\nTry a different template or try again."
|
| 156 |
|
| 157 |
-
except requests.exceptions.Timeout:
|
| 158 |
-
return None, "❌ Request timeout. Try again."
|
| 159 |
except Exception as e:
|
| 160 |
-
return None, f"❌ Error
|
| 161 |
|
| 162 |
-
#
|
| 163 |
MODELS = {
|
| 164 |
-
"Llama 3.
|
| 165 |
-
|
| 166 |
-
"Mistral 7B": "mistralai/Mistral-7B-Instruct-v0.2",
|
| 167 |
-
"Phi 3 Mini": "microsoft/Phi-3-mini-4k-instruct",
|
| 168 |
-
"Gemma 2B": "google/gemma-2b-it",
|
| 169 |
}
|
| 170 |
|
| 171 |
# Examples
|
| 172 |
examples = [
|
| 173 |
-
["When you finally fix the bug at 3 AM", "Success Kid", "Llama 3.
|
| 174 |
-
["Junior dev vs Senior dev
|
| 175 |
-
["My code in
|
| 176 |
-
["Trying to explain code to non-developers", "Ancient Aliens", "Llama 3.2 3B (Recommended)"],
|
| 177 |
-
["Me before coffee vs after coffee", "Two Buttons", "Llama 3.2 3B (Recommended)"],
|
| 178 |
-
["When the code works on first try", "Disaster Girl", "Mistral 7B"],
|
| 179 |
]
|
| 180 |
|
| 181 |
-
# Custom CSS
|
| 182 |
-
custom_css = """
|
| 183 |
-
.gradio-container {max-width: 1200px !important;}
|
| 184 |
-
.header-gradient {
|
| 185 |
-
text-align: center;
|
| 186 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 187 |
-
padding: 30px;
|
| 188 |
-
border-radius: 15px;
|
| 189 |
-
color: white;
|
| 190 |
-
margin-bottom: 20px;
|
| 191 |
-
}
|
| 192 |
-
"""
|
| 193 |
-
|
| 194 |
# UI
|
| 195 |
-
with gr.Blocks(
|
| 196 |
|
| 197 |
gr.HTML("""
|
| 198 |
-
<div
|
|
|
|
| 199 |
<h1>🥸 AI Meme Generator</h1>
|
| 200 |
-
<h3>
|
| 201 |
-
<p>AI creates funny meme text, then generates your meme instantly!</p>
|
| 202 |
</div>
|
| 203 |
""")
|
| 204 |
|
| 205 |
-
gr.Markdown(""
|
| 206 |
-
⚠️ **First Time Setup:** Add `HF_TOKEN` to Space Settings → Repository Secrets
|
| 207 |
-
([Get Free Token](https://huggingface.co/settings/tokens))
|
| 208 |
-
""")
|
| 209 |
|
| 210 |
with gr.Row():
|
| 211 |
with gr.Column(scale=2):
|
| 212 |
idea = gr.Textbox(
|
| 213 |
-
label="🎨
|
| 214 |
-
placeholder="
|
| 215 |
-
lines=2
|
| 216 |
-
info="Describe your meme idea - AI will create funny text for it"
|
| 217 |
)
|
| 218 |
|
| 219 |
with gr.Row():
|
| 220 |
template = gr.Dropdown(
|
| 221 |
choices=list(MEME_TEMPLATES.keys()),
|
| 222 |
value="Drake",
|
| 223 |
-
label="🖼️
|
| 224 |
-
info="Choose which meme format to use"
|
| 225 |
)
|
| 226 |
|
| 227 |
model = gr.Dropdown(
|
| 228 |
choices=list(MODELS.keys()),
|
| 229 |
-
value="Llama 3.
|
| 230 |
-
label="🤖
|
| 231 |
-
info="Llama 3.2 3B is fastest and most reliable"
|
| 232 |
)
|
| 233 |
|
| 234 |
-
|
| 235 |
-
btn = gr.Button("🚀 Generate Meme", variant="primary", size="lg")
|
| 236 |
-
clear_btn = gr.ClearButton(components=[idea], value="🗑️ Clear")
|
| 237 |
|
| 238 |
with gr.Column(scale=1):
|
| 239 |
gr.Markdown("""
|
| 240 |
-
###
|
| 241 |
-
|
| 242 |
-
**1. Get HuggingFace Token:**
|
| 243 |
-
- Visit [HF Tokens](https://huggingface.co/settings/tokens)
|
| 244 |
-
- Click "New token"
|
| 245 |
-
- Select "Read" permission
|
| 246 |
-
- Copy token (starts with `hf_`)
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
- Name: `HF_TOKEN`
|
| 253 |
-
- Value: (paste token)
|
| 254 |
-
- Save and restart Space
|
| 255 |
|
| 256 |
-
|
| 257 |
-
- Enter your idea
|
| 258 |
-
- Pick a template
|
| 259 |
-
- Click "Generate Meme"
|
| 260 |
-
- Download and share!
|
| 261 |
|
| 262 |
-
|
| 263 |
-
- ✅ Be specific and descriptive
|
| 264 |
-
- ✅ Include context/scenario
|
| 265 |
-
- ✅ Use "Llama 3.2 3B" for best results
|
| 266 |
-
- ✅ Generation takes 2-5 seconds
|
| 267 |
""")
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
label="🖼️ Your Generated Meme",
|
| 272 |
-
type="filepath",
|
| 273 |
-
height=400,
|
| 274 |
-
show_download_button=True
|
| 275 |
-
)
|
| 276 |
-
|
| 277 |
-
output_status = gr.Textbox(
|
| 278 |
-
label="📊 Status & Details",
|
| 279 |
-
lines=8,
|
| 280 |
-
show_copy_button=True
|
| 281 |
-
)
|
| 282 |
-
|
| 283 |
-
gr.Markdown("### 💡 Example Ideas (Click to Try!)")
|
| 284 |
-
|
| 285 |
-
gr.Examples(
|
| 286 |
-
examples=examples,
|
| 287 |
-
inputs=[idea, template, model],
|
| 288 |
-
label="Click any example to auto-fill and try it out"
|
| 289 |
-
)
|
| 290 |
-
|
| 291 |
-
gr.Markdown("""
|
| 292 |
-
---
|
| 293 |
-
|
| 294 |
-
### 🔧 Troubleshooting
|
| 295 |
-
|
| 296 |
-
| Problem | Solution |
|
| 297 |
-
|---------|----------|
|
| 298 |
-
| ❌ Token not found | Add `HF_TOKEN` in Space Settings → Repository Secrets |
|
| 299 |
-
| ❌ 404 Model error | Model may not be available - try "Llama 3.2 3B" |
|
| 300 |
-
| ❌ 503 Model loading | Wait 30 seconds for model to wake up |
|
| 301 |
-
| ❌ 429 Rate limit | Wait 60 seconds (free tier limits) |
|
| 302 |
-
| ❌ ImgFlip error | Try different template or retry |
|
| 303 |
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
1. **You describe** your meme idea
|
| 307 |
-
2. **AI generates** funny top and bottom text
|
| 308 |
-
3. **ImgFlip creates** the meme with your chosen template
|
| 309 |
-
4. **Download** and share instantly!
|
| 310 |
-
|
| 311 |
-
### ⚡ Features
|
| 312 |
-
|
| 313 |
-
- ✅ **Fast:** 2-5 second generation
|
| 314 |
-
- ✅ **Smart:** AI creates contextual humor
|
| 315 |
-
- ✅ **Easy:** Just describe and click
|
| 316 |
-
- ✅ **Free:** 100% free to use
|
| 317 |
-
- ✅ **No waiting:** Instant results
|
| 318 |
-
|
| 319 |
-
---
|
| 320 |
-
|
| 321 |
-
<div style='text-align: center; padding: 25px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 322 |
-
border-radius: 10px; color: white;'>
|
| 323 |
-
<p style='font-size: 1.2em; margin: 0;'><strong>🤗 100% Free & Open Source</strong></p>
|
| 324 |
-
<p style='margin: 10px 0;'>Built with: HuggingFace Inference API • ImgFlip API • Gradio</p>
|
| 325 |
-
<p style='margin: 10px 0;'>⭐ Star this Space if you find it useful!</p>
|
| 326 |
-
<p style='margin: 0; font-size: 0.9em;'><em>Free tier has rate limits - be patient between generations</em></p>
|
| 327 |
-
</div>
|
| 328 |
-
""")
|
| 329 |
|
| 330 |
-
# Event handler
|
| 331 |
btn.click(
|
| 332 |
fn=lambda i, t, m: create_meme(i, t, MODELS[m]),
|
| 333 |
inputs=[idea, template, model],
|
| 334 |
outputs=[output_img, output_status]
|
| 335 |
)
|
| 336 |
|
| 337 |
-
# Launch
|
| 338 |
if __name__ == "__main__":
|
| 339 |
-
demo.launch(
|
|
|
|
| 25 |
"One Does Not Simply": "61579",
|
| 26 |
"Batman Slapping Robin": "438680",
|
| 27 |
"Ancient Aliens": "101470",
|
|
|
|
| 28 |
}
|
| 29 |
|
| 30 |
def generate_meme_text(idea: str, model: str):
|
|
|
|
| 34 |
return None, None, error
|
| 35 |
|
| 36 |
try:
|
| 37 |
+
prompt = f"""Create funny meme text for: "{idea}"
|
| 38 |
|
| 39 |
+
Reply ONLY in this format:
|
| 40 |
+
TOP: [setup text - max 10 words]
|
| 41 |
+
BOTTOM: [punchline text - max 10 words]
|
| 42 |
|
| 43 |
+
Now generate:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
TOP:"""
|
| 45 |
|
|
|
|
| 46 |
response = client.text_generation(
|
| 47 |
prompt,
|
| 48 |
model=model,
|
| 49 |
+
max_new_tokens=100,
|
| 50 |
temperature=0.7,
|
|
|
|
| 51 |
return_full_text=False
|
| 52 |
)
|
| 53 |
|
| 54 |
# Parse response
|
| 55 |
+
full_text = "TOP:" + response
|
|
|
|
| 56 |
|
| 57 |
top_text = ""
|
| 58 |
bottom_text = ""
|
| 59 |
|
| 60 |
+
for line in full_text.split('\n'):
|
| 61 |
line = line.strip()
|
| 62 |
if line.startswith("TOP:"):
|
| 63 |
+
top_text = line.replace("TOP:", "").strip().strip('[]"\'.,')
|
| 64 |
elif line.startswith("BOTTOM:"):
|
| 65 |
+
bottom_text = line.replace("BOTTOM:", "").strip().strip('[]"\'.,')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
# Fallback if parsing fails
|
| 68 |
if not top_text or not bottom_text:
|
|
|
|
| 69 |
words = idea.split()
|
| 70 |
+
mid = max(1, len(words) // 2)
|
| 71 |
top_text = ' '.join(words[:mid])
|
| 72 |
bottom_text = ' '.join(words[mid:])
|
| 73 |
|
| 74 |
+
# Limit length
|
| 75 |
+
top_text = ' '.join(top_text.split()[:10])
|
| 76 |
+
bottom_text = ' '.join(bottom_text.split()[:10])
|
| 77 |
+
|
| 78 |
return top_text, bottom_text, None
|
| 79 |
|
| 80 |
except Exception as e:
|
| 81 |
error_msg = str(e)
|
| 82 |
+
return None, None, f"❌ AI Error: {error_msg[:150]}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
def create_meme(idea: str, template: str, model: str):
|
| 85 |
"""Generate complete meme"""
|
| 86 |
if not idea or len(idea.strip()) < 3:
|
| 87 |
+
return None, "❌ Enter a meme idea!"
|
|
|
|
|
|
|
| 88 |
|
| 89 |
# Get AI-generated text
|
| 90 |
top, bottom, error = generate_meme_text(idea, model)
|
|
|
|
| 119 |
with open(temp_path, 'wb') as f:
|
| 120 |
f.write(img_response.content)
|
| 121 |
|
| 122 |
+
return temp_path, f"""✅ Success!
|
| 123 |
|
| 124 |
+
Top: {top}
|
| 125 |
+
Bottom: {bottom}
|
| 126 |
|
| 127 |
+
Model: {model}
|
| 128 |
+
Template: {template}
|
| 129 |
|
| 130 |
+
URL: {meme_url}"""
|
|
|
|
|
|
|
| 131 |
else:
|
| 132 |
+
return None, f"✅ Meme created!\n\nURL: {meme_url}\n\nTop: {top}\nBottom: {bottom}"
|
| 133 |
else:
|
| 134 |
+
return None, f"❌ ImgFlip Error: {data.get('error_message', 'Unknown')}"
|
|
|
|
| 135 |
|
|
|
|
|
|
|
| 136 |
except Exception as e:
|
| 137 |
+
return None, f"❌ Error: {str(e)[:150]}"
|
| 138 |
|
| 139 |
+
# WORKING MODELS (verified)
|
| 140 |
MODELS = {
|
| 141 |
+
"Llama 3.1 8B (Recommended)": "meta-llama/Llama-3.1-8B-Instruct",
|
| 142 |
+
# Add more models here that you verify work
|
|
|
|
|
|
|
|
|
|
| 143 |
}
|
| 144 |
|
| 145 |
# Examples
|
| 146 |
examples = [
|
| 147 |
+
["When you finally fix the bug at 3 AM", "Success Kid", "Llama 3.1 8B (Recommended)"],
|
| 148 |
+
["Junior dev vs Senior dev", "Drake", "Llama 3.1 8B (Recommended)"],
|
| 149 |
+
["My code in dev vs production", "Distracted Boyfriend", "Llama 3.1 8B (Recommended)"],
|
|
|
|
|
|
|
|
|
|
| 150 |
]
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
# UI
|
| 153 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="AI Meme Generator") as demo:
|
| 154 |
|
| 155 |
gr.HTML("""
|
| 156 |
+
<div style='text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 157 |
+
padding: 30px; border-radius: 15px; color: white; margin-bottom: 20px;'>
|
| 158 |
<h1>🥸 AI Meme Generator</h1>
|
| 159 |
+
<h3>HuggingFace AI + ImgFlip API</h3>
|
|
|
|
| 160 |
</div>
|
| 161 |
""")
|
| 162 |
|
| 163 |
+
gr.Markdown("⚠️ **Setup:** Add `HF_TOKEN` to Settings → Repository Secrets ([Get Token](https://huggingface.co/settings/tokens))")
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
with gr.Row():
|
| 166 |
with gr.Column(scale=2):
|
| 167 |
idea = gr.Textbox(
|
| 168 |
+
label="🎨 Meme Idea",
|
| 169 |
+
placeholder="When you find a bug in production...",
|
| 170 |
+
lines=2
|
|
|
|
| 171 |
)
|
| 172 |
|
| 173 |
with gr.Row():
|
| 174 |
template = gr.Dropdown(
|
| 175 |
choices=list(MEME_TEMPLATES.keys()),
|
| 176 |
value="Drake",
|
| 177 |
+
label="🖼️ Template"
|
|
|
|
| 178 |
)
|
| 179 |
|
| 180 |
model = gr.Dropdown(
|
| 181 |
choices=list(MODELS.keys()),
|
| 182 |
+
value="Llama 3.1 8B (Recommended)",
|
| 183 |
+
label="🤖 Model"
|
|
|
|
| 184 |
)
|
| 185 |
|
| 186 |
+
btn = gr.Button("🚀 Generate", variant="primary", size="lg")
|
|
|
|
|
|
|
| 187 |
|
| 188 |
with gr.Column(scale=1):
|
| 189 |
gr.Markdown("""
|
| 190 |
+
### Setup
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
+
1. Get token: [HF Tokens](https://huggingface.co/settings/tokens)
|
| 193 |
+
2. Settings → Secrets
|
| 194 |
+
3. Add `HF_TOKEN`
|
| 195 |
+
4. Restart Space
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
### Share Working Models
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
+
If you find models that work, please share them so I can add them to the list!
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
""")
|
| 201 |
|
| 202 |
+
output_img = gr.Image(label="Meme", type="filepath")
|
| 203 |
+
output_status = gr.Textbox(label="Status", lines=6)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
+
gr.Examples(examples=examples, inputs=[idea, template, model])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
|
|
|
| 207 |
btn.click(
|
| 208 |
fn=lambda i, t, m: create_meme(i, t, MODELS[m]),
|
| 209 |
inputs=[idea, template, model],
|
| 210 |
outputs=[output_img, output_status]
|
| 211 |
)
|
| 212 |
|
|
|
|
| 213 |
if __name__ == "__main__":
|
| 214 |
+
demo.launch()
|