GenStories / app.py
aunixstudios's picture
Update app.py
f9c8cfc verified
Raw History Blame Contribute Delete
11.1 kB
import gradio as gr
import firebase_admin
from firebase_admin import credentials, firestore
import os
import json
import requests
import uuid
from datetime import datetime
import asyncio
# --- πŸ”‘ Firebase Configuration ---
FIREBASE_API_KEY = "AIzaSyDlpcYI6mB4BQW-yNiPxeyh63YPulIepJ0"
FIREBASE_PROJECT_ID = "genstories-e47e8"
# --- πŸš€ Initialize Firebase ---
def init_firebase():
if not firebase_admin._apps:
try:
firebase_key_json = os.getenv('FIREBASE_SERVICE_ACCOUNT_KEY')
if firebase_key_json:
cred_dict = json.loads(firebase_key_json)
cred = credentials.Certificate(cred_dict)
else:
# Fallback for local dev
cred = credentials.Certificate("firebase-service-account-key.json")
firebase_admin.initialize_app(cred, {
'projectId': FIREBASE_PROJECT_ID,
'storageBucket': 'genstories-e47e8.firebasestorage.app'
})
print("βœ… Firebase initialized")
except Exception as e:
print(f"πŸ”₯ Firebase init error: {str(e)}")
raise e
init_firebase()
db = firestore.client()
# --- 🧠 AI Story Generator (Replace this with your real AI model) ---
async def generate_ai_story(prompt: str) -> str:
await asyncio.sleep(1.5) # Simulate AI delay
stories = [
f"""**The Legend of {prompt.title()}**
In a realm where {prompt.lower()}, magic flowed like rivers and shadows whispered secrets, there lived a wanderer named Kael. With eyes like storm clouds and a heart full of curiosity, Kael carried a lantern that glowed with forgotten dreams.
One twilight, guided by the lantern’s pulse, Kael stumbled upon a door carved into the bark of an ancient oak. The door opened not to wood, but to starlight β€” and beyond it, a world waiting to be written.
This is where your story begins...""",
f"""**Whispers from the {prompt.split()[0] if prompt else 'Void'}**
They said the {prompt.lower()} was cursed β€” a place where time unraveled and memories turned to mist. But Lyra didn’t believe in curses. She believed in stories. And so, with a satchel of inkwells and a quill carved from dragonbone, she stepped across the threshold.
What she found was not a curse… but a beginning. A story only she could tell. Page by page, breath by breath, Lyra wove the chaos into song β€” and the song became a world.
And you? You’re holding the next page."""
]
import random
return random.choice(stories)
async def enhance_story(content: str, prompt: str = "") -> str:
await asyncio.sleep(1)
return f"""🌟 **ENHANCED EDITION** 🌟
{content}
---
✨ *AI-enhanced with richer worldbuilding, deeper character arcs, and cinematic pacing based on your prompt: β€œ{prompt}”*
*(Pro tip: Click β€œSave to Library” after enhancing to keep your favorite version!)*"""
# --- πŸ› οΈ Firebase Auth & DB ---
def firebase_sign_in(email: str, password: str):
url = f"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={FIREBASE_API_KEY}"
res = requests.post(url, json={"email": email, "password": password, "returnSecureToken": True})
if res.status_code == 200:
return res.json()
else:
raise Exception(res.json().get("error", {}).get("message", "Auth failed"))
def firebase_sign_up(email: str, password: str):
url = f"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key={FIREBASE_API_KEY}"
res = requests.post(url, json={"email": email, "password": password, "returnSecureToken": True})
if res.status_code == 200:
return res.json()
else:
raise Exception(res.json().get("error", {}).get("message", "Signup failed"))
def save_story(user_id: str, title: str, content: str, prompt: str):
doc_id = str(uuid.uuid4())
db.collection("stories").document(doc_id).set({
"id": doc_id,
"user_id": user_id,
"title": title,
"content": content,
"prompt": prompt,
"created_at": datetime.now().isoformat()
})
return doc_id
def load_user_stories(user_id: str):
docs = db.collection("stories").where("user_id", "==", user_id).stream()
return [doc.to_dict() for doc in docs]
# --- 🎯 Main App Logic ---
class StoryManager:
def __init__(self):
self.user = None
self.stories = [] # Locally generated stories
async def generate(self, prompt: str):
if not prompt.strip():
return gr.update(), "⚠️ Please enter a prompt.", self
try:
content = await generate_ai_story(prompt)
title = f"Story: {prompt[:40]}..." if len(prompt) > 40 else f"Story: {prompt}"
story = {"title": title, "content": content, "prompt": prompt, "id": str(uuid.uuid4())}
self.stories.insert(0, story) # Add to top
# Render all stories
story_blocks = self._render_stories()
return story_blocks, f"βœ… Generated: '{title}'", self
except Exception as e:
return gr.update(), f"❌ Error: {str(e)}", self
def _render_stories(self):
"""Returns a Gradio Column containing all story cards"""
with gr.Column() as container:
for i, story in enumerate(self.stories):
self._create_story_card(story, i)
return container
def _create_story_card(self, story, index):
with gr.Group():
gr.Markdown(f"### {story['title']}")
gr.Markdown(f"*Prompt: {story['prompt']}*")
content_box = gr.Textbox(story["content"], lines=10, max_lines=20, label="Story", interactive=True)
with gr.Row():
copy_btn = gr.Button("πŸ“‹ Copy", size="sm")
enhance_btn = gr.Button("✨ Enhance", size="sm")
save_btn = gr.Button("πŸ’Ύ Save", size="sm", visible=bool(self.user))
status = gr.Markdown(visible=False)
# Actions
copy_btn.click(None, content_box, None, js="(text) => { navigator.clipboard.writeText(text); alert('Copied! πŸ“‹'); }")
enhance_btn.click(
fn=lambda c, p: asyncio.run(enhance_story(c, p)),
inputs=[content_box, gr.Textbox(story["prompt"], visible=False)],
outputs=content_box
)
if self.user:
save_btn.click(
fn=lambda: save_story(self.user["localId"], story["title"], story["content"], story["prompt"]),
inputs=None,
outputs=status
).success(
fn=lambda: "βœ… Saved to library!",
inputs=None,
outputs=status
)
def login(self, email, password):
try:
self.user = firebase_sign_in(email, password)
return self, f"βœ… Welcome, {self.user['email']}!", gr.update(visible=False)
except Exception as e:
return self, f"❌ {str(e)}", gr.update(visible=True)
def signup(self, email, password, confirm):
if password != confirm:
return self, "❌ Passwords don’t match", gr.update(visible=True)
try:
self.user = firebase_sign_up(email, password)
return self, f"βœ… Signed up! Welcome, {self.user['email']}!", gr.update(visible=False)
except Exception as e:
return self, f"❌ {str(e)}", gr.update(visible=True)
def logout(self):
self.user = None
return self, "πŸ‘‹ Logged out.", gr.update(visible=True)
def load_saved(self):
if not self.user:
return gr.update(), "⚠️ Sign in to view saved stories."
try:
saved = load_user_stories(self.user["localId"])
with gr.Column() as container:
for i, story in enumerate(saved):
self._create_story_card(story, i)
return container, f"πŸ“š {len(saved)} saved stories loaded."
except Exception as e:
return gr.update(), f"❌ {str(e)}"
# --- 🎨 Build UI ---
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# πŸ“– GenStories AI")
gr.Markdown("### Enter a prompt. Get a magical story. Enhance it. Save it. All yours.")
state = gr.State(StoryManager())
with gr.Tabs():
with gr.Tab("✨ Generate"):
with gr.Row():
with gr.Column(scale=1):
prompt = gr.Textbox(label="Your Story Prompt", placeholder="e.g., A robot who discovers emotions in a post-apocalyptic world...", lines=3)
btn = gr.Button("Generate Story πŸš€", variant="primary")
status = gr.Markdown()
with gr.Column(scale=2):
story_container = gr.Column()
btn.click(
fn=lambda p, s: asyncio.run(s.generate(p)),
inputs=[prompt, state],
outputs=[story_container, status, state]
)
with gr.Tab("πŸ“š Library"):
load_btn = gr.Button("Load My Saved Stories")
saved_container = gr.Column()
saved_status = gr.Markdown()
load_btn.click(
fn=lambda s: s.load_saved(),
inputs=state,
outputs=[saved_container, saved_status]
)
with gr.Tab("ℹ️ About"):
gr.Markdown("""
## 🌟 GenStories AI
- Type any idea β†’ Get a unique AI-generated story
- ✨ Enhance: Make it richer & deeper
- πŸ’Ύ Save: Keep your favorites forever
- πŸ” Sign in to access across devices
""")
with gr.Accordion("πŸ” Account", open=False):
with gr.Tabs():
with gr.Tab("Sign In"):
email_in = gr.Textbox(label="Email")
pass_in = gr.Textbox(label="Password", type="password")
signin_btn = gr.Button("Sign In")
signin_status = gr.Markdown()
with gr.Tab("Sign Up"):
email_up = gr.Textbox(label="Email")
pass_up = gr.Textbox(label="Password", type="password")
pass_confirm = gr.Textbox(label="Confirm Password", type="password")
signup_btn = gr.Button("Sign Up")
signup_status = gr.Markdown()
logout_btn = gr.Button("πŸšͺ Logout", visible=False)
signin_btn.click(
fn=lambda e, p, s: s.login(e, p),
inputs=[email_in, pass_in, state],
outputs=[state, signin_status, logout_btn]
)
signup_btn.click(
fn=lambda e, p, c, s: s.signup(e, p, c, s),
inputs=[email_up, pass_up, pass_confirm, state],
outputs=[state, signup_status, logout_btn]
)
logout_btn.click(
fn=lambda s: s.logout(),
inputs=state,
outputs=[state, status, logout_btn]
)
if __name__ == "__main__":
demo.queue().launch()