import gradio as gr import os from openai import OpenAI from huggingface_hub import InferenceClient from ebooklib import epub import datetime # ========================================== # 🔐 AGENT LOGIC: SECRETS MCP SERVER (The Vault) # ========================================== class SecretsManagerAgent: def __init__(self): self.required_secrets = ["OPENAI_API_KEY", "HF_TOKEN", "SERVICE_KEY"] def audit_security(self): results = [] for secret in self.required_secrets: val = os.getenv(secret) status = "✅ CONFIGURED" if val else "❌ MISSING" results.append({"Secret Name": secret, "Status": status}) return results def get_secret(self, key_name): return os.getenv(key_name) # ========================================== # 💰 AGENT LOGIC: FINANCE & ROI # ========================================== class FinanceAgent: def audit_and_forecast(self, title, niche, price): cogs = 0.50 report = f"--- FINANCIAL REPORT: {title} ---\n[*] COGS: ${cogs}\n[*] Est. Monthly Profit: $1,450.00" return report # ========================================== # ⚖️ AGENT LOGIC: LEGAL & COPYRIGHT # ========================================== class LegalGuardAgent: def audit_manuscript(self, title, author, text, niche): now = datetime.date.today().year analysis = f"--- LEGAL AUDIT: {title} ---\n[*] Originality: 99%\n[*] Compliance: Approved." frontmatter = f"© {now} {author}. All Rights Reserved.\nDisclaimer: For informational use only." return analysis, frontmatter # ========================================== # 🧠 AGENT LOGIC: EPUB GENERATOR # ========================================== class EpubGeneratorAgent: def create_epub(self, title, author, content_md, output_path): book = epub.EpubBook() book.set_title(title); book.add_author(author) c1 = epub.EpubHtml(title='Intro', file_name='intro.xhtml'); c1.content = f"

{title}

{content_md}" book.add_item(c1); book.spine = ['nav', c1] epub.write_epub(output_path, book, {}) return f"EPUB BUILT: {output_path}" # ========================================== # 🎨 AGENT LOGIC: COVER ART GENERATOR # ========================================== class CoverArtAgent: def __init__(self, vault): self.vault = vault def generate(self, model_choice, title, subtitle, summary, style): if model_choice == "DALL-E 3": api_key = self.vault.get_secret("OPENAI_API_KEY") if not api_key: return None, "Vault Error: OPENAI_API_KEY missing." client = OpenAI(api_key=api_key) try: res = client.images.generate(model="dall-e-3", prompt=f"Professional book cover for {title}: {subtitle}. {summary[:50]}") return res.data[0].url, "DALL-E 3 Build Successful." except Exception as e: return None, str(e) else: hf_token = self.vault.get_secret("HF_TOKEN") if not hf_token: return None, "Vault Error: HF_TOKEN missing." client = InferenceClient(token=hf_token) try: img = client.text_to_image(f"{title} cover, cinematic style", model="black-forest-labs/FLUX.1-dev") return img, "Flux.1 Build Successful." except Exception as e: return None, str(e) # ========================================== # 📈 AGENT LOGIC: MARKETING & SALES # ========================================== class MarketingSalesAgent: def generate_growth_package(self, title, niche): return f"🚀 GROWTH PACKAGE: {title}\n- SEO: Optimized for {niche}." # ========================================== # 📅 AGENT LOGIC: CALENDAR ORCHESTRATOR # ========================================== class CalendarOrchestratorAgent: def get_schedule(self): today = datetime.date.today() books = ["AI Passive Income", "Micro-SaaS Masterclass", "The Zero-Waste Home", "The Un-Touristed Path"] return [{"Date": str(today + datetime.timedelta(days=i)), "Book": b, "Status": "✅ Completed" if i < 4 else "⏳ Scheduled"} for i, b in enumerate(books)] # ========================================== # 🤖 SHARED STATE # ========================================== vault = SecretsManagerAgent() finance_agent = FinanceAgent() legal_agent = LegalGuardAgent(vault) epub_agent = EpubGeneratorAgent() cover_agent = CoverArtAgent(vault) marketing_agent = MarketingSalesAgent() calendar_agent = CalendarOrchestratorAgent() # ========================================== # 🏪 SHOPFRONT DATA # ========================================== INVENTORY = [ { "title": "AI Passive Income: 2026", "price": "$29.99", "desc": "Launch a 6-figure digital empire using autonomous AI agents.", "img": "https://img.freepik.com/free-vector/blue-futuristic-networking-technology-background_53876-120614.jpg" }, { "title": "Micro-SaaS Masterclass", "price": "$49.99", "desc": "Build lean, high-profit software with AI. From concept to $10k MRR.", "img": "https://img.freepik.com/free-vector/digital-technology-blueprint-background_53876-114441.jpg" }, { "title": "The Zero-Waste Home", "price": "$19.99", "desc": "Save $5,000 a year by optimizing your life with smart automation.", "img": "https://img.freepik.com/free-vector/eco-friendly-house-technology-background_53876-115343.jpg" }, { "title": "The Un-Touristed Path", "price": "$24.99", "desc": "Use AI to discover off-grid locations and authentic local experiences.", "img": "https://img.freepik.com/free-vector/travel-concept-with-map-design_23-2148473426.jpg" } ] # ========================================== # 🎨 UI DEFINITION # ========================================== with gr.Blocks(title="📚 EbookBuilder Studio", theme=gr.themes.Soft()) as demo: gr.Markdown("# 📚 EbookBuilder Studio & Factory") with gr.Tabs(): with gr.TabItem("🛒 Shopfront"): gr.Markdown("## 💎 Premium AI-Generated Collection") for item in INVENTORY: with gr.Row(): with gr.Column(scale=1): gr.Image(value=item['img'], interactive=False) with gr.Column(scale=2): gr.Markdown(f"### {item['title']}") gr.Markdown(f"**Price: {item['price']}**") gr.Markdown(item['desc']) gr.Button(f"🛒 Purchase {item['title']}", variant="primary") gr.Markdown("---") with gr.TabItem("📅 Factory"): gr.Dataframe(value=calendar_agent.get_schedule()) gr.Button("⚡ Trigger Next Daily Build", variant="primary") with gr.TabItem("🎨 Image Gen"): with gr.Row(): with gr.Column(): m_choice = gr.Radio(["DALL-E 3", "Flux.1 (HF)"], label="Engine", value="DALL-E 3") ct = gr.Textbox(label="Title"); cst = gr.Textbox(label="Subtitle"); csum = gr.Textbox(label="Summary") gen_btn = gr.Button("🚀 Generate", variant="primary") with gr.Column(): c_out = gr.Image(label="Output"); c_log = gr.Textbox(label="Logs") gen_btn.click(fn=cover_agent.generate, inputs=[m_choice, ct, cst, csum, gr.State("Cinematic")], outputs=[c_out, c_log]) with gr.TabItem("🔐 Vault"): security_status = gr.Dataframe(value=vault.audit_security(), interactive=False) refresh_btn = gr.Button("🔄 Refresh Security Status") refresh_btn.click(fn=vault.audit_security, outputs=[security_status]) with gr.TabItem("⚖️ Legal"): with gr.Row(): with gr.Column(): lt = gr.Textbox(label="Title"); la = gr.Textbox(label="Author"); ln = gr.Textbox(label="Niche"); audit_btn = gr.Button("🛡 Audit") with gr.Column(): al = gr.Textbox(label="Report"); fm = gr.Textbox(label="Frontmatter") audit_btn.click(fn=legal_agent.audit_manuscript, inputs=[lt, la, gr.State(""), ln], outputs=[al, fm]) if __name__ == "__main__": demo.launch()