vatcharb's picture
Upload app.py
45a2dd5 verified
Raw
History Blame Contribute Delete
14.7 kB
# -*- coding: utf-8 -*-
"""Present2_MySpa_Chatbot_Sentiment_Prj.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/18_uakb-N3cZ-f4RFLnQYQv7m4I35NuIt
"""
#!pip -q install groq
#!pip install gradio
#!pip install openpyxl
#!pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
#!pip install google-colab
#=========VSCode=====================================================================
# from dotenv import find_dotenv, load_dotenv
# _ = load_dotenv(find_dotenv())
# import os
# secret_key = os.environ.get("GROQ_API_kEY")
#========google.colab======================================================================
#from google.colab import userdata
#secret_key = userdata.get('GROQ_API_kEY')
import os
secret_key = os.environ.get("GROQ_API_kEY") # Set this in Hugging Face Secrets
from groq import Groq
clientGroq = Groq(
api_key= secret_key,
)
def is_thai(text):
"""Check if the text contains any Thai character"""
return any('\u0E00' <= ch <= '\u0E7F' for ch in text)
#from google.colab import drive
#drive.mount('/content/drive')
import pandas as pd
df = pd.read_excel("spa_services_withkeywords.xlsx")
#df = pd.read_excel("/content/drive/MyDrive/SpaProject/spa_services_withkeywords.xlsx")
df.head()
def get_completion(prompt, model= "llama3-70b-8192", clientGroq = clientGroq):
messages = [{"role": "user", "content": prompt}]
response = clientGroq.chat.completions.create(
model=model,
messages=messages,
temperature=0,
max_tokens= 4000,
top_p = 0.5
)
return response.choices[0].message.content
def get_spa_recommendation(user_input):
user_input_lower = user_input.lower()
matched_rows = []
for _, row in df.iterrows():
eng_keywords = [kw.strip().lower() for kw in str(row["Keywords"]).split(",")]
thai_keywords = [kw.strip().lower() for kw in str(row["Keywords (Thai)"]).split(",")]
all_keywords = eng_keywords + thai_keywords
# Count how many keywords appear in user input
match_count = sum(1 for kw in all_keywords if kw in user_input_lower)
if match_count > 0:
matched_rows.append({
"row": row,
"match_count": match_count,
"price": row["Price"]
})
if not matched_rows:
return "❌ ไม่พบบริการที่ตรงกับคำอธิบายของคุณ" if is_thai(user_input) else "❌ No matching service found for your request."
# Sort by match count first, then by price
sorted_matches = sorted(matched_rows, key=lambda x: (x["match_count"], x["price"]), reverse=True)
top_row = sorted_matches[0]["row"]
# ดึงชื่อแพ็กเกจจาก Excel ตรง ๆ
service_name = top_row['Service']
duration = top_row['Duration']
price = top_row['Price']
if is_thai(user_input):
prompt = f"""
คุณคือผู้ช่วยแนะนำบริการสปาผู้หญิง ก่อนแนะนำบริการ ให้ทักทายลูกค้าก่อนว่า สวัสดีค่ะคุณลูกค้าที่รัก MySpa ยินดีให้บริการก่อนค่อยให้คำแนะนำจากอาการหรือความรู้สึกของลูกค้า
ลูกค้า: {user_input}
คุณ: กรุณาแนะนำบริการสปาที่เหมาะสมให้เลือกจากรายการที่ Mapping จาก Keyword ได้โดย Keyword ที่ได้มีดังนี้ ชื่อแพ็คเกจ จาก {service_name} ระยะเวลา จาก {duration} และราคาเบื้องต้น {price}
พร้อมอธิบายผลลัพธ์ที่ได้จากแพ็คเกจที่แนะนำ
แสดงผลลัพธ์เป็นภาษาไทย ชื่อแพ็คเกจ จาก {service_name} ให้เด่น มีสีสรรนิด และก่อนการนำเสนอให้ทักทายลูกค้า แสดงผลลัพธ์ทั้งหมดใน Format ของ Markdown
"""
else:
prompt = f"""
You are a spa assistant. Before recommending a services ,first greeting the customer with Hello dear customer, MySpa is happy to server you then provide suggestions based on the customer's symptoms or feeling.
Customer input: {user_input}
Please recommend **only one** service using the information and format below :
- Service: {service_name}
- Duration: {duration}
- Price: {price} THB
Also, explain the benefits or outcomes of the recommended package.
Display the results in Eng language, new line for highlight the package name from {service_name} to make it stand out.
Before presenting, greet the customer again. Display all the results in the Markdown format.
"""
return get_completion(prompt)
import gradio as gr
def spa_bot_interface(text):
return get_spa_recommendation(text)
#gr.Interface(
# fn=spa_bot_interface,
# inputs=gr.Textbox(label="กรุณาพิมพ์อาการของคุณ / Your symptom"),
# # Use gr.Textbox as the output component with a label
# outputs=gr.Textbox(label="คำแนะนำจาก BHU MHAI SPA / Suggestion from BHU MHAI SPA"),
# title="BHU MHAI Spa",
# description="พิมพ์อาการของคุณ ทางร้านจะแนะนำบริการสปาที่เหมาะสม"
#).launch(debug=False,share=True)
# prompt: # prompt: We need procedure involve with input feedback from customer and report sentiment feeling about feedback positive , negative or neutral and save result of all feedback and sentiment into excel file name result_spa_sentiment.xls by saving file into google drive in path /content/drive/MyDrive/SpaProject if can not file that create file and we need interface by using gradio and make this part into function for calling
#from google.colab import drive
import os
# Mount Google Drive
#drive.mount('/content/drive')
def analyze_sentiment(text):
"""Analyzes the sentiment of the input text using the Groq API."""
prompt = f"""
Analyze the sentiment of the following customer feedback. Classify the sentiment as 'positive', 'negative', or 'neutral'.
Only respond with the sentiment classification. Do not include any other text.
Customer Feedback: "{text}"
Sentiment:
"""
sentiment = get_completion(prompt)
return sentiment.strip().lower()
def process_feedback_and_save(feedback):
"""Processes customer feedback, analyzes sentiment, and saves to an Excel file."""
sentiment = analyze_sentiment(feedback)
# Define the path to the Excel file
#excel_file_path = '/content/drive/MyDrive/SpaProject/result_spa_sentiment.xlsx'
#excel_file_path = 'result_spa_sentiment.xlsx'
# Check if the directory exists, create it if not
#if not os.path.exists('/content/drive/MyDrive/SpaProject'):
# os.makedirs('/content/drive/MyDrive/SpaProject')
if not os.path.exists('output'):
os.makedirs('output')
excel_file_path = 'result_spa_sentiment.xlsx'
# Load existing data or create a new DataFrame
try:
df_sentiment = pd.read_excel(excel_file_path)
except FileNotFoundError:
df_sentiment = pd.DataFrame(columns=['Feedback', 'Sentiment'])
# Append the new feedback and sentiment
new_row = pd.DataFrame({'Feedback': [feedback], 'Sentiment': [sentiment]})
df_sentiment = pd.concat([df_sentiment, new_row], ignore_index=True)
# Save the updated DataFrame to Excel
df_sentiment.to_excel(excel_file_path, index=False)
return f"Feedback received: '{feedback}'\nSentiment: {sentiment}\nSaved to: {excel_file_path}"
def feedback_interface(feedback):
"""Gradio interface function to process and save feedback."""
return process_feedback_and_save(feedback)
# Add a new Gradio interface for feedback
#gr.Interface(
# fn=feedback_interface,
# inputs=gr.Textbox(label="Enter your feedback"),
# outputs=gr.Textbox(label="Feedback Analysis Result"),
# title="Customer Feedback Sentiment Analysis",
# description="Enter your feedback to get sentiment analysis and save it."
#).launch(debug=False, share=True)
#from googletrans import Translator
# ✅ STEP 1: ฟังก์ชันสรุปเนื้อหา (เหมาะสำหรับบทความสุขภาพ)
def summarize_text(text):
prompt = f"สรุปเนื้อหาต่อไปนี้ให้กระชับแต่ครบถ้วน:\n\n{text} พร้อมปรับรูปแบบให้สวยงามใส่ Markdown"
return get_completion(prompt)
#return response['choices'][0]['message']['content']
# ✅ STEP 2: ฟังก์ชันสร้างโพสต์โปรโมชัน
def generate_spa_promo(topic):
prompt = f"""
คุณเป็นนักการตลาดสายสุขภาพที่เชี่ยวชาญด้านสปา
เขียนโพสต์ Facebook โปรโมชันของร้าน MySpa Shop เป็นภาษาไทยเกี่ยวกับหัวข้อ "{topic}"
โพสต์ควรมี:
- คำโปรยเปิดโพสต์
- เนื้อหาเชิญชวน
- ใช้อีโมจิประกอบให้โพสต์ดูน่าสนใจ (เช่น 💆‍♀️✨🎉🌿)
- ปิดท้ายด้วยแฮชแท็กที่เกี่ยวข้อง
เขียนให้เหมาะกับ Facebook หรือ Line OA โดยใช้ภาษาที่เป็นกันเอง สไตล์มืออาชีพ พร้อมปรับรูปแบบให้สวยงามใส่ Markdown
"""
return summarize_text(get_completion(prompt))
#return response['choices'][0]['message']['content']
def load_readme():
# Define the path to the README file in your Google Drive
#readme_file_path = "/content/drive/MyDrive/SpaProject/Readme_Myspa_Chatbot.md"
readme_file_path = "Readme_Myspa_Chatbot.md"
try:
with open(readme_file_path, "r", encoding="utf-8") as f:
return f.read()
except FileNotFoundError:
# Handle the case where the file is not found
print(f"Error: The file {readme_file_path} was not found.")
return "Error loading README file. Please ensure 'Readme_Myspa_Chatbot.md' is in '/content/drive/MyDrive/SpaProject'."
import gradio as gr
# 🧠 ฟังก์ชันหลัก
#def spa_bot_interface(symptom):
# # ตัวอย่าง: ปรับเป็นระบบจริงได้
# return f"จากอาการ '{symptom}', แนะนำบริการ: Thai Massage 60 mins"
#def feedback_interface(feedback):
# ตัวอย่าง: วิเคราะห์ความเห็น
# return f"ขอบคุณสำหรับความคิดเห็น: '{feedback}' (วิเคราะห์ว่า: Positive)"
# 🌐 Gradio Web UI (Single Page)
with gr.Blocks(title="MySpa Chatbot") as demo:
gr.Markdown("## 🌸 MySpa Chatbot\nให้คำแนะนำและรับความคิดเห็นจากลูกค้า")
with gr.Tab("📄 README"):
gr.Markdown("## 📘 Project Documentation\nHere’s an overview of the MySpa AI Chatbot Project:")
gr.Markdown(load_readme())
with gr.Tab("💆 Spa Recommend"):
gr.Markdown("### พิมพ์อาการของคุณ เพื่อรับบริการที่เหมาะสม")
with gr.Row():
symptom_input = gr.Textbox(label="อาการของคุณ / Your Symptom", placeholder="เช่น ปวดหลัง เครียด...")
recommend_output = gr.Textbox(label="คำแนะนำจาก MySpa SPA", interactive=False)
spa_btn = gr.Button("🎯 แนะนำบริการ")
spa_btn.click(fn=spa_bot_interface, inputs=symptom_input, outputs=recommend_output)
with gr.Tab("🗣️ Customer Feedback"):
gr.Markdown("### แสดงความคิดเห็นเกี่ยวกับบริการของเรา")
with gr.Row():
feedback_input = gr.Textbox(label="ความคิดเห็นของคุณ / Your Feedback", placeholder="ใส่ความรู้สึก หรือคำแนะนำ...")
feedback_output = gr.Textbox(label="ผลการวิเคราะห์ความคิดเห็น", interactive=False)
fb_btn = gr.Button("📊 วิเคราะห์ความคิดเห็น")
fb_btn.click(fn=feedback_interface, inputs=feedback_input, outputs=feedback_output)
with gr.Tab("✨ AI Post Generator"): # Renamed tab for clarity
gr.Markdown("### ให้ AI ช่วยสร้างโพสต์โปรโมชันหรือเนื้อหา")
with gr.Row():
# Add an input textbox for the user to enter the topic
#post_topic_input = gr.Textbox(label="หัวข้อสำหรับโพสต์ / Topic for Post", placeholder="เช่น โปรโมชั่นลดราคา สปาหน้าใส...")
post_topic_input = gr.Dropdown(label="เลือกหัวข้อสำหรับโพสต์ / Choose a topic for the post", choices=["แนะนำบริการใหม่", "โปรโมชั่นเดือนนี้", "บทความสุขภาพทั่วไป"])
post_output = gr.Textbox(label="โพสต์ที่สร้างโดย AI", interactive=False)
post_btn = gr.Button("📝 สร้างโพสต์") # Renamed button for clarity
# Link the button click to the generate_spa_promo function, using the textbox as input
post_btn.click(fn=generate_spa_promo, inputs = post_topic_input, outputs=post_output)
# 🚀 เรียกหน้าเว็บ
#demo.launch(share=True)
demo.launch()