Spaces:
Paused
Paused
| # 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 | |
| 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) |