AI_Promotion / app.py
PebllaRyan's picture
Update app.py
0eac169 verified
Raw History Blame Contribute Delete
8.1 kB
# app.py
import os
import gradio as gr
import torch
import csv
from datetime import datetime
from huggingface_hub import HfApi
from openai import OpenAI
from langchain.vectorstores import FAISS
from langchain_huggingface import HuggingFaceEmbeddings
# === 1. 初始化 API 和模型 ===
client = OpenAI(
api_key=os.getenv("DEEPSEEK_KEY"),
base_url="https://api.deepseek.com/v1"
)
device = "cuda" if torch.cuda.is_available() else "cpu"
embeddings = HuggingFaceEmbeddings(
model_name="shibing624/text2vec-base-chinese",
model_kwargs={"device": device}
)
# 加载本地 FAISS 向量库
vectorstore = FAISS.load_local("promotion_faiss_index", embeddings, allow_dangerous_deserialization=True)
# === 2. 构建 Prompt ===
def build_prompt(query, docs):
context_blocks = []
for i, doc in enumerate(docs, start=1):
meta = doc.metadata
context_blocks.append(
f"[文档 {i}]\n"
f"{doc.page_content}\n"
f"门店类型: {meta.get('store_type')}, 地点: {meta.get('location')}, "
f"活动类型: {meta.get('promotion_type')}, 销售增长: {meta.get('sales_growth')}%\n"
)
context_text = "\n".join(context_blocks)
supported_promos = """你可使用的促销类型包括(仅限以下这些):
1. 吸引新用户(Attract New Members):
- 注册优惠券(Sign Up Coupons)
- 首单优惠(First Order Promo)
2. 提高客单价(Increase Average Order Value):
- 满X送Y(Buy X Get Y Free)
- 买1打折(Buy 1 Get 1 Discount)
- 买X得积分(Buy X Get Bonus Points)
- 订单满减(Order Discounts)
- 下单送礼(Free Gifts)
3. 提升复购率(Improve Customer Repurchase Rates):
- 满X次送券(Buy X Get Coupon)
- 下单送下次券(Coupons for Next Order)
- 填问卷得券(Survey Rewards)
- 连续购买奖励(Continuous Purchase Rewards)
- 使用优惠码(Promo Code)
"""
return f"""你是一位餐饮行业的促销策划顾问,擅长根据实际可执行的促销方式,结合门店类型、地理位置、问题目标等,为用户提供具有针对性的促销策略。
请注意以下要求:
【用户需求】
用户提出的问题如下:
{query}
【历史促销案例参考】
以下是与该问题相关的历史促销案例,你可以从中借鉴策略或效果数据:
{context_text}
【可使用的促销工具】
{supported_promos}
【你的任务】
请结合用户需求和历史案例,从“可使用的促销工具”中选择最合适的 1~3 种促销方式进行组合推荐,并使用 Markdown 格式输出以下内容(结构清晰、便于阅读):
### 🎯 推荐促销组合
1. **促销方式名称**(如:注册优惠券)
- 类型分类:吸引新用户 / 提高客单价 / 提升复购率
2. **促销方式名称**
- 类型分类:...
### 🔗 策略组合逻辑
- 为什么选择这些促销方式?
- 它们之间如何形成协同效应?
### 📈 预期效果
- 例如:提高转化率、提升客单价、增强复购频次等
- 尽可能结合历史案例效果进行合理预估
### 💡 示例说明
请结合具体门店类型和地点,用“示例”形式说明组合如何实际操作。例如:
> 某咖啡馆在下午时段推出“买一送一 + 注册即送券”策略,成功提升闲时人流...
⚠️ 重要提示:
- 只能使用提供的促销工具列表,不要发明新的促销方式
- 保持语言简洁、条理清晰,避免冗长描述
"""
# === 3. 调用 DeepSeek 模型 ===
def ask_promotion_ai(query):
results = vectorstore.similarity_search(query, k=3)
prompt = build_prompt(query, results)
messages = [
{"role": "system", "content": "你是一位餐饮营销专家"},
{"role": "user", "content": prompt}
]
try:
response = client.chat.completions.create(
model="deepseek-reasoner",
messages=messages,
stream=False
)
return response.choices[0].message.content
except Exception as e:
return f"❗ 调用 DeepSeek 失败:{str(e)}"
# === 4. 格式化输入 ===
def format_query(store_name, store_type, location, budget, problem):
parts = [
f"店家名称:{store_name}",
f"餐馆类型:{store_type}",
f"地理位置:{location}",
f"问题或目标:{problem}"
]
if budget.strip():
parts.insert(3, f"促销预算:{budget}")
return "\n".join(parts)
# === 5. 记录用户反馈 ===
def record_feedback(user_query, final_answer, feedback_choice, improved_answer):
with open("feedback.csv", "a", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
answer_used = final_answer if feedback_choice == "好" else improved_answer
writer.writerow([current_time, user_query, feedback_choice, answer_used])
hf_token = os.getenv("HF_TOKEN", None)
if not hf_token:
return "⚠️ 未设置 HF_TOKEN,无法同步到 Hugging Face Datasets"
try:
api = HfApi()
api.upload_file(
path_or_fileobj="feedback.csv",
path_in_repo="feedback.csv",
repo_id="PebllaRyan/Feedbacks",
repo_type="dataset",
token=hf_token,
commit_message="更新用户反馈"
)
return "✅ 反馈已保存,并同步到 Hugging Face Datasets"
except Exception as e:
return f"⚠️ 本地已保存,但上传失败:{str(e)}"
# === 6. 构建 Gradio 界面 ===
with gr.Blocks(css="""
body { font-family: 'Helvetica Neue', sans-serif; background: #f9f9fb; }
.gradio-container { max-width: 800px; margin: auto; padding: 2em 2em; border-radius: 12px; background: white; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05); }
h1, h2, h3 { color: #2c2c2c; }
.gr-button { background-color: #3b82f6 !important; color: white !important; border-radius: 8px; }
.gr-button:hover { background-color: #2563eb !important; }
textarea, input { border-radius: 6px !important; }
.gr-textbox { margin-bottom: 10px !important; }
label { font-weight: 600; margin-bottom: 4px; display: inline-block; color: #4b5563; }
""") as demo:
gr.Markdown("## 🧠 AI促销推荐助手")
gr.Markdown("填写信息后,我们将根据历史促销案例为你生成专属策略建议。")
with gr.Group():
with gr.Row():
store_name = gr.Textbox(label="🏷️ 店家名称", placeholder="例如:小王烧烤")
store_type = gr.Textbox(label="🍽️ 餐馆类型", placeholder="例如:中式快餐 / 咖啡馆")
with gr.Row():
location = gr.Textbox(label="📍 地理位置", placeholder="例如:北京市朝阳区")
budget = gr.Textbox(label="💰 促销预算(选填)", placeholder="例如:500元以内,可留空")
problem = gr.Textbox(label="❓ 当前问题或目标", placeholder="例如:下午人流少,希望提高堂食销量", lines=3)
submit_btn = gr.Button("🚀 提交问题")
ai_answer = gr.Textbox(label="📋 AI 回答", lines=10)
submit_btn.click(
fn=lambda sn, st, loc, bud, prob: ask_promotion_ai(
format_query(sn, st, loc, bud, prob)
),
inputs=[store_name, store_type, location, budget, problem],
outputs=[ai_answer]
)
gr.Markdown("---")
gr.Markdown("### 🙏 你对这次 AI 回答满意吗?")
with gr.Group():
feedback_choice = gr.Radio(["好", "不好"], label="你的评价")
improved_answer = gr.Textbox(label="💡 如果不满意,你觉得更好的答案是?", lines=3)
feedback_btn = gr.Button("📩 提交反馈")
feedback_output = gr.Markdown()
feedback_btn.click(
fn=record_feedback,
inputs=[problem, ai_answer, feedback_choice, improved_answer],
outputs=[feedback_output]
)
# 启动 Gradio app
demo.launch()