CoolFace
Apppublic

dev2004v/ai-content-detector

sourceHugging Faceapache-2.0updated 9mo agoView on Hugging Face
0likes
model.py35 linesDownload Raw Back to root
1import joblib2import os3from sklearn.feature_extraction.text import TfidfVectorizer4from sklearn.decomposition import TruncatedSVD5 6# Define relative file paths (assuming 'models/' is in the same directory as this script)7BASE_DIR = os.path.dirname(os.path.abspath(__file__))8MODEL_PATH = os.path.join(BASE_DIR, "models", "random_forest_model.pkl")9VECTORIZER_PATH = os.path.join(BASE_DIR, "models", "vectorizer.pkl")10SVD_PATH = os.path.join(BASE_DIR, "models", "svd.pkl")11 12try:13    # Load the trained model, vectorizer, and SVD transformer14    model = joblib.load(MODEL_PATH)15    vectorizer = joblib.load(VECTORIZER_PATH)16    svd = joblib.load(SVD_PATH)17    print(" Model, vectorizer, and SVD loaded successfully!")18except Exception as e:19    print(f" Error loading model files: {e}")20    exit(1)21 22def predict_text(text: str) -> dict:23    """Preprocess input text and predict using trained model."""24    try:25        X_tfidf = vectorizer.transform([text])  # Convert to TF-IDF26        X_reduced = svd.transform(X_tfidf)  # Apply dimensionality reduction27        prediction = model.predict(X_reduced)[0]  # Predict label (0 or 1)28 29        probability = float(model.predict_proba(X_reduced)[0][1])30        print(probability)  # Printing probability31 32        return {"generated": int(prediction), "probability": probability}33    except Exception as e:34        print(f" Prediction error: {e}")35        return {"generated": -1, "probability": 0.0}