Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
International Trade Flow Predictor - Full Application for Hugging Face Spaces
|
3 |
+
"""
|
4 |
+
from flask import Flask, render_template, request, jsonify
|
5 |
+
import os
|
6 |
+
import json
|
7 |
+
import requests
|
8 |
+
import pandas as pd
|
9 |
+
import numpy as np
|
10 |
+
import time
|
11 |
+
from dotenv import load_dotenv
|
12 |
+
import sys
|
13 |
+
import logging
|
14 |
+
|
15 |
+
# Configure logging
|
16 |
+
logging.basicConfig(level=logging.INFO)
|
17 |
+
logger = logging.getLogger(__name__)
|
18 |
+
|
19 |
+
# Load environment variables from .env file if it exists
|
20 |
+
load_dotenv()
|
21 |
+
|
22 |
+
# Log environment for debugging
|
23 |
+
logger.info(f"Environment variables: HUGGINGFACE_API_TOKEN exists: {'HUGGINGFACE_API_TOKEN' in os.environ}")
|
24 |
+
logger.info(f"Python version: {sys.version}")
|
25 |
+
logger.info(f"Working directory: {os.getcwd()}")
|
26 |
+
logger.info(f"Directory contents: {os.listdir('.')}")
|
27 |
+
|
28 |
+
# Initialize Flask app
|
29 |
+
app = Flask(__name__)
|
30 |
+
|
31 |
+
# Import the llm_assistant module
|
32 |
+
try:
|
33 |
+
from llm_assistant import TradeAssistant
|
34 |
+
logger.info("Successfully imported TradeAssistant")
|
35 |
+
except Exception as e:
|
36 |
+
logger.error(f"Error importing TradeAssistant: {str(e)}")
|
37 |
+
|
38 |
+
# Create a fallback class if import fails
|
39 |
+
class TradeAssistant:
|
40 |
+
def __init__(self, api_token=None):
|
41 |
+
self.api_token = api_token
|
42 |
+
|
43 |
+
def query(self, user_question, chat_history=None, include_app_context=True):
|
44 |
+
return {
|
45 |
+
"success": False,
|
46 |
+
"response": "The AI assistant is temporarily unavailable. Please check the application logs for details.",
|
47 |
+
"message": "Import error"
|
48 |
+
}
|
49 |
+
|
50 |
+
def format_chat_history(self, chat_history_raw):
|
51 |
+
return []
|
52 |
+
|
53 |
+
def enhance_query_with_context(self, query):
|
54 |
+
return query
|
55 |
+
|
56 |
+
def explain_hs_code(self, code):
|
57 |
+
return {
|
58 |
+
"success": False,
|
59 |
+
"response": "HS code explanation is temporarily unavailable.",
|
60 |
+
"message": "Import error"
|
61 |
+
}
|
62 |
+
|
63 |
+
def get_trade_recommendation(self, country=None, product=None, year=None):
|
64 |
+
return {
|
65 |
+
"success": False,
|
66 |
+
"response": "Trade recommendations are temporarily unavailable.",
|
67 |
+
"message": "Import error"
|
68 |
+
}
|
69 |
+
|
70 |
+
# Initialize the AI Assistant
|
71 |
+
trade_assistant = TradeAssistant(api_token=os.environ.get("HUGGINGFACE_API_TOKEN"))
|
72 |
+
|
73 |
+
# Import the primary app functionality
|
74 |
+
# This avoids having to duplicate all the code
|
75 |
+
from app import (get_countries, get_product_codes, query_comtrade,
|
76 |
+
clean_comtrade_data, predict_trade, export_data,
|
77 |
+
get_ml_models, train_ml_model, get_cached_data,
|
78 |
+
get_trade_rankings, get_top_trade_partners)
|
79 |
+
|
80 |
+
# Home page
|
81 |
+
@app.route('/')
|
82 |
+
def index():
|
83 |
+
return render_template('index.html')
|
84 |
+
|
85 |
+
# AI Assistant endpoints
|
86 |
+
@app.route('/api/assistant/query', methods=['POST'])
|
87 |
+
def assistant_query():
|
88 |
+
data = request.json
|
89 |
+
|
90 |
+
# Get the user question from request
|
91 |
+
user_question = data.get('question', '')
|
92 |
+
|
93 |
+
# Validate input
|
94 |
+
if not user_question:
|
95 |
+
return jsonify({
|
96 |
+
'success': False,
|
97 |
+
'response': '',
|
98 |
+
'message': 'No question provided'
|
99 |
+
})
|
100 |
+
|
101 |
+
# Get chat history if provided
|
102 |
+
chat_history_raw = data.get('chatHistory', [])
|
103 |
+
|
104 |
+
# Format chat history for the LLM
|
105 |
+
chat_history = trade_assistant.format_chat_history(chat_history_raw)
|
106 |
+
|
107 |
+
# Enhance query with additional context if applicable
|
108 |
+
enhanced_question = trade_assistant.enhance_query_with_context(user_question)
|
109 |
+
|
110 |
+
# Send query to the LLM
|
111 |
+
response = trade_assistant.query(enhanced_question, chat_history)
|
112 |
+
|
113 |
+
# Return the response
|
114 |
+
return jsonify(response)
|
115 |
+
|
116 |
+
# API endpoint for HS code explanation
|
117 |
+
@app.route('/api/assistant/explain-hs-code', methods=['POST'])
|
118 |
+
def explain_hs_code():
|
119 |
+
data = request.json
|
120 |
+
|
121 |
+
# Get the HS code from request
|
122 |
+
hs_code = data.get('code', '')
|
123 |
+
|
124 |
+
# Validate input
|
125 |
+
if not hs_code:
|
126 |
+
return jsonify({
|
127 |
+
'success': False,
|
128 |
+
'response': '',
|
129 |
+
'message': 'No HS code provided'
|
130 |
+
})
|
131 |
+
|
132 |
+
# Send to specific HS code explanation function
|
133 |
+
response = trade_assistant.explain_hs_code(hs_code)
|
134 |
+
|
135 |
+
# Return the response
|
136 |
+
return jsonify(response)
|
137 |
+
|
138 |
+
# API endpoint for trade recommendations
|
139 |
+
@app.route('/api/assistant/get-recommendation', methods=['POST'])
|
140 |
+
def get_recommendation():
|
141 |
+
data = request.json
|
142 |
+
|
143 |
+
# Get parameters
|
144 |
+
country = data.get('country', None)
|
145 |
+
product = data.get('product', None)
|
146 |
+
year = data.get('year', None)
|
147 |
+
|
148 |
+
# At least one parameter should be provided
|
149 |
+
if not country and not product and not year:
|
150 |
+
return jsonify({
|
151 |
+
'success': False,
|
152 |
+
'response': '',
|
153 |
+
'message': 'Please provide at least one parameter (country, product, or year)'
|
154 |
+
})
|
155 |
+
|
156 |
+
# Get recommendation
|
157 |
+
response = trade_assistant.get_trade_recommendation(country, product, year)
|
158 |
+
|
159 |
+
# Return the response
|
160 |
+
return jsonify(response)
|
161 |
+
|
162 |
+
if __name__ == "__main__":
|
163 |
+
# Hugging Face Spaces uses port 7860 by default
|
164 |
+
port = int(os.environ.get("PORT", 7860))
|
165 |
+
app.run(host="0.0.0.0", port=port)
|