Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
77 lines (62 loc) · 2.43 KB
/
Copy pathapp.py
File metadata and controls
77 lines (62 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# app.py
from flask import Flask, request, jsonify
import joblib
import pandas as pd
from textblob import TextBlob
# 1. Initialize the "Waiter" (The App)
app = Flask(__name__)
# 2. Load the "Brains" (Model & Encoder)
print("Loading model and encoder...")
model = joblib.load('like_predictor.pkl')
encoder = joblib.load('company_encoder.pkl')
@app.route('/')
def home():
return "🚀 Like Prediction API is Running!"
@app.route('/predict', methods=['POST'])
def predict():
try:
# A. Get the order (JSON data from user)
data = request.get_json()
# Example Input:
# {
# "content": "I love these shoes!",
# "media": "http://image.com",
# "datetime": "2025-01-01 10:00:00",
# "company": "campus"
# }
# B. Feature Engineering (The Translation Layer)
# We must do EXACTLY what we did in training
content = data.get('content', '')
media = data.get('media', 'no_media')
date_str = data.get('datetime', '2025-01-01 12:00:00')
company = data.get('company', 'Unknown')
# 1. Calculate Text Features
word_count = len(content.split())
char_count = len(content)
sentiment = TextBlob(content).sentiment.polarity
# 2. Calculate Media & Time
has_media = 1 if media != 'no_media' else 0
hour = pd.to_datetime(date_str).hour
# 3. Encode Company
# Handle "Unknown" companies safely (If unknown, default to 0)
try:
company_encoded = encoder.transform([company])[0]
except:
company_encoded = 0 # Default fallback
# C. Prepare the "Tray" for the Model
# MUST be in the exact same order as training:
# ['word_count', 'char_count', 'has_media', 'hour', 'sentiment', 'company_encoded']
features = [[word_count, char_count, has_media, hour, sentiment, company_encoded]]
# D. Ask the Kitchen (Model) for the result
prediction = model.predict(features)[0]
# E. Return the result to the customer
return jsonify({
'success': True,
'predicted_likes': int(prediction),
'sentiment_score': sentiment
})
except Exception as e:
return jsonify({'error': str(e)}), 500
# 3. Open the Restaurant
if __name__ == '__main__':
app.run(port=5000, debug=True)