CoolFace
Apppublic

Anwaree/message-classification

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py67 linesDownload Raw Back to root
1# -----------------------------2# app.py pour déploiement Spam Detector3# -----------------------------4import gradio as gr5import joblib6import re7from nltk.corpus import stopwords8from nltk.stem import PorterStemmer9import nltk10nltk.download('stopwords')11 12# -----------------------------13# 1️⃣ Prétraitement d'un message14# -----------------------------15stop_words = set(stopwords.words('english'))16stemmer = PorterStemmer()17 18def preprocess_message(text):19    """Prétraite un message pour qu'il corresponde au format du modèle."""20    if not text:21        return ""22    text = text.lower()23    text = re.sub(r'http\S+|www\S+', '', text)24    text = re.sub(r'\S+@\S+', '', text)25    text = re.sub(r'\+?\d[\d -]{8,}\d', '', text)26    text = re.sub(r'\d+', '', text)27    text = re.sub(r'[^a-z\s!/+>]', '', text)  # garder ponctuation utile pour spam28    words = [stemmer.stem(word) for word in text.split() if word not in stop_words]29    return " ".join(words)30 31# -----------------------------32# 2️⃣ Charger modèle et TF-IDF33# -----------------------------34model = joblib.load("spam_model.pkl")35vectorizer = joblib.load("tfidf_vectorizer.pkl")36 37# -----------------------------38# 3️⃣ Fonction de prédiction39# -----------------------------40def predict_message(message):41    cleaned = preprocess_message(message)42    X = vectorizer.transform([cleaned])43    prediction = model.predict(X)[0]44    probability = model.predict_proba(X)[0][1] if hasattr(model, 'predict_proba') else None45    return {46        "Message": message,47        "Prediction": prediction,48        "Spam Probability": round(float(probability), 4) if probability is not None else None49    }50 51# -----------------------------52# 4️⃣ Interface Gradio53# -----------------------------54iface = gr.Interface(55    fn=predict_message,56    inputs=gr.Textbox(lines=3, placeholder="Entrez votre message..."),57    outputs="json",58    title="📩 Spam Detector",59    description="Entrez un message pour savoir s'il s'agit de spam ou non."60)61 62# -----------------------------63# 5️⃣ Lancer l'application64# -----------------------------65if __name__ == "__main__":66    iface.launch()67