mike23415 commited on
Commit
2309cd2
·
verified ·
1 Parent(s): 03683e8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +452 -0
app.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, send_file
2
+ from flask_cors import CORS
3
+ import os
4
+ import io
5
+ import base64
6
+ import requests
7
+ import random
8
+ from PIL import Image, ImageDraw, ImageFont
9
+ import numpy as np
10
+ from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration
11
+ import torch
12
+ from datetime import datetime, timedelta
13
+ import json
14
+ import re
15
+ from collections import Counter
16
+ import threading
17
+ import time
18
+
19
+ app = Flask(__name__)
20
+ CORS(app)
21
+
22
+ # Initialize AI models
23
+ print("Loading AI models...")
24
+ try:
25
+ # Image captioning for smart suggestions
26
+ caption_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
27
+ caption_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
28
+
29
+ # Text generation for meme text
30
+ text_generator = pipeline("text-generation",
31
+ model="microsoft/DialoGPT-medium",
32
+ tokenizer="microsoft/DialoGPT-medium")
33
+
34
+ # Sentiment analysis for mood-based memes
35
+ sentiment_analyzer = pipeline("sentiment-analysis",
36
+ model="cardiffnlp/twitter-roberta-base-sentiment-latest")
37
+
38
+ print("Models loaded successfully!")
39
+ except Exception as e:
40
+ print(f"Error loading models: {e}")
41
+ # Fallback to mock responses if models fail to load
42
+
43
+ # Meme templates and trending data
44
+ MEME_TEMPLATES = {
45
+ "drake": {"top": "Drake pointing away", "bottom": "Drake pointing towards"},
46
+ "distracted_boyfriend": {"top": "Looking at something new", "bottom": "Ignoring what you had"},
47
+ "woman_yelling_cat": {"top": "When someone disagrees", "bottom": "You trying to stay calm"},
48
+ "this_is_fine": {"top": "Everything is falling apart", "bottom": "This is fine"},
49
+ "expanding_brain": {"top": "Basic idea", "bottom": "Galaxy brain idea"},
50
+ "change_my_mind": {"top": "Controversial opinion", "bottom": "Change my mind"},
51
+ "two_buttons": {"top": "Difficult choice A", "bottom": "Difficult choice B"},
52
+ "disaster_girl": {"top": "When you cause chaos", "bottom": "And act innocent"}
53
+ }
54
+
55
+ HUMOR_STYLES = {
56
+ "sarcastic": ["Oh great, another", "Because that always works", "Sure, that makes perfect sense"],
57
+ "wholesome": ["You're doing great!", "Believe in yourself", "Every day is a gift"],
58
+ "dark": ["When life gives you lemons", "Nothing matters anyway", "We're all doomed but"],
59
+ "relatable": ["When you realize", "Me trying to", "That moment when"],
60
+ "gen_z": ["No cap", "It's giving", "That's lowkey", "Main character energy"]
61
+ }
62
+
63
+ # Mock trending data (in production, this would come from social media APIs)
64
+ trending_topics = ["AI taking over", "Work from home", "Monday motivation", "Weekend vibes",
65
+ "Cryptocurrency", "Climate change", "Social media addiction", "Netflix binge"]
66
+
67
+ class MemeAI:
68
+ def __init__(self):
69
+ self.meme_history = []
70
+ self.user_preferences = {}
71
+
72
+ def analyze_image(self, image):
73
+ """Analyze image and generate smart suggestions"""
74
+ try:
75
+ # Generate caption
76
+ inputs = caption_processor(image, return_tensors="pt")
77
+ out = caption_model.generate(**inputs, max_length=50)
78
+ caption = caption_processor.decode(out[0], skip_special_tokens=True)
79
+
80
+ # Extract key objects/concepts
81
+ keywords = self.extract_keywords(caption)
82
+
83
+ return {
84
+ "caption": caption,
85
+ "keywords": keywords,
86
+ "suggestions": self.generate_text_suggestions(keywords)
87
+ }
88
+ except Exception as e:
89
+ print(f"Image analysis error: {e}")
90
+ return {
91
+ "caption": "Image uploaded",
92
+ "keywords": ["general"],
93
+ "suggestions": self.get_generic_suggestions()
94
+ }
95
+
96
+ def extract_keywords(self, text):
97
+ """Extract meaningful keywords from image caption"""
98
+ # Simple keyword extraction (in production, use more sophisticated NLP)
99
+ words = re.findall(r'\b\w+\b', text.lower())
100
+ # Filter out common words
101
+ stop_words = {'a', 'an', 'the', 'is', 'are', 'was', 'were', 'with', 'of', 'in', 'on', 'at'}
102
+ keywords = [word for word in words if word not in stop_words and len(word) > 2]
103
+ return keywords[:5] # Return top 5 keywords
104
+
105
+ def generate_text_suggestions(self, keywords, humor_style="relatable"):
106
+ """Generate contextual meme text suggestions"""
107
+ suggestions = []
108
+
109
+ # Keyword-based suggestions
110
+ for keyword in keywords:
111
+ if keyword in ["person", "people", "man", "woman"]:
112
+ suggestions.extend([
113
+ f"When you see someone {keyword}",
114
+ f"Me trying to be a normal {keyword}",
115
+ f"That {keyword} energy"
116
+ ])
117
+ elif keyword in ["dog", "cat", "animal"]:
118
+ suggestions.extend([
119
+ f"When your {keyword} judges you",
120
+ f"Me as a {keyword}",
121
+ f"{keyword.title()} > humans"
122
+ ])
123
+ elif keyword in ["car", "food", "house", "computer"]:
124
+ suggestions.extend([
125
+ f"When you can't afford a {keyword}",
126
+ f"My relationship with {keyword}",
127
+ f"{keyword.title()} problems require {keyword} solutions"
128
+ ])
129
+
130
+ # Add humor style variations
131
+ style_templates = HUMOR_STYLES.get(humor_style, HUMOR_STYLES["relatable"])
132
+ for template in style_templates[:3]:
133
+ suggestions.append(f"{template} {random.choice(keywords)}")
134
+
135
+ return list(set(suggestions))[:10] # Return unique suggestions, max 10
136
+
137
+ def get_generic_suggestions(self):
138
+ """Fallback suggestions when image analysis fails"""
139
+ return [
140
+ "When you realize it's Monday",
141
+ "Me trying to adult",
142
+ "This is fine",
143
+ "Why are you like this?",
144
+ "Big mood energy",
145
+ "That awkward moment when",
146
+ "Me vs my responsibilities",
147
+ "Plot twist: nobody asked"
148
+ ]
149
+
150
+ def analyze_mood(self, text):
151
+ """Analyze text mood for personalized suggestions"""
152
+ try:
153
+ result = sentiment_analyzer(text)[0]
154
+ mood = result['label'].lower()
155
+ confidence = result['score']
156
+
157
+ mood_suggestions = {
158
+ 'positive': ["You're killing it!", "Main character energy", "That's the spirit!"],
159
+ 'negative': ["This is fine", "Why are we here?", "Everything is chaos"],
160
+ 'neutral': ["It be like that sometimes", "Just vibing", "No thoughts, head empty"]
161
+ }
162
+
163
+ return mood_suggestions.get(mood, mood_suggestions['neutral'])
164
+ except:
165
+ return self.get_generic_suggestions()
166
+
167
+ def get_trending_suggestions(self):
168
+ """Generate suggestions based on trending topics"""
169
+ trending_memes = []
170
+ for topic in trending_topics[:5]:
171
+ trending_memes.extend([
172
+ f"When {topic} hits different",
173
+ f"Me explaining {topic} to my parents",
174
+ f"{topic} be like"
175
+ ])
176
+ return trending_memes
177
+
178
+ def predict_virality(self, text, image_features=None):
179
+ """Mock virality prediction (would use ML model in production)"""
180
+ score = 0
181
+
182
+ # Length check (shorter usually better)
183
+ if len(text) < 50:
184
+ score += 20
185
+
186
+ # Trending topic check
187
+ for topic in trending_topics:
188
+ if topic.lower() in text.lower():
189
+ score += 30
190
+
191
+ # Humor markers
192
+ humor_words = ['when', 'me', 'that', 'mood', 'vibes', 'energy', 'literally']
193
+ score += sum(5 for word in humor_words if word in text.lower())
194
+
195
+ # Randomize for demo
196
+ score += random.randint(0, 30)
197
+
198
+ return min(score, 100)
199
+
200
+ def learn_user_preferences(self, user_id, meme_data):
201
+ """Learn from user's meme creation patterns"""
202
+ if user_id not in self.user_preferences:
203
+ self.user_preferences[user_id] = {
204
+ 'humor_styles': [],
205
+ 'topics': [],
206
+ 'formats': []
207
+ }
208
+
209
+ # Update preferences (simplified)
210
+ self.user_preferences[user_id]['topics'].extend(meme_data.get('keywords', []))
211
+ if 'humor_style' in meme_data:
212
+ self.user_preferences[user_id]['humor_styles'].append(meme_data['humor_style'])
213
+
214
+ # Initialize AI engine
215
+ meme_ai = MemeAI()
216
+
217
+ @app.route('/health', methods=['GET'])
218
+ def health_check():
219
+ return jsonify({"status": "healthy", "timestamp": datetime.now().isoformat()})
220
+
221
+ @app.route('/analyze-image', methods=['POST'])
222
+ def analyze_image():
223
+ """Analyze uploaded image and provide smart suggestions"""
224
+ try:
225
+ data = request.get_json()
226
+
227
+ if 'image' not in data:
228
+ return jsonify({"error": "No image provided"}), 400
229
+
230
+ # Decode base64 image
231
+ image_data = base64.b64decode(data['image'].split(',')[1])
232
+ image = Image.open(io.BytesIO(image_data))
233
+
234
+ # Analyze image
235
+ analysis = meme_ai.analyze_image(image)
236
+
237
+ return jsonify({
238
+ "success": True,
239
+ "analysis": analysis,
240
+ "trending_suggestions": meme_ai.get_trending_suggestions()[:5]
241
+ })
242
+
243
+ except Exception as e:
244
+ return jsonify({"error": str(e)}), 500
245
+
246
+ @app.route('/generate-suggestions', methods=['POST'])
247
+ def generate_suggestions():
248
+ """Generate text suggestions based on various inputs"""
249
+ try:
250
+ data = request.get_json()
251
+
252
+ suggestions = []
253
+
254
+ # If keywords provided
255
+ if 'keywords' in data:
256
+ suggestions.extend(meme_ai.generate_text_suggestions(
257
+ data['keywords'],
258
+ data.get('humor_style', 'relatable')
259
+ ))
260
+
261
+ # If mood text provided
262
+ if 'mood_text' in data:
263
+ suggestions.extend(meme_ai.analyze_mood(data['mood_text']))
264
+
265
+ # Add trending suggestions
266
+ suggestions.extend(meme_ai.get_trending_suggestions()[:3])
267
+
268
+ # Remove duplicates and limit
269
+ unique_suggestions = list(set(suggestions))[:15]
270
+
271
+ return jsonify({
272
+ "success": True,
273
+ "suggestions": unique_suggestions,
274
+ "humor_styles": list(HUMOR_STYLES.keys())
275
+ })
276
+
277
+ except Exception as e:
278
+ return jsonify({"error": str(e)}), 500
279
+
280
+ @app.route('/predict-virality', methods=['POST'])
281
+ def predict_virality():
282
+ """Predict how viral a meme might be"""
283
+ try:
284
+ data = request.get_json()
285
+
286
+ if 'text' not in data:
287
+ return jsonify({"error": "No text provided"}), 400
288
+
289
+ score = meme_ai.predict_virality(data['text'])
290
+
291
+ # Generate advice
292
+ advice = []
293
+ if score < 30:
294
+ advice.append("Try adding trending topics or relatable situations")
295
+ if len(data['text']) > 100:
296
+ advice.append("Shorter text usually performs better")
297
+ if score > 70:
298
+ advice.append("This has great potential to go viral!")
299
+
300
+ return jsonify({
301
+ "success": True,
302
+ "virality_score": score,
303
+ "advice": advice,
304
+ "trending_topics": trending_topics[:5]
305
+ })
306
+
307
+ except Exception as e:
308
+ return jsonify({"error": str(e)}), 500
309
+
310
+ @app.route('/meme-battle', methods=['POST'])
311
+ def meme_battle():
312
+ """AI judges meme battle between submissions"""
313
+ try:
314
+ data = request.get_json()
315
+
316
+ if 'memes' not in data or len(data['memes']) < 2:
317
+ return jsonify({"error": "Need at least 2 memes for battle"}), 400
318
+
319
+ results = []
320
+ for i, meme in enumerate(data['memes']):
321
+ score = meme_ai.predict_virality(meme.get('text', ''))
322
+ results.append({
323
+ "id": i,
324
+ "text": meme.get('text', ''),
325
+ "score": score,
326
+ "feedback": f"Virality potential: {score}%"
327
+ })
328
+
329
+ # Sort by score
330
+ results.sort(key=lambda x: x['score'], reverse=True)
331
+
332
+ return jsonify({
333
+ "success": True,
334
+ "winner": results[0],
335
+ "rankings": results,
336
+ "battle_commentary": f"The winner with {results[0]['score']}% virality potential!"
337
+ })
338
+
339
+ except Exception as e:
340
+ return jsonify({"error": str(e)}), 500
341
+
342
+ @app.route('/trending-topics', methods=['GET'])
343
+ def get_trending_topics():
344
+ """Get current trending topics for memes"""
345
+ return jsonify({
346
+ "success": True,
347
+ "trending_topics": trending_topics,
348
+ "meme_templates": MEME_TEMPLATES,
349
+ "humor_styles": list(HUMOR_STYLES.keys())
350
+ })
351
+
352
+ @app.route('/personalized-suggestions', methods=['POST'])
353
+ def get_personalized_suggestions():
354
+ """Get personalized suggestions based on user history"""
355
+ try:
356
+ data = request.get_json()
357
+ user_id = data.get('user_id', 'anonymous')
358
+
359
+ # Get user preferences
360
+ preferences = meme_ai.user_preferences.get(user_id, {})
361
+
362
+ # Generate personalized suggestions
363
+ suggestions = []
364
+
365
+ # Based on user's favorite topics
366
+ if 'topics' in preferences:
367
+ top_topics = Counter(preferences['topics']).most_common(3)
368
+ for topic, _ in top_topics:
369
+ suggestions.extend(meme_ai.generate_text_suggestions([topic]))
370
+
371
+ # Based on humor style
372
+ if 'humor_styles' in preferences and preferences['humor_styles']:
373
+ favorite_style = Counter(preferences['humor_styles']).most_common(1)[0][0]
374
+ suggestions.extend(HUMOR_STYLES.get(favorite_style, []))
375
+
376
+ # Fallback to trending if no preferences
377
+ if not suggestions:
378
+ suggestions = meme_ai.get_trending_suggestions()
379
+
380
+ return jsonify({
381
+ "success": True,
382
+ "personalized_suggestions": list(set(suggestions))[:10],
383
+ "user_preferences": preferences
384
+ })
385
+
386
+ except Exception as e:
387
+ return jsonify({"error": str(e)}), 500
388
+
389
+ @app.route('/save-meme-data', methods=['POST'])
390
+ def save_meme_data():
391
+ """Save meme data for learning user preferences"""
392
+ try:
393
+ data = request.get_json()
394
+ user_id = data.get('user_id', 'anonymous')
395
+
396
+ # Learn from this meme
397
+ meme_ai.learn_user_preferences(user_id, data)
398
+
399
+ return jsonify({
400
+ "success": True,
401
+ "message": "Preferences updated"
402
+ })
403
+
404
+ except Exception as e:
405
+ return jsonify({"error": str(e)}), 500
406
+
407
+ @app.route('/create-template', methods=['POST'])
408
+ def create_template():
409
+ """AI creates new meme template suggestions"""
410
+ try:
411
+ data = request.get_json()
412
+
413
+ # Mock template creation (in production, use image generation models)
414
+ new_templates = [
415
+ {
416
+ "name": "AI Takeover",
417
+ "description": "When AI does something better than humans",
418
+ "suggested_text": {
419
+ "top": "Humans doing task manually",
420
+ "bottom": "AI doing it in 0.1 seconds"
421
+ }
422
+ },
423
+ {
424
+ "name": "Remote Work Reality",
425
+ "description": "Work from home expectations vs reality",
426
+ "suggested_text": {
427
+ "top": "What I thought WFH would be like",
428
+ "bottom": "What it actually is"
429
+ }
430
+ },
431
+ {
432
+ "name": "Gen Z vs Millennial",
433
+ "description": "Generational differences",
434
+ "suggested_text": {
435
+ "top": "Gen Z explaining new slang",
436
+ "bottom": "Millennials pretending to understand"
437
+ }
438
+ }
439
+ ]
440
+
441
+ return jsonify({
442
+ "success": True,
443
+ "new_templates": new_templates,
444
+ "trending_formats": ["Before/After", "Expectation/Reality", "Me vs Everyone else"]
445
+ })
446
+
447
+ except Exception as e:
448
+ return jsonify({"error": str(e)}), 500
449
+
450
+ if __name__ == '__main__':
451
+ port = int(os.environ.get('PORT', 7860))
452
+ app.run(host='0.0.0.0', port=port, debug=True)