-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
76 lines (66 loc) · 2.32 KB
/
server.py
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
# import main Flask class and request object
from unicodedata import category
from flask import Flask, request
from flask_cors import CORS
from emissions_calculator.usableModel import predict
from emissions_calculator.vocab import text_pipeline
import CategoryMapping
import json
import requests
import os
from dotenv import load_dotenv
import time
app = Flask(__name__)
CORS(app)
@app.route('/')
def start():
return "server running"
@app.route('/get_emissions', methods=['POST'])
def process_json():
processStart = time.time()
content_type = request.headers.get('Content-Type')
if (content_type == 'application/json'):
product = request.get_json()
# check that the product cat was able to be scraped
print(product["Category"] in list(CategoryMapping.AMAZON_TO_API_CATEGORY.keys()))
if product["Category"] != "" and product["Category"] in list(CategoryMapping.AMAZON_TO_API_CATEGORY.keys()):
category = product["Category"]
#if not guess using AI
else:
start = time.time()
category = predict(product["productTitle"], text_pipeline)
end = time.time()
print(end - start)
print(category)
API_cat = CategoryMapping.AMAZON_TO_API_CATEGORY[category]
print(API_cat)
load_dotenv()
MY_API_KEY = os.getenv('CLIMATE_KEY')
URL = 'https://beta3.api.climatiq.io/estimate'
headers = {
'Authorization': 'Bearer {KEY}'.format(KEY = MY_API_KEY),
'Content-Type': 'application/x-www-form-urlencoded',
}
data = {
"emission_factor": {
"id": CategoryMapping.API_CATEGORY_TO_ACTIVITY_ID[API_cat],
"region": "us"
},
"parameters": {
"money": product["productCost"],
"money_unit": "usd"
}
}
print(data)
start = time.time()
response = requests.post(URL, headers=headers, json=data).json()
end = time.time()
print(end - start)
processEnd = time.time()
print(processEnd - processStart)
return json.dumps({"emissions": response})
else:
return 'Content-Type not supported!'
if __name__ == '__main__':
# run app in debug mode on port 5000
app.run(debug=True, port=5000)