VendIQ / app.py
rohit-97535470279's picture
Update app.py
20b205a verified
# =========================================================
# VendIQ – Intelligent Market Assistant (LangGraph + Gradio)
# Founder: Rohit Kumar | Data Scientist
# =========================================================
import os
import random
import sqlite3
from datetime import datetime
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
import torch
from transformers import pipeline
from diffusers import StableDiffusionPipeline
# ---- LangGraph Imports ----
from langgraph.graph import StateGraph, END
from typing import TypedDict, Optional
# ---- LangChain community imports ----
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
# ---- UI ----
import gradio as gr
# =========================================================
# 1. CONFIGURATION
# =========================================================
TEXT_MODEL = "google/flan-t5-large"
IMAGE_MODEL = "runwayml/stable-diffusion-v1-5"
EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
PDF_PATH = "Business Strategy Document – Mukesh Ambani Style.pdf"
DB_PATH = "vendiq.db"
device = "cuda" if torch.cuda.is_available() else "cpu"
text_gen = pipeline("text2text-generation", model=TEXT_MODEL)
try:
image_gen = StableDiffusionPipeline.from_pretrained(
IMAGE_MODEL,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
safety_checker=None
).to(device)
except Exception:
image_gen = None
# =========================================================
# 2. DATABASE
# =========================================================
def init_db():
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS deals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
company TEXT,
product TEXT,
strategy TEXT,
profit REAL,
marketing TEXT,
created_at TEXT
)''')
conn.commit()
conn.close()
init_db()
# =========================================================
# 3. CONTEXT MEMORY
# =========================================================
def load_strategy():
emb = HuggingFaceEmbeddings(model_name=EMBED_MODEL)
if os.path.exists(PDF_PATH):
loader = PyPDFLoader(PDF_PATH)
pages = loader.load()
vectordb = FAISS.from_documents(pages, emb)
return vectordb
return FAISS.from_texts(
["Reliance-style strategy emphasizing scale, technology, and market dominance"],
emb
)
vectordb = load_strategy()
def get_context(query):
try:
results = vectordb.similarity_search(query, k=2)
return "\n".join([r.page_content for r in results])
except Exception:
return "Reliance-inspired strategy: scale, vertical integration, and customer-first innovation."
# =========================================================
# 4. LANGGRAPH STATE
# =========================================================
class VendIQState(TypedDict):
scenario: str
product: str
context: Optional[str]
strategy: Optional[str]
marketing: Optional[str]
profit: Optional[float]
chart_path: Optional[str]
ad_path: Optional[str]
# =========================================================
# 5. NODES
# =========================================================
def context_node(state: VendIQState):
context = get_context(state["scenario"])
state["context"] = context if context else f"General B2B environment for {state['scenario']}"
return state
def strategy_node(state: VendIQState):
tone = random.choice([
"aggressive expansion mindset",
"strategic partnership and alliance-driven growth",
"innovation-led differentiation and disruption",
"cost leadership with scalability focus",
"customer loyalty and retention-based positioning"
])
focus = random.choice([
"digital transformation and process automation",
"supply chain optimization and vendor integration",
"B2B channel growth and ecosystem partnerships",
"new market entry and regional dominance",
"AI-driven customer analytics and personalization"
])
risk_profile = random.choice([
"high-reward disruptive expansion",
"balanced strategic scaling",
"low-risk sustainable long-term growth"
])
prompt = f"""
You are **VendIQ**, an AI Strategy Architect modeled on Mukesh Ambani’s philosophy:
*scale fast, integrate vertically, and own the market ecosystem.*
---
### 🧩 Context
{state["context"]}
### 🌍 Scenario
{state["scenario"]}
### 🏷️ Product
{state["product"]}
---
### 🎯 Objective
Formulate a **5-Step Negotiation & Market-Entry Strategy** for **{state["product"]}**, crafted in Ambani-style β€” focused on ecosystem control, long-term scale, and competitive dominance.
πŸ”Ή **Approach Tone:** {tone}
πŸ”Ή **Strategic Focus:** {focus}
πŸ”Ή **Risk Appetite:** {risk_profile}
---
### πŸ“˜ Each Step Should Include:
1️⃣ **Objective** β€” Clear, measurable business goal.
2️⃣ **Action Plan** β€” Concrete strategic move or partnership.
3️⃣ **Rationale** β€” Market or competitive logic behind it.
4️⃣ **Expected Outcome** β€” Measurable or strategic impact.
5️⃣ **Ambani-Style Twist** β€” How vertical integration or scale amplifies the result.
---
Format clearly using numbered steps (1–5).
End with a single-line **Positioning Summary** showing how {state["product"]} establishes category dominance.
Maintain a professional, analytical tone β€” like a market intelligence brief.
"""
state["strategy"] = text_gen(prompt.strip(), max_length=700, temperature=0.85)[0]["generated_text"]
return state
# =========================================================
# 🧩 MARKETING NODE β€” DISTINCT 7-DAY PLAN (Ambani-Style)
# =========================================================
def marketing_node(state):
"""
Generates a 7-Day Ambani-style Marketing Plan based on the scenario and product.
Ensures clear day-wise objectives, actions, and KPIs.
"""
prompt = f"""
You are **VendIQ**, an AI-powered B2B Marketing Strategist inspired by Reliance’s agility, scale, and dominance mindset.
Your goal is to convert a strategic vision into a precise 7-day marketing execution plan.
### Scenario
{state["scenario"]}
### Product
{state["product"]}
### Strategic Philosophy (for inspiration)
{state["context"]}
---
### TASK
Ignore negotiation or high-level strategy repetition.
Focus on practical execution β€” digital + field + B2B partnerships.
Be concise, measurable, and bold. Use Reliance-style scale thinking.
Generate a **7-Day Marketing Plan** using this format:
#### πŸ—“οΈ Day 1: Market Pulse
- **Objective:** Identify initial customer response
- **Action Steps:** (2–3 crisp bullet points)
- **KPIs:** (measurable goals)
#### πŸš€ Day 2: Visibility & Awareness
...
Continue till **Day 7**, ending with a summary that highlights momentum, scaling, and brand loyalty.
Ensure:
- Each day has a unique purpose.
- Avoid repeating negotiation/strategy language.
- Include Ambani-style confidence in tone.
- Output should read like a business execution manual.
---
### OUTPUT
Now write the full 7-day marketing plan below:
"""
from transformers import pipeline
text_gen = pipeline("text-generation", model="google/flan-t5-large")
marketing_plan = text_gen(prompt.strip(), max_length=900, temperature=1.05)[0]["generated_text"]
# Save to state
state["marketing"] = marketing_plan
return state
def profit_node(state: VendIQState):
"""
Generates a realistic 7-day profit forecast visualization for the product.
Includes business-like chart design and performance trend logic.
"""
base_profit = random.randint(500, 2500)
growth_trend = random.choice(["upward", "steady", "volatile", "decline-risk"])
if growth_trend == "upward":
profits = [base_profit + i * random.randint(40, 120) for i in range(7)]
elif growth_trend == "steady":
profits = [base_profit + random.randint(-50, 50) for _ in range(7)]
elif growth_trend == "volatile":
profits = [base_profit + random.randint(-200, 250) for _ in range(7)]
else:
profits = [base_profit - i * random.randint(20, 70) for i in range(7)]
days = list(range(1, 8))
plt.figure(figsize=(6, 3.5))
plt.plot(days, profits, marker="o", linewidth=2)
plt.title(f"πŸ“Š 7-Day Profit Projection – {state['product']}", fontsize=11, fontweight="bold")
plt.xlabel("Day", fontsize=9)
plt.ylabel("Profit ($)", fontsize=9)
plt.grid(True, linestyle="--", alpha=0.6)
plt.tight_layout()
chart_path = f"{state['product']}_profit.png"
plt.savefig(chart_path, dpi=150)
plt.close()
state["profit"] = profits[-1]
state["chart_path"] = chart_path
return state
def ad_node(state: VendIQState):
"""
Generates a B2B advertisement image for the product.
Uses Stable Diffusion if available; otherwise, falls back to a styled banner.
"""
theme = random.choice([
"AI innovation and automation",
"enterprise intelligence and scale",
"sustainability and green business",
"luxury fintech excellence",
"smart logistics transformation",
"healthcare precision technology"
])
color_scheme = random.choice([
"blue and silver",
"black and gold",
"emerald green and white",
"navy and cyan",
"crimson red and charcoal gray",
"deep teal and white"
])
visual_tone = random.choice([
"futuristic realism",
"executive corporate branding",
"3D minimalism with strong contrast",
"AI-powered digital theme",
"luxury business aesthetics"
])
if image_gen:
prompt = (
f"Design a premium B2B advertisement for a product named {state['product']}. "
f"Theme: {theme}. "
f"Color scheme: {color_scheme}. "
f"Visual tone: {visual_tone}. "
f"Include elements of market leadership, innovation, and trust. "
f"Style: professional, cinematic, and Ambani-style corporate dominance. "
f"No text or logos. 16:9 aspect ratio."
)
img = image_gen(prompt).images[0]
else:
# Fallback banner generation
color_map = {
"blue and silver": (40, 60, 140),
"black and gold": (30, 25, 25),
"emerald green and white": (0, 100, 60),
"navy and cyan": (15, 40, 80),
"crimson red and charcoal gray": (90, 20, 30),
"deep teal and white": (0, 80, 85)
}
bg_color = color_map.get(color_scheme, (0, 80, 160))
img = Image.new("RGB", (960, 540), color=bg_color)
draw = ImageDraw.Draw(img)
font = ImageFont.load_default()
# Add subtle design
draw.rectangle([0, 400, 960, 540], fill=(255, 255, 255, 40))
draw.text((30, 430), f"{state['product']}", font=font, fill="white")
draw.text((30, 460), "Powered by VendIQ – B2B Market Intelligence", font=font, fill="white")
ad_path = f"{state['product']}_ad.png"
img.save(ad_path)
state["ad_path"] = ad_path
return state
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib.utils import simpleSplit
def save_to_pdf(product, strategy_text, marketing_text):
filename = f"{product.replace(' ', '_')}_VendIQ_Report.pdf"
c = canvas.Canvas(filename, pagesize=A4)
width, height = A4
# ---- Title ----
c.setFont("Helvetica-Bold", 18)
c.drawCentredString(width / 2, height - 1*inch, "VendIQ – Strategic Market Report")
c.setFont("Helvetica", 12)
c.drawCentredString(width / 2, height - 1.3*inch, f"Product: {product}")
c.drawCentredString(width / 2, height - 1.6*inch, datetime.now().strftime("Generated on %Y-%m-%d %H:%M"))
c.line(1*inch, height - 1.7*inch, width - 1*inch, height - 1.7*inch)
# ---- Section 1: Negotiation & Market Entry ----
text_obj = c.beginText(1*inch, height - 2.2*inch)
text_obj.setFont("Helvetica-Bold", 14)
text_obj.textLine("Section 1 – Negotiation & Market Entry Strategy")
text_obj.setFont("Helvetica", 11)
text_obj.textLine("")
for line in simpleSplit(strategy_text, "Helvetica", 11, width - 2*inch):
text_obj.textLine(line)
c.drawText(text_obj)
# ---- Section 2: 7-Day Marketing Plan ----
c.showPage()
text_obj = c.beginText(1*inch, height - 1*inch)
text_obj.setFont("Helvetica-Bold", 14)
text_obj.textLine("Section 2 – 7-Day B2B Marketing Plan")
text_obj.setFont("Helvetica", 11)
text_obj.textLine("")
for line in simpleSplit(marketing_text, "Helvetica", 11, width - 2*inch):
text_obj.textLine(line)
c.drawText(text_obj)
c.save()
return filename
def save_node(state: VendIQState):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute(
"INSERT INTO deals (company, product, strategy, profit, marketing, created_at) VALUES (?, ?, ?, ?, ?, ?)",
("GlobalTech", state["product"], state["strategy"], state["profit"], state["marketing"],
datetime.now().strftime("%Y-%m-%d %H:%M"))
)
conn.commit()
conn.close()
pdf_path = save_to_pdf(state["product"], state["strategy"], state["marketing"])
state["pdf_path"] = pdf_path
return state
# =========================================================
# 6. LANGGRAPH PIPELINE
# =========================================================
graph = StateGraph(VendIQState)
graph.add_node("context", context_node)
graph.add_node("strategy", strategy_node)
graph.add_node("marketing", marketing_node)
graph.add_node("profit", profit_node)
graph.add_node("ad", ad_node)
graph.add_node("save", save_node)
graph.set_entry_point("context")
graph.add_edge("context", "strategy")
graph.add_edge("strategy", "marketing")
graph.add_edge("marketing", "profit")
graph.add_edge("profit", "ad")
graph.add_edge("ad", "save")
graph.add_edge("save", END)
vendiq_graph = graph.compile()
# =========================================================
# 7. GRADIO UI
# =========================================================
def vendiq_app(scenario, product):
if not scenario or not product:
return "⚠ Please enter both fields.", None, None, None, None, None
result = vendiq_graph.invoke({"scenario": scenario, "product": product})
return (
result["strategy"],
result["profit"],
result["chart_path"],
result["marketing"],
result["ad_path"],
result.get("pdf_path") # βœ… include PDF download link
)
with gr.Blocks(title="VendIQ – Intelligent Market Assistant") as app:
gr.Markdown("<h1 style='text-align:center;'>VendIQ – Intelligent Market Assistant</h1>")
gr.Markdown("<p style='text-align:center;'>B2B Strategy, Marketing, and Profit Insights with Ambani-style intelligence.</p>")
with gr.Tab("πŸš€ Generate Strategy"):
scenario = gr.Textbox(label="Business Scenario", placeholder="E.g., entering new logistics market")
product = gr.Textbox(label="Product", placeholder="E.g., AI Supply Chain Platform")
btn = gr.Button("Generate Strategy")
strategy_out = gr.Textbox(label="Negotiation Strategy", lines=6)
profit_out = gr.Number(label="Projected Profit ($)")
chart_out = gr.Image(label="Profit Chart")
marketing_out = gr.Textbox(label="7-Day Marketing Plan", lines=6)
ad_out = gr.Image(label="Ad Image")
pdf_out = gr.File(label="πŸ“„ Download Full Report (PDF)") # βœ… Added output
btn.click(
fn=vendiq_app,
inputs=[scenario, product],
outputs=[strategy_out, profit_out, chart_out, marketing_out, ad_out, pdf_out]
)
app.launch()