Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, jsonify
|
| 2 |
+
import joblib
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
app = Flask(__name__)
|
| 6 |
+
|
| 7 |
+
# Load Model & Vectorizer
|
| 8 |
+
lr = joblib.load(open('tag_predictor_lr.pkl','rb'))
|
| 9 |
+
mlb_classes = joblib.load(open('mlb_classes.pkl','rb'))
|
| 10 |
+
tfidf = joblib.load(open('tfidf_vectorizer.pkl','rb'))
|
| 11 |
+
|
| 12 |
+
def preprocess_text(text):
|
| 13 |
+
text = text.lower()
|
| 14 |
+
text = re.sub(r'[^a-zA-Z\s]', '', text)
|
| 15 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 16 |
+
return text
|
| 17 |
+
|
| 18 |
+
def predict_tags(text, model=lr, threshold=0.1):
|
| 19 |
+
clean_text = preprocess_text(text)
|
| 20 |
+
text_tfidf = tfidf.transform([clean_text])
|
| 21 |
+
|
| 22 |
+
if hasattr(model, 'predict_proba'):
|
| 23 |
+
probas = model.predict_proba(text_tfidf)
|
| 24 |
+
tags = []
|
| 25 |
+
p = []
|
| 26 |
+
for i, class_name in enumerate(mlb_classes):
|
| 27 |
+
if probas[i][0][1] > threshold:
|
| 28 |
+
tags.append(class_name)
|
| 29 |
+
p.append(probas[i][0][1])
|
| 30 |
+
return tags, p
|
| 31 |
+
else:
|
| 32 |
+
preds = model.predict(text_tfidf)
|
| 33 |
+
tags = [mlb_classes[i] for i, val in enumerate(preds[0]) if val == 1]
|
| 34 |
+
return tags, preds[0]
|
| 35 |
+
|
| 36 |
+
@app.route('/')
|
| 37 |
+
def index():
|
| 38 |
+
return render_template('index.html')
|
| 39 |
+
|
| 40 |
+
@app.route('/predict', methods=['POST'])
|
| 41 |
+
def predict():
|
| 42 |
+
query = request.form.get("query")
|
| 43 |
+
tags, probabilities = predict_tags(query)
|
| 44 |
+
return jsonify({"tags": tags, "probabilities": probabilities})
|
| 45 |
+
|
| 46 |
+
if __name__ == '__main__':
|
| 47 |
+
app.run(debug=True)
|