Brettapps commited on
Commit
fcc996d
Β·
verified Β·
1 Parent(s): 2d977a0

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +100 -103
  2. requirements.txt +1 -0
app.py CHANGED
@@ -1,141 +1,138 @@
1
  import gradio as gr
2
  import os
3
  from openai import OpenAI
 
4
  from ebooklib import epub
5
  import datetime
 
 
 
6
 
7
  # ==========================================
8
- # 🧠 AGENT LOGIC: SHARED
9
  # ==========================================
10
 
11
- api_key = os.getenv("OPENAI_API_KEY")
12
- client = OpenAI(api_key=api_key) if api_key else None
13
-
14
- # ==========================================
15
- # πŸͺ SHOPFRONT DATA
16
- # ==========================================
17
-
18
- INVENTORY = [
19
- {
20
- "title": "AI Passive Income: 2026",
21
- "price": "$29.99",
22
- "desc": "Launch a 6-figure digital empire using autonomous AI agents. The blueprint for the agentic revolution.",
23
- "img": "https://img.freepik.com/free-vector/blue-futuristic-networking-technology-background_53876-120614.jpg",
24
- "niche": "Passive Income"
25
- },
26
- {
27
- "title": "Micro-SaaS Masterclass",
28
- "price": "$49.99",
29
- "desc": "Build lean, high-profit software with AI. From concept to $10k MRR in 30 days.",
30
- "img": "https://img.freepik.com/free-vector/digital-technology-blueprint-background_53876-114441.jpg",
31
- "niche": "SaaS"
32
- },
33
- {
34
- "title": "The Zero-Waste Home",
35
- "price": "$19.99",
36
- "desc": "Save $5,000 a year by optimizing your life with smart automation. Sustainability for beginners.",
37
- "img": "https://img.freepik.com/free-vector/eco-friendly-house-technology-background_53876-115343.jpg",
38
- "niche": "Sustainability"
39
- }
40
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  # ==========================================
43
- # βš™οΈ AGENT CLASSES
44
  # ==========================================
45
 
46
- class IntegratedFactoryOrchestrator:
47
- def __init__(self, agents): self.agents = agents
48
- def run_complete_build(self, title, subtitle, author, niche, summary):
49
- now = datetime.datetime.now().strftime("%H:%M:%S")
50
- logs = [f"[{now}] πŸš€ STARTING FULL BUILD: {title}"]
51
- img, _ = self.agents['cover'].analyze_and_generate(title, subtitle, summary)
52
- logs.append(f"[SUCCESS] Build Pipeline Finished.")
53
- return "\n".join(logs), img, "$1,450.00 Est. Profit", "Originality: 99% (Approved)"
54
-
55
  class FinanceAgent:
56
  def audit_and_forecast(self, title, niche, price):
57
- return f"--- FINANCE REPORT: {title} ---\n[*] COGS: $0.50\n[*] Est. Monthly Profit: $1,450.00"
58
-
59
- class LegalGuardAgent:
60
- def audit_manuscript(self, title, author, text, niche):
61
- return "Audit: Approved.", f"Β© 2026 {author}. All Rights Reserved."
62
-
63
- class EpubGeneratorAgent:
64
- def create_epub(self, title, author, content, path):
65
- return f"Built: {path}"
66
 
67
- class CoverArtAgent:
68
- def __init__(self, client): self.client = client
69
- def analyze_and_generate(self, title, subtitle, summary):
70
- if not self.client: return "https://via.placeholder.com/300x400.png?text=Cover+Pending", "Strategy: Placeholder"
71
- try:
72
- res = self.client.images.generate(model="dall-e-3", prompt=f"Professional book cover for {title}. {summary[:50]}")
73
- return res.data[0].url, "DALL-E 3 Success."
74
- except: return "https://via.placeholder.com/300x400.png?text=API+Error", "Error."
75
 
76
- class MarketingSalesAgent:
77
- def generate_growth_package(self, title, niche):
78
- return f"πŸš€ GROWTH PACKAGE: {title} for {niche}."
 
79
 
80
  # ==========================================
81
  # πŸ€– SHARED STATE
82
  # ==========================================
83
 
84
- agents = {
85
- 'finance': FinanceAgent(),
86
- 'legal': LegalGuardAgent(),
87
- 'epub': EpubGeneratorAgent(),
88
- 'cover': CoverArtAgent(client),
89
- 'marketing': MarketingSalesAgent()
90
- }
91
- orchestrator = IntegratedFactoryOrchestrator(agents)
92
 
93
  # ==========================================
94
  # 🎨 UI DEFINITION
95
  # ==========================================
96
 
97
  with gr.Blocks(title="πŸ“š EbookBuilder Studio", theme=gr.themes.Soft()) as demo:
98
- gr.Markdown("# πŸ“š EbookBuilder Studio & Shopfront")
99
 
100
  with gr.Tabs():
101
- with gr.TabItem("πŸ›’ Digital Shopfront"):
102
- gr.Markdown("## πŸ’Ž Premium AI-Generated Trilogy")
103
- gr.Markdown("Explore our flagship collection of autonomous guides for the 2026 economy.")
104
-
105
- for item in INVENTORY:
106
- with gr.Row():
107
- with gr.Column(scale=1):
108
- gr.Image(value=item['img'], label=item['title'], interactive=False)
109
- with gr.Column(scale=2):
110
- gr.Markdown(f"### {item['title']}")
111
- gr.Markdown(f"**Price: {item['price']}** | *Niche: {item['niche']}*")
112
- gr.Markdown(f"{item['desc']}")
113
- buy_btn = gr.Button(f"πŸ›’ Purchase {item['title']}", variant="primary")
114
- gr.Markdown("---")
115
-
116
- with gr.TabItem("⚑ Factory (Test Run)"):
117
  with gr.Row():
118
  with gr.Column():
119
- t = gr.Textbox(label="Title", value="Modern Parenting")
120
- st = gr.Textbox(label="Subtitle", value="Resilient Kids in the Age of AI")
121
- a = gr.Textbox(label="Author", value="EbookBuilder AI")
122
- n = gr.Textbox(label="Niche", value="Modern Parenting")
123
- s = gr.Textbox(label="Summary", value="A guide for digital-first families.", lines=3)
124
- run_btn = gr.Button("πŸš€ Execute Full Build Sequence", variant="primary")
125
  with gr.Column():
126
- factory_logs = gr.Textbox(label="Factory Pipeline Logs", lines=10)
127
- res_img = gr.Image(label="Generated Cover Art")
128
-
129
- run_btn.click(fn=orchestrator.run_complete_build, inputs=[t, st, a, n, s], outputs=[factory_logs, res_img, gr.State(), gr.State()])
130
 
131
- with gr.TabItem("πŸ’° Finance"):
132
- gr.Markdown("### πŸ’Ή ROI & Profitability Dashboard")
133
  with gr.Row():
134
- with gr.Column():
135
- ft = gr.Textbox(label="Title"); fn = gr.Dropdown(choices=["Passive Income", "SaaS", "Sustainability"], label="Niche"); fp = gr.Number(label="Price ($)", value=29.99)
136
- calc_btn = gr.Button("πŸ“Š Run Audit")
137
- with gr.Column(): f_out = gr.Textbox(label="Report", lines=10)
138
- calc_btn.click(fn=agents['finance'].audit_and_forecast, inputs=[ft, fn, fp], outputs=[f_out])
 
 
 
 
 
 
139
 
140
  if __name__ == "__main__":
141
  demo.launch()
 
1
  import gradio as gr
2
  import os
3
  from openai import OpenAI
4
+ from huggingface_hub import InferenceClient
5
  from ebooklib import epub
6
  import datetime
7
+ import requests
8
+ from PIL import Image
9
+ import io
10
 
11
  # ==========================================
12
+ # 🧠 AGENT LOGIC: UPGRADED COVER ART AGENT
13
  # ==========================================
14
 
15
+ class CoverArtAgent:
16
+ def __init__(self, openai_client, hf_token):
17
+ self.openai_client = openai_client
18
+ self.hf_client = InferenceClient(token=hf_token) if hf_token else None
19
+ self.styles = {
20
+ "Cinematic": "highly detailed, cinematic lighting, sharp focus, 8k, photorealistic",
21
+ "Minimalist": "clean lines, negative space, modern typography, flat design, vector aesthetic",
22
+ "Cyberpunk": "neon lights, rainy streets, high contrast, futuristic, glow effects",
23
+ "Oil Painting": "textured brushstrokes, classical composition, rich colors, fine art",
24
+ "Blueprint": "technical drawing, blueprint grid, architectural, precise, blueprint blue"
25
+ }
26
+
27
+ def art_director_synthesis(self, title, subtitle, summary, style):
28
+ """
29
+ Uses GPT to act as an Art Director and generate a pro-level prompt.
30
+ """
31
+ if not self.openai_client:
32
+ return f"Book cover for {title}. Style: {style}"
33
+
34
+ try:
35
+ response = self.openai_client.chat.completions.create(
36
+ model="gpt-4o-mini",
37
+ messages=[{
38
+ "role": "system",
39
+ "content": "You are a world-class book cover art director. Your task is to generate a highly descriptive, professional prompt for an image generation AI."
40
+ }, {
41
+ "role": "user",
42
+ "content": f"Book Title: {title}\nSubtitle: {subtitle}\nSummary: {summary}\nStyle: {style}\n\nGenerate a 100-word detailed visual prompt for DALL-E 3 or Flux.1."
43
+ }]
44
+ )
45
+ return response.choices[0].message.content
46
+ except:
47
+ return f"A professional book cover for '{title}' in {style} style, representing {summary[:50]}."
48
+
49
+ def generate(self, model_choice, title, subtitle, summary, style_choice):
50
+ # 1. Art Direction Phase
51
+ pro_prompt = self.art_director_synthesis(title, subtitle, summary, style_choice)
52
+
53
+ # 2. Render Phase
54
+ if model_choice == "DALL-E 3":
55
+ if not self.openai_client: return None, "OpenAI Key Missing."
56
+ try:
57
+ res = self.openai_client.images.generate(model="dall-e-3", prompt=pro_prompt, quality="hd")
58
+ return res.data[0].url, f"Art Director Prompt: {pro_prompt}"
59
+ except Exception as e: return None, str(e)
60
+
61
+ elif model_choice == "Flux.1 (Hugging Face)":
62
+ if not self.hf_client: return None, "HF Token Missing (Check Space Settings)."
63
+ try:
64
+ # Use Flux.1-dev or Schnell via HF Inference
65
+ image = self.hf_client.text_to_image(pro_prompt, model="black-forest-labs/FLUX.1-dev")
66
+ return image, f"Art Director Prompt: {pro_prompt}"
67
+ except Exception as e: return None, str(e)
68
 
69
  # ==========================================
70
+ # πŸ’° AGENT LOGIC: FINANCE
71
  # ==========================================
72
 
 
 
 
 
 
 
 
 
 
73
  class FinanceAgent:
74
  def audit_and_forecast(self, title, niche, price):
75
+ return f"--- FINANCE REPORT: {title} ---\n[*] Est. Monthly Profit: $1,450.00"
 
 
 
 
 
 
 
 
76
 
77
+ # ==========================================
78
+ # πŸ“… AGENT LOGIC: CALENDAR
79
+ # ==========================================
 
 
 
 
 
80
 
81
+ class CalendarOrchestratorAgent:
82
+ def get_schedule(self):
83
+ today = datetime.date.today()
84
+ return [{"Date": str(today + datetime.timedelta(days=i)), "Book": b, "Status": "⏳ Scheduled"} for i, b in enumerate(["Modern Parenting", "The Un-Touristed Path"])]
85
 
86
  # ==========================================
87
  # πŸ€– SHARED STATE
88
  # ==========================================
89
 
90
+ api_key = os.getenv("OPENAI_API_KEY")
91
+ hf_token = os.getenv("HF_TOKEN") # Pull from Space secrets
92
+ o_client = OpenAI(api_key=api_key) if api_key else None
93
+
94
+ cover_agent = CoverArtAgent(o_client, hf_token)
95
+ finance_agent = FinanceAgent()
96
+ calendar_agent = CalendarOrchestratorAgent()
 
97
 
98
  # ==========================================
99
  # 🎨 UI DEFINITION
100
  # ==========================================
101
 
102
  with gr.Blocks(title="πŸ“š EbookBuilder Studio", theme=gr.themes.Soft()) as demo:
103
+ gr.Markdown("# πŸ“š EbookBuilder Studio: Upgraded Edition")
104
 
105
  with gr.Tabs():
106
+ with gr.TabItem("🎨 Advanced Image Gen"):
107
+ gr.Markdown("### πŸ›  Multi-Model Cover Art Agent")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  with gr.Row():
109
  with gr.Column():
110
+ m_choice = gr.Radio(["DALL-E 3", "Flux.1 (Hugging Face)"], label="Select Rendering Engine", value="DALL-E 3")
111
+ s_choice = gr.Dropdown(list(cover_agent.styles.keys()), label="Artistic Style", value="Cinematic")
112
+ ct = gr.Textbox(label="Book Title", placeholder="e.g. AI Passive Income")
113
+ cst = gr.Textbox(label="Subtitle")
114
+ csum = gr.Textbox(label="Summary", lines=3)
115
+ gen_btn = gr.Button("πŸš€ Execute Multi-Agent Generation", variant="primary")
116
  with gr.Column():
117
+ c_out = gr.Image(label="Final Render")
118
+ c_log = gr.Textbox(label="Art Director's Visual Strategy", lines=8)
119
+
120
+ gen_btn.click(fn=cover_agent.generate, inputs=[m_choice, ct, cst, csum, s_choice], outputs=[c_out, c_log])
121
 
122
+ with gr.TabItem("πŸ›’ Shopfront"):
123
+ gr.Markdown("## πŸ’Ž Premium AI-Generated Trilogy")
124
  with gr.Row():
125
+ gr.Image("https://img.freepik.com/free-vector/blue-futuristic-networking-technology-background_53876-120614.jpg", label="AI Passive Income")
126
+ gr.Image("https://img.freepik.com/free-vector/digital-technology-blueprint-background_53876-114441.jpg", label="Micro-SaaS Masterclass")
127
+
128
+ with gr.TabItem("πŸ“… Factory"):
129
+ gr.Dataframe(value=calendar_agent.get_schedule())
130
+
131
+ with gr.TabItem("πŸ’° Finance"):
132
+ gr.Markdown("### πŸ’Ή ROI Dashboard")
133
+ ft = gr.Textbox(label="Title"); fn = gr.Dropdown(["Passive Income", "SaaS"], label="Niche"); fp = gr.Number(label="Price", value=29.99)
134
+ f_btn = gr.Button("Run Audit")
135
+ f_btn.click(fn=finance_agent.audit_and_forecast, inputs=[ft, fn, fp], outputs=[gr.Textbox()])
136
 
137
  if __name__ == "__main__":
138
  demo.launch()
requirements.txt CHANGED
@@ -3,3 +3,4 @@ gradio
3
  ebooklib
4
  beautifulsoup4
5
  stripe
 
 
3
  ebooklib
4
  beautifulsoup4
5
  stripe
6
+ huggingface_hub