Spaces:
Runtime error
Runtime error
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import joblib
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from fastapi import FastAPI, Form, HTTPException, Request
|
| 5 |
+
|
| 6 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 7 |
+
from sklearn.linear_model import SGDClassifier
|
| 8 |
+
from sklearn.pipeline import Pipeline
|
| 9 |
+
from sklearn.exceptions import NotFittedError
|
| 10 |
+
|
| 11 |
+
# --- 1. Basic Setup & Configuration ---
|
| 12 |
+
# Hugging Face provides persistent storage at the root of the project
|
| 13 |
+
USER_MODELS_DIR = "user_models_data"
|
| 14 |
+
os.makedirs(USER_MODELS_DIR, exist_ok=True)
|
| 15 |
+
|
| 16 |
+
app = FastAPI()
|
| 17 |
+
|
| 18 |
+
# --- Label Mapping ---
|
| 19 |
+
label_mapping = {
|
| 20 |
+
'positive_sentiment': 0, 'negative_sentiment': 1,
|
| 21 |
+
'greeting': 2, 'farewell': 3, 'thanks': 4, 'searching_inquiry': 5
|
| 22 |
+
}
|
| 23 |
+
reverse_label_mapping = {v: k for k, v in label_mapping.items()}
|
| 24 |
+
|
| 25 |
+
# --- 2. Helper Functions ---
|
| 26 |
+
def get_user_paths(user_id: str):
|
| 27 |
+
user_dir = os.path.join(USER_MODELS_DIR, user_id)
|
| 28 |
+
os.makedirs(user_dir, exist_ok=True)
|
| 29 |
+
return {
|
| 30 |
+
"model_path": os.path.join(user_dir, "model.joblib"),
|
| 31 |
+
"data_path": os.path.join(user_dir, "training_data.csv")
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
# --- 3. API Endpoints ---
|
| 35 |
+
@app.get("/")
|
| 36 |
+
def read_root():
|
| 37 |
+
return {"message": "Welcome! Your AI is running on Hugging Face Spaces."}
|
| 38 |
+
|
| 39 |
+
@app.post("/predict/")
|
| 40 |
+
async def predict(user_id: str = Form(...), text: str = Form(...)):
|
| 41 |
+
paths = get_user_paths(user_id)
|
| 42 |
+
if not os.path.exists(paths["model_path"]):
|
| 43 |
+
raise HTTPException(status_code=404, detail="Model not found. Please train it first.")
|
| 44 |
+
model_pipeline = joblib.load(paths["model_path"])
|
| 45 |
+
try:
|
| 46 |
+
predicted_index = model_pipeline.predict([text])[0]
|
| 47 |
+
probabilities = model_pipeline.predict_proba([text])[0]
|
| 48 |
+
predicted_label = reverse_label_mapping[predicted_index]
|
| 49 |
+
confidence = float(probabilities[predicted_index])
|
| 50 |
+
return {"intent": predicted_label, "confidence": confidence}
|
| 51 |
+
except Exception as e:
|
| 52 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 53 |
+
|
| 54 |
+
@app.post("/train/")
|
| 55 |
+
async def train(user_id: str = Form(...), text: str = Form(...), label: str = Form(...)):
|
| 56 |
+
if label not in label_mapping:
|
| 57 |
+
raise HTTPException(status_code=400, detail="Invalid label.")
|
| 58 |
+
paths = get_user_paths(user_id)
|
| 59 |
+
new_data = pd.DataFrame([{"text": text, "label": label}])
|
| 60 |
+
if os.path.exists(paths["data_path"]):
|
| 61 |
+
new_data.to_csv(paths["data_path"], mode='a', header=False, index=False)
|
| 62 |
+
else:
|
| 63 |
+
new_data.to_csv(paths["data_path"], mode='w', header=True, index=False)
|
| 64 |
+
df = pd.read_csv(paths["data_path"])
|
| 65 |
+
if len(df['label'].unique()) < 2:
|
| 66 |
+
return {"message": "Model not trained. Please provide at least two different categories of examples."}
|
| 67 |
+
df['label_numeric'] = df['label'].map(label_mapping)
|
| 68 |
+
X = df['text']
|
| 69 |
+
y = df['label_numeric']
|
| 70 |
+
model_pipeline = Pipeline([
|
| 71 |
+
('tfidf', TfidfVectorizer()),
|
| 72 |
+
('clf', SGDClassifier(loss='modified_huber', random_state=42)),
|
| 73 |
+
])
|
| 74 |
+
model_pipeline.fit(X, y)
|
| 75 |
+
joblib.dump(model_pipeline, paths["model_path"])
|
| 76 |
+
return {"message": f"Training successful for user '{user_id}'."}
|