Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,79 +4,94 @@ import numpy as np
|
|
| 4 |
import pymysql
|
| 5 |
import gradio as gr
|
| 6 |
|
| 7 |
-
#
|
| 8 |
MODEL_PATH = "model.joblib"
|
| 9 |
if not os.path.exists(MODEL_PATH):
|
| 10 |
raise FileNotFoundError("model.joblib not found. Ensure it is uploaded to the root directory.")
|
| 11 |
|
| 12 |
pipeline = joblib.load(MODEL_PATH)
|
| 13 |
|
| 14 |
-
|
| 15 |
-
def log_prediction_to_mysql(raw_text: str, prediction: str, confidence: float):
|
| 16 |
db_host = os.getenv("DB_HOST")
|
| 17 |
if not db_host:
|
| 18 |
-
return "
|
| 19 |
|
| 20 |
try:
|
|
|
|
|
|
|
|
|
|
| 21 |
connection = pymysql.connect(
|
| 22 |
host=db_host,
|
| 23 |
user=os.getenv("DB_USER"),
|
| 24 |
password=os.getenv("DB_PASSWORD"),
|
| 25 |
database=os.getenv("DB_NAME"),
|
| 26 |
port=int(os.getenv("DB_PORT", 3306)),
|
|
|
|
| 27 |
autocommit=True,
|
| 28 |
connect_timeout=5
|
| 29 |
)
|
| 30 |
-
|
| 31 |
with connection.cursor() as cursor:
|
| 32 |
sql = "INSERT INTO predictions (input_text, predicted_intent, confidence) VALUES (%s, %s, %s)"
|
| 33 |
-
cursor.execute(sql, (raw_text,
|
| 34 |
-
|
| 35 |
connection.close()
|
| 36 |
-
return "Successfully logged prediction to
|
| 37 |
except Exception as e:
|
| 38 |
return f"MySQL Logging Error: {str(e)}"
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
return {}, "Please provide a valid input text."
|
| 44 |
|
| 45 |
-
cleaned_text =
|
| 46 |
-
|
| 47 |
-
#
|
| 48 |
-
|
| 49 |
classes = pipeline.classes_
|
| 50 |
-
|
| 51 |
-
#
|
| 52 |
-
conf_dict = {str(cls): float(prob) for cls, prob in zip(classes,
|
| 53 |
-
|
| 54 |
-
# Identify
|
| 55 |
-
top_idx = np.argmax(
|
| 56 |
predicted_intent = str(classes[top_idx])
|
| 57 |
-
top_confidence = float(
|
| 58 |
-
|
| 59 |
-
#
|
| 60 |
-
db_status =
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
demo = gr.Interface(
|
| 67 |
fn=predict_intent,
|
| 68 |
-
inputs=gr.Textbox(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
outputs=[
|
| 70 |
-
gr.Label(num_top_classes=3, label="
|
| 71 |
-
gr.Textbox(label="
|
| 72 |
],
|
| 73 |
-
title="
|
| 74 |
-
description="
|
| 75 |
examples=[
|
| 76 |
-
["Where is my order package?"],
|
| 77 |
-
["I want to cancel my active
|
| 78 |
-
["
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
)
|
| 81 |
|
| 82 |
if __name__ == "__main__":
|
|
|
|
| 4 |
import pymysql
|
| 5 |
import gradio as gr
|
| 6 |
|
| 7 |
+
# Load trained Scikit-Learn pipeline
|
| 8 |
MODEL_PATH = "model.joblib"
|
| 9 |
if not os.path.exists(MODEL_PATH):
|
| 10 |
raise FileNotFoundError("model.joblib not found. Ensure it is uploaded to the root directory.")
|
| 11 |
|
| 12 |
pipeline = joblib.load(MODEL_PATH)
|
| 13 |
|
| 14 |
+
def log_to_mysql(raw_text: str, predicted_intent: str, confidence: float) -> str:
|
|
|
|
| 15 |
db_host = os.getenv("DB_HOST")
|
| 16 |
if not db_host:
|
| 17 |
+
return "DB_HOST secret not found. Skipping MySQL log."
|
| 18 |
|
| 19 |
try:
|
| 20 |
+
use_ssl = os.getenv("USE_SSL", "false").lower() == "true"
|
| 21 |
+
ssl_config = {"ssl": True} if use_ssl else None
|
| 22 |
+
|
| 23 |
connection = pymysql.connect(
|
| 24 |
host=db_host,
|
| 25 |
user=os.getenv("DB_USER"),
|
| 26 |
password=os.getenv("DB_PASSWORD"),
|
| 27 |
database=os.getenv("DB_NAME"),
|
| 28 |
port=int(os.getenv("DB_PORT", 3306)),
|
| 29 |
+
ssl=ssl_config,
|
| 30 |
autocommit=True,
|
| 31 |
connect_timeout=5
|
| 32 |
)
|
| 33 |
+
|
| 34 |
with connection.cursor() as cursor:
|
| 35 |
sql = "INSERT INTO predictions (input_text, predicted_intent, confidence) VALUES (%s, %s, %s)"
|
| 36 |
+
cursor.execute(sql, (raw_text, predicted_intent, confidence))
|
| 37 |
+
|
| 38 |
connection.close()
|
| 39 |
+
return "Successfully logged prediction to MySQL."
|
| 40 |
except Exception as e:
|
| 41 |
return f"MySQL Logging Error: {str(e)}"
|
| 42 |
|
| 43 |
+
def predict_intent(user_text: str):
|
| 44 |
+
if not user_text or not user_text.strip():
|
| 45 |
+
return {}, "Input text cannot be empty."
|
|
|
|
| 46 |
|
| 47 |
+
cleaned_text = user_text.strip().lower()
|
| 48 |
+
|
| 49 |
+
# Perform Inference
|
| 50 |
+
probs = pipeline.predict_proba([cleaned_text])[0]
|
| 51 |
classes = pipeline.classes_
|
| 52 |
+
|
| 53 |
+
# Format Class Probabilities
|
| 54 |
+
conf_dict = {str(cls): float(prob) for cls, prob in zip(classes, probs)}
|
| 55 |
+
|
| 56 |
+
# Identify Top Class
|
| 57 |
+
top_idx = int(np.argmax(probs))
|
| 58 |
predicted_intent = str(classes[top_idx])
|
| 59 |
+
top_confidence = float(probs[top_idx])
|
| 60 |
+
|
| 61 |
+
# Persist log to MySQL
|
| 62 |
+
db_status = log_to_mysql(user_text, predicted_intent, top_confidence)
|
| 63 |
+
|
| 64 |
+
status_report = (
|
| 65 |
+
f"Predicted Intent: {predicted_intent}\n"
|
| 66 |
+
f"Confidence Score: {top_confidence:.2%}\n"
|
| 67 |
+
f"Database Status: {db_status}"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
return conf_dict, status_report
|
| 71 |
+
|
| 72 |
+
# Gradio Interface Component Setup
|
| 73 |
demo = gr.Interface(
|
| 74 |
fn=predict_intent,
|
| 75 |
+
inputs=gr.Textbox(
|
| 76 |
+
lines=3,
|
| 77 |
+
placeholder="Enter customer query (e.g., 'Where is my order parcel?')...",
|
| 78 |
+
label="Customer Inquiry Input"
|
| 79 |
+
),
|
| 80 |
outputs=[
|
| 81 |
+
gr.Label(num_top_classes=3, label="Intent Probabilities"),
|
| 82 |
+
gr.Textbox(label="Evaluation & DB Logging Log", interactive=False)
|
| 83 |
],
|
| 84 |
+
title="E-Commerce Intent Classification Engine",
|
| 85 |
+
description="Real-time intent classification running on Hugging Face Spaces (CPU Basic). Predictions log dynamically to MySQL for Power BI dashboards.",
|
| 86 |
examples=[
|
| 87 |
+
["Where is my order package? Order #48291"],
|
| 88 |
+
["I want to cancel my active order"],
|
| 89 |
+
["How do I return an item and get a refund?"],
|
| 90 |
+
["My card was charged twice for one transaction"],
|
| 91 |
+
["Is this shirt available in size Medium?"],
|
| 92 |
+
["Connect me to a human support agent"]
|
| 93 |
+
],
|
| 94 |
+
theme="soft"
|
| 95 |
)
|
| 96 |
|
| 97 |
if __name__ == "__main__":
|