"""
Ethereal Wisdom PRO β Monetized AI Wisdom Platform
Free: 3 wisdom generations/day, ads shown, basic features
Premium ($7.99/mo): Unlimited, no ads, collections, daily digest, shareable cards
"""
import gradio as gr
import os
import json
import hashlib
from datetime import datetime
import requests
import re
# ============ CONFIG ============
FREE_DAILY_LIMIT = 3
PREMIUM_PRICE = "$7.99/month"
STRIPE_LINK = os.environ.get("STRIPE_PAYMENT_LINK", "https://buy.stripe.com/YOUR_LINK")
ADSENSE_CLIENT = os.environ.get("ADSENSE_CLIENT", "ca-pub-YOUR_ID")
ADMIN_CODE = os.environ.get("ADMIN_CODE", "ethereal2024")
HF_TOKEN = os.environ.get("HF_TOKEN", "")
WISDOM_TOPICS = [
"Life", "Love", "Success", "Failure", "Courage", "Wisdom",
"Creativity", "Gratitude", "Mindfulness", "Leadership",
"Happiness", "Resilience", "Purpose", "Freedom", "Growth"
]
WISDOM_STYLES = [
"Stoic philosopher (Marcus Aurelius, Seneca)",
"Eastern mystic (Lao Tzu, Buddha)",
"Modern poet (Rumi, Kahlil Gibran)",
"Tech visionary (Steve Jobs, Naval Ravikant)",
"Ancient Greek (Socrates, Plato)",
"Motivational speaker (Tony Robbins, Brene Brown)",
"Zen master (Dogen, Thich Nhat Hanh)",
"Entrepreneur (Elon Musk, Jeff Bezos)"
]
# ============ USAGE TRACKING ============
USAGE_FILE = "/tmp/ethereal_usage.json"
def load_usage():
try:
with open(USAGE_FILE, 'r') as f:
return json.load(f)
except:
return {}
def save_usage(data):
with open(USAGE_FILE, 'w') as f:
json.dump(data, f)
def get_user_id(request: gr.Request):
try:
if request is not None:
client = getattr(request, 'client', None)
ip = getattr(client, 'host', '0.0.0.0') if client else '0.0.0.0'
headers = getattr(request, 'headers', {})
ua = headers.get("user-agent", "unknown") if headers else "unknown"
else:
ip = "0.0.0.0"
ua = "unknown"
return hashlib.md5(f"{ip}:{ua}".encode()).hexdigest()[:16]
except Exception:
return "anonymous"
def check_usage(user_id: str):
data = load_usage()
today = datetime.now().strftime("%Y-%m-%d")
if user_id not in data or data[user_id].get("date") != today:
prev_premium = data.get(user_id, {}).get("premium", False) if user_id in data else False
prev_fav = data.get(user_id, {}).get("favorites", []) if user_id in data else []
prev_hist = data.get(user_id, {}).get("history", []) if user_id in data else []
data[user_id] = {"count": 0, "date": today, "premium": prev_premium,
"favorites": prev_fav, "history": prev_hist}
return data[user_id]
def increment_usage(user_id: str):
data = load_usage()
usage = check_usage(user_id)
usage["count"] += 1
data[user_id] = usage
save_usage(data)
def add_favorite(user_id: str, quote: str, author: str, topic: str):
data = load_usage()
usage = check_usage(user_id)
if "favorites" not in usage:
usage["favorites"] = []
usage["favorites"].append({"quote": quote, "author": author, "topic": topic, "saved": datetime.now().isoformat()})
usage["favorites"] = usage["favorites"][-50:]
data[user_id] = usage
save_usage(data)
def get_favorites(user_id: str):
return check_usage(user_id).get("favorites", [])
def add_history(user_id: str, prompt: str, quote: str):
data = load_usage()
usage = check_usage(user_id)
if "history" not in usage:
usage["history"] = []
usage["history"].append({"prompt": prompt, "quote": quote, "time": datetime.now().isoformat()})
usage["history"] = usage["history"][-20:]
data[user_id] = usage
save_usage(data)
def set_premium(user_id: str, premium: bool = True):
data = load_usage()
if user_id not in data:
data[user_id] = {"count": 0, "date": datetime.now().strftime("%Y-%m-%d"), "premium": premium, "favorites": [], "history": []}
else:
data[user_id]["premium"] = premium
save_usage(data)
# ============ AI WISDOM GENERATION ============
def generate_wisdom(topic, style, mood, length, request: gr.Request):
user_id = get_user_id(request)
usage = check_usage(user_id)
if not usage.get("premium") and usage["count"] >= FREE_DAILY_LIMIT:
return (
"",
f"β **Daily Limit Reached** β You've used your {FREE_DAILY_LIMIT} free wisdom generations today.\n\n"
f"π **[Upgrade to Ethereal Wisdom Premium]({STRIPE_LINK})** for unlimited access!\n\n"
f"**Premium includes:**\n"
f"β’ Unlimited AI wisdom generations\n"
f"β’ Beautiful shareable quote cards\n"
f"β’ Personal collections & favorites\n"
f"β’ Daily wisdom digest email\n"
f"β’ No ads, priority speed\n\n"
f"Only {PREMIUM_PRICE}"
)
try:
API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
length_map = {"Short (1 sentence)": 1, "Medium (2-3 sentences)": 2, "Long (paragraph)": 3}
sentences = length_map.get(length, 2)
prompt = f"""[INST] You are a masterful wisdom generator. Write {sentences} profound, original wisdom quote about {topic.lower()} in the voice of a {style.lower()}.
Mood: {mood.lower()}
Requirements:
- Original and unique (not a known quote)
- Deeply insightful and thought-provoking
- Beautiful, poetic language
- No clichΓ©s or generic advice
- Format: Quote text followed by "β Style Name" attribution
Only output the quote and attribution. No extra text. [/INST]"""
max_tokens = 256 if usage.get("premium") else 128
payload = {
"inputs": prompt,
"parameters": {
"max_new_tokens": max_tokens,
"temperature": 0.8,
"top_p": 0.9,
"return_full_text": False
}
}
response = requests.post(API_URL, headers=headers, json=payload, timeout=45)
result = response.json()
if isinstance(result, list) and len(result) > 0:
text = result[0].get("generated_text", "").strip()
else:
text = str(result)
# Clean up the output
text = re.sub(r'?s>\s*', '', text)
text = re.sub(r'\[/?INST\]', '', text)
text = text.strip()
# If no attribution, add one
if 'β' not in text and '-' not in text[-30:]:
style_name = style.split('(')[0].strip() if '(' in style else style
text = f"{text}\n\nβ {style_name}"
# Extract quote and author
parts = text.split('β')
quote = parts[0].strip().strip('"').strip("'")
author = parts[1].strip() if len(parts) > 1 else style.split('(')[0].strip()
increment_usage(user_id)
add_history(user_id, f"{topic}, {style}, {mood}", quote)
remaining = "β Premium" if usage.get("premium") else f"{FREE_DAILY_LIMIT - usage['count'] - 1} left today"
return (
f"**{quote}**\n\nβ {author}",
f"β¨ Generated! {remaining}"
)
except Exception as e:
return "", f"β οΈ Error: {str(e)}. Please try again."
# ============ DAILY WISDOM ============
def get_daily_wisdom(request: gr.Request):
today = datetime.now().strftime("%A, %B %d")
topics = ["Gratitude", "Mindfulness", "Courage", "Growth", "Wisdom", "Love", "Purpose"]
topic = topics[datetime.now().weekday() % len(topics)]
style = WISDOM_STYLES[datetime.now().day % len(WISDOM_STYLES)]
quote, status = generate_wisdom(topic, style, "peaceful", "Medium (2-3 sentences)", request)
return f"### βοΈ Daily Wisdom β {today}\n\n{quote}"
# ============ COLLECTIONS ============
def show_collection(request: gr.Request):
user_id = get_user_id(request)
favs = get_favorites(user_id)
if not favs:
return "π« Your collection is empty. Generate wisdom and click β€οΈ to save!"
result = "### π Your Wisdom Collection\n\n"
for i, f in enumerate(reversed(favs), 1):
result += f"**{i}.** \"{f['quote']}\"\nβ {f['author']} | *{f['topic']}*\n\n---\n\n"
return result
# ============ ADMIN ============
def admin_upgrade(code, user_id):
if code != ADMIN_CODE:
return "β Invalid code"
set_premium(user_id, True)
return f"β
User {user_id} is now PREMIUM!"
def admin_stats(code):
if code != ADMIN_CODE:
return "β Invalid code"
data = load_usage()
total = len(data)
premium = sum(1 for u in data.values() if u.get("premium"))
today = datetime.now().strftime("%Y-%m-%d")
requests_today = sum(u.get("count", 0) for u in data.values() if u.get("date") == today)
total_favs = sum(len(u.get("favorites", [])) for u in data.values())
return f"π Stats:\nβ’ Users: {total}\nβ’ Premium: {premium}\nβ’ Requests today: {requests_today}\nβ’ Saved quotes: {total_favs}"
# ============ AD HTML ============
AD_BANNER = f"""
π’ Advertisement β Remove ads with Premium
Unlimited wisdom β’ Shareable cards β’ Collections β’ No ads
Upgrade β {PREMIUM_PRICE}AI-generated wisdom for your mind, heart, and soul
Free: 3/day | Premium: Unlimited
β¨ Ethereal Wisdom PRO Β© 2024