bravo24's picture
Update app.py
c455538 verified
"""
FomoFeed - Smart Notification Generator v2
Template-based with intelligent selection (NO GPT-2)
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import random
from datetime import datetime
import uvicorn
app = FastAPI(title="FomoFeed Smart Notification Generator", version="2.0.0")
class UserProfile(BaseModel):
user_id: int
username: str
is_creator: bool = False
top_tags: list[str] = []
last_post_days_ago: int = 0
avg_engagement: float = 0.0
follower_count: int = 0
optimal_hour: int = 19
class NotificationRequest(BaseModel):
profile: UserProfile
notification_type: str
language: str = "tr"
class NotificationResponse(BaseModel):
title: str
body: str
emoji: str
confidence: float
# ════════════════════════════════════════
# AKILLI TEMPLATE SİSTEMİ
# ════════════════════════════════════════
# Kişiselleştirme değişkenleri:
# {username} → kullanıcı adı
# {days} → kaç gündür inaktif
# {followers} → takipçi sayısı
# {tag} → en popüler tag
# {hour} → optimal saat
TEMPLATES = {
"tr": {
"low_activity": {
"casual": [ # 1-7 gün inaktif
{"title": "👋 Naber {username}?", "body": "Takip ettiklerin yeni şeyler paylaştı. Bir göz at!"},
{"title": "📱 Feedin dolmuş!", "body": "Son {days} günde birçok yeni paylaşım yapıldı."},
{"title": "✨ Bir şeyler kaçırıyorsun", "body": "Takip ettiklerinden yeni içerikler var."},
],
"warm": [ # 7-30 gün inaktif
{"title": "🥺 Seni özledik {username}", "body": "Yokluğunda {days} günlük içerik birikti."},
{"title": "👀 Neler kaçırdın!", "body": "Son zamanlarda harika paylaşımlar yapıldı. Görmek ister misin?"},
{"title": "💭 Seni düşündük", "body": "Bir süredir görünmüyorsun. Her şey yolunda mı?"},
],
"cold": [ # 30+ gün inaktif
{"title": "🌟 Geri dönsen harika olur", "body": "Topluluk büyümeye devam ediyor. Sen de katıl!"},
{"title": "💚 Hâlâ buradasın değil mi?", "body": "Seni bekleyen içerikler var. Bir baksan mı?"},
{"title": "🔄 Çok şey değişti!", "body": "{days} gündür gelmedin. Yeni özellikler ve içerikler seni bekliyor."},
],
"creator_specific": [ # İçerik üretici
{"title": "🎨 Takipçilerin seni bekliyor", "body": "{followers} takipçin yeni içerik bekliyor!"},
{"title": "📸 İlham geldi mi?", "body": "Son paylaşımından {days} gün oldu. Takipçilerin merak ediyor!"},
{"title": "🔥 Senin tarzın özlendi", "body": "Platformda eksikliğin hissediliyor. Geri dön!"},
]
},
"optimal_time": {
"feed_ready": [
{"title": "⏰ Tam zamanı!", "body": "Şu an platformdan en çok keyif alacağın an."},
{"title": "🔥 Feedin hazır", "body": "Senin için seçilmiş içerikler bekliyor."},
{"title": "✨ İyi vakit geçirmeye hazır mısın?", "body": "Feedinde ilgini çekecek paylaşımlar var."},
],
"creator_post_time": [
{"title": "📊 Paylaşım zamanı!", "body": "Takipçilerin şu an en aktif. İçerik paylaşmak için ideal!"},
{"title": "🎯 Prime time!", "body": "Saat {hour}:00 — takipçilerin online. Paylaşım yap!"},
]
},
"trending_tag": {
"default": [
{"title": "🔥 #{tag} trend!", "body": "Bu konuda paylaşım yapma fırsatını kaçırma."},
{"title": "⚡ #{tag} patladı!", "body": "Herkes bu konu hakkında konuşuyor. Sen de katıl!"},
{"title": "📈 #{tag} yükselişte", "body": "Bu trend'e katılmak için harika bir zaman."},
]
},
"milestone": {
"default": [
{"title": "🎉 Tebrikler {username}!", "body": "{followers} takipçiye ulaştın!"},
{"title": "⭐ Harika gidiyorsun!", "body": "Topluluk seni seviyor. Devam et!"},
]
}
},
"en": {
"low_activity": {
"casual": [
{"title": "👋 Hey {username}!", "body": "People you follow shared new stuff. Take a look!"},
{"title": "📱 Your feed is full!", "body": "Lots of new posts in the last {days} days."},
{"title": "✨ You're missing out", "body": "New content from people you follow."},
],
"warm": [
{"title": "🥺 We miss you {username}", "body": "{days} days of content piled up while you were away."},
{"title": "👀 See what you missed!", "body": "Amazing posts were shared recently. Want to see?"},
{"title": "💭 Thinking of you", "body": "Haven't seen you in a while. Everything okay?"},
],
"cold": [
{"title": "🌟 We'd love to see you back", "body": "The community keeps growing. Join in!"},
{"title": "💚 Still there?", "body": "Content is waiting for you. Want to take a peek?"},
{"title": "🔄 A lot has changed!", "body": "It's been {days} days. New features and content await you."},
],
"creator_specific": [
{"title": "🎨 Your followers are waiting", "body": "{followers} followers want new content from you!"},
{"title": "📸 Feeling inspired?", "body": "It's been {days} days since your last post. Followers are curious!"},
{"title": "🔥 Your style is missed", "body": "The platform feels your absence. Come back!"},
]
},
"optimal_time": {
"feed_ready": [
{"title": "⏰ Perfect timing!", "body": "This is the best moment to enjoy the platform."},
{"title": "🔥 Your feed is ready", "body": "Curated content is waiting for you."},
{"title": "✨ Ready for a good time?", "body": "Your feed has posts you'll love."},
],
"creator_post_time": [
{"title": "📊 Time to post!", "body": "Your followers are most active right now. Ideal time to share!"},
{"title": "🎯 Prime time!", "body": "It's {hour}:00 — your followers are online. Post now!"},
]
},
"trending_tag": {
"default": [
{"title": "🔥 #{tag} is trending!", "body": "Don't miss the chance to post about this."},
{"title": "⚡ #{tag} is blowing up!", "body": "Everyone's talking about it. Join in!"},
{"title": "📈 #{tag} is rising", "body": "Great time to hop on this trend."},
]
},
"milestone": {
"default": [
{"title": "🎉 Congrats {username}!", "body": "You reached {followers} followers!"},
{"title": "⭐ You're doing great!", "body": "The community loves you. Keep going!"},
]
}
},
"de": {
"low_activity": {
"casual": [
{"title": "👋 Hey {username}!", "body": "Leute denen du folgst haben Neues geteilt!"},
],
"warm": [
{"title": "🥺 Wir vermissen dich", "body": "{days} Tage an Inhalten haben sich angesammelt."},
],
"cold": [
{"title": "🌟 Komm zurück!", "body": "Die Community wächst weiter. Mach mit!"},
],
"creator_specific": [
{"title": "🎨 Deine Follower warten", "body": "{followers} Follower wollen neuen Content!"},
]
},
"optimal_time": {
"feed_ready": [
{"title": "⏰ Perfektes Timing!", "body": "Jetzt ist der beste Moment zum Genießen."},
],
"creator_post_time": [
{"title": "📊 Zeit zu posten!", "body": "Deine Follower sind jetzt am aktivsten."},
]
},
"trending_tag": {
"default": [
{"title": "🔥 #{tag} ist im Trend!", "body": "Verpasse nicht die Chance darüber zu posten."},
]
},
"milestone": {
"default": [
{"title": "🎉 Glückwunsch {username}!", "body": "Du hast {followers} Follower erreicht!"},
]
}
},
"fr": {
"low_activity": {
"casual": [
{"title": "👋 Salut {username}!", "body": "Tes abonnés ont partagé du nouveau!"},
],
"warm": [
{"title": "🥺 Tu nous manques", "body": "{days} jours de contenu t'attendent."},
],
"cold": [
{"title": "🌟 Reviens!", "body": "La communauté grandit. Rejoins-nous!"},
],
"creator_specific": [
{"title": "🎨 Tes abonnés t'attendent", "body": "{followers} abonnés veulent du nouveau contenu!"},
]
},
"optimal_time": {
"feed_ready": [
{"title": "⏰ C'est le moment!", "body": "Le meilleur moment pour profiter de la plateforme."},
],
"creator_post_time": [
{"title": "📊 C'est l'heure de poster!", "body": "Tes abonnés sont les plus actifs maintenant."},
]
},
"trending_tag": {
"default": [
{"title": "🔥 #{tag} est en tendance!", "body": "Ne rate pas l'occasion d'en parler."},
]
},
"milestone": {
"default": [
{"title": "🎉 Félicitations {username}!", "body": "Tu as atteint {followers} abonnés!"},
]
}
},
"ar": {
"low_activity": {
"casual": [
{"title": "👋 أهلاً {username}!", "body": "اللي تتابعهم نشروا أشياء جديدة!"},
],
"warm": [
{"title": "🥺 اشتقنا لك", "body": "محتوى {days} يوم مستنيك."},
],
"cold": [
{"title": "🌟 ارجع لنا!", "body": "المجتمع يكبر. انضم لنا!"},
],
"creator_specific": [
{"title": "🎨 متابعينك مستنينك", "body": "{followers} متابع يبون محتوى جديد!"},
]
},
"optimal_time": {
"feed_ready": [
{"title": "⏰ الوقت المثالي!", "body": "أفضل وقت للاستمتاع بالمنصة."},
],
"creator_post_time": [
{"title": "📊 وقت النشر!", "body": "متابعينك أكثر نشاطاً الحين."},
]
},
"trending_tag": {
"default": [
{"title": "🔥 #{tag} ترند!", "body": "لا تفوت فرصة النشر عن هالموضوع."},
]
},
"milestone": {
"default": [
{"title": "🎉 مبروك {username}!", "body": "وصلت {followers} متابع!"},
]
}
}
}
def select_template(request: NotificationRequest) -> dict:
"""
Akıllı template seçimi:
- İnaktiflik süresine göre ton ayarla (casual/warm/cold)
- Creator mı değil mi?
- Kişiselleştirme değişkenlerini doldur
"""
profile = request.profile
ntype = request.notification_type
lang = request.language
# Dil fallback
if lang not in TEMPLATES:
lang = "en"
lang_templates = TEMPLATES[lang]
# Bildirim tipine göre template grubunu seç
if ntype not in lang_templates:
ntype = "optimal_time"
type_templates = lang_templates[ntype]
# Alt kategori seç
if ntype == "low_activity":
days = profile.last_post_days_ago
if profile.is_creator and "creator_specific" in type_templates:
# Creator'lara özel mesaj (%40 ihtimal)
if random.random() < 0.4:
pool = type_templates["creator_specific"]
elif days <= 7:
pool = type_templates.get("casual", type_templates.get("warm", []))
elif days <= 30:
pool = type_templates.get("warm", type_templates.get("cold", []))
else:
pool = type_templates.get("cold", type_templates.get("warm", []))
else:
if days <= 7:
pool = type_templates.get("casual", [])
elif days <= 30:
pool = type_templates.get("warm", [])
else:
pool = type_templates.get("cold", [])
elif ntype == "optimal_time":
if profile.is_creator and "creator_post_time" in type_templates:
pool = type_templates["creator_post_time"] if random.random() < 0.5 else type_templates.get("feed_ready", [])
else:
pool = type_templates.get("feed_ready", [])
else:
pool = type_templates.get("default", [])
# Boş pool kontrolü
if not pool:
pool = [{"title": "👋 Hey!", "body": "Check out what's new."}]
# Rastgele template seç
template = random.choice(pool)
# Değişkenleri doldur
tag = profile.top_tags[0] if profile.top_tags else "trending"
title = template["title"].format(
username=profile.username,
days=profile.last_post_days_ago,
followers=profile.follower_count,
tag=tag,
hour=profile.optimal_hour
)
body = template["body"].format(
username=profile.username,
days=profile.last_post_days_ago,
followers=profile.follower_count,
tag=tag,
hour=profile.optimal_hour
)
# Emoji
emoji_map = {
"optimal_time": "⏰",
"low_activity": "👋",
"trending_tag": "🔥",
"milestone": "🎉"
}
return {
"title": title,
"body": body,
"emoji": emoji_map.get(ntype, "📱"),
"confidence": 0.85
}
@app.get("/")
def root():
return {
"service": "FomoFeed Smart Notification Generator",
"status": "active",
"version": "2.0.0",
"method": "intelligent_template_selection"
}
@app.get("/health")
def health():
return {
"status": "healthy",
"model_loaded": True,
"timestamp": datetime.now().isoformat()
}
@app.post("/generate", response_model=NotificationResponse)
def generate_notification(request: NotificationRequest):
try:
result = select_template(request)
return NotificationResponse(**result)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/batch_generate")
def batch_generate(requests: list[NotificationRequest]):
try:
results = []
for req in requests:
result = select_template(req)
results.append({"user_id": req.profile.user_id, **result})
return {"notifications": results}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)