File size: 3,151 Bytes
34cc684
 
da017e7
2bd62dd
34cc684
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
78
79
80
81
82
83
84
85
# app.py
from flask import Flask, request, jsonify
from xgboost import XGBRegressor
import pandas as pd
import requests
import os

app = Flask(__name__)

# Load the pre-trained model
model = XGBRegressor()
model.load_model('model.json')

# Fetch data from Facebook API
def fetch_data_from_api(query, geo_locations):
    url = f"https://graph.facebook.com/v17.0/act_597540533213624/targetingsearch"
    params = {
        "q": query,
        "geo_locations[countries]": geo_locations,
        "access_token": os.getenv('ACCESS_TOKEN')
    }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"Failed to fetch data from API. Status code: {response.status_code}")

# Generate synthetic metrics
def generate_synthetic_metrics(data):
    IMPRESSION_RATE = 0.10  # 10% of audience sees the ad
    CTR = 0.05  # 5% of impressions result in clicks
    CONVERSION_RATE = 0.02  # 2% of clicks result in conversions
    CPM = 5  # $5 per 1000 impressions
    REVENUE_PER_CONVERSION = 50  # $50 per conversion

    data['impressions'] = data['audience_size_lower_bound'] * IMPRESSION_RATE
    data['clicks'] = data['impressions'] * CTR
    data['conversions'] = data['clicks'] * CONVERSION_RATE
    data['ad_spend'] = (data['impressions'] / 1000) * CPM
    data['revenue'] = data['conversions'] * REVENUE_PER_CONVERSION
    data['roi'] = (data['revenue'] - data['ad_spend']) / data['ad_spend']

    return data

@app.route('/predict', methods=['GET'])
def predict():
    try:
        # Get user input from query parameters
        query = request.args.get('q', default='Fitness')  # Default query is 'Fitness'
        geo_locations = request.args.get('geo_locations', default='NG')  # Default country is 'NG'

        # Fetch data from Facebook API
        response_data = fetch_data_from_api(query, geo_locations)

        # Extract the list of dictionaries from the "data" key
        if "data" in response_data and isinstance(response_data["data"], list):
            data = pd.DataFrame(response_data["data"])

            # Generate synthetic metrics
            data = generate_synthetic_metrics(data)

            # Use the first row of the data for prediction
            input_data = data.iloc[0][['ad_spend', 'impressions', 'clicks', 'conversions']]

            # Predict ROI
            predicted_roi = model.predict([input_data])

            # Return the prediction
            return jsonify({
                "ad_spend": input_data['ad_spend'],
                "impressions": input_data['impressions'],
                "clicks": input_data['clicks'],
                "conversions": input_data['conversions'],
                "predicted_roi": float(predicted_roi[0]),
                "note": "These are recommendations based on real-world data. Actual results may vary."
            })

        else:
            return jsonify({"error": "The 'data' key is missing or not a list in the API response."}), 400

    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)