File size: 8,349 Bytes
2564faa
19783c5
9415b01
fcc996d
c4bcf1c
4cd71df
2564faa
aa73e64
cdc9d85
4cd71df
 
cdc9d85
 
 
fcc996d
cdc9d85
 
 
 
 
 
 
fcc996d
cdc9d85
 
aa73e64
ea19393
c4bcf1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e6078f
 
cdc9d85
c4bcf1c
 
2e6078f
cdc9d85
 
 
 
 
 
c4bcf1c
cdc9d85
 
 
 
 
 
 
c4bcf1c
cdc9d85
 
aa73e64
c4bcf1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa73e64
4cd71df
aa73e64
9415b01
cdc9d85
c4bcf1c
 
 
cdc9d85
c4bcf1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19783c5
aa73e64
4cd71df
aa73e64
9415b01
aa73e64
c4bcf1c
9415b01
 
c4bcf1c
 
 
 
 
 
 
 
 
 
 
cdc9d85
c4bcf1c
 
 
 
 
9415b01
 
cdc9d85
 
c4bcf1c
 
cdc9d85
2d977a0
c4bcf1c
 
 
 
 
 
 
 
 
 
 
 
2564faa
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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"<h1>{title}</h1>{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()