Skip to content

Commit

Permalink
Merge pull request #2 from allora-network/diego/ora-1068-add-previous…
Browse files Browse the repository at this point in the history
…-reputer-reports-to-enable-ema-on-eq13

Get losses, bulletproof gt/ losses, change endpoints
  • Loading branch information
xmariachi authored Apr 4, 2024
2 parents 3a7fba9 + 313ac01 commit 0ce34bb
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 10 deletions.
32 changes: 30 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

ETHUSD_TOKEN = "ETHUSD"
API_PORT = int(os.environ.get('TRUTH_API_PORT', 5000))
ALLORA_VALIDATOR_API_URL = str(os.environ.get('ALLORA_VALIDATOR_API_URL','http://localhost:1317/emissions/v1/network_loss/'))
app = Flask(__name__)

DATABASE_PATH = 'prices.db'
Expand Down Expand Up @@ -64,15 +65,15 @@ def update_price(token_name, token_from, token_to):
return jsonify({'error': f'Failed to update {token_name} price: {str(e)}'}), 500


@app.route('/get/<token>/<timestamp>')
@app.route('/gt/<token>/<timestamp>')
def get_eth_price(token, timestamp):
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
cursor.execute("SELECT timestamp, price FROM prices WHERE token=? AND timestamp <= ? ORDER BY timestamp DESC LIMIT 1", (token, timestamp))
result = cursor.fetchone()
conn.close()
if result:
return jsonify({'value': str(result[1])}), 200
return str('"' + str(result[1]) + '"'), 200
else:
return jsonify({'error': 'No price data found for the specified token and timestamp'}), 404

Expand Down Expand Up @@ -121,6 +122,33 @@ def init_price_token(token_name, token_from, token_to):
raise e


def get_test_data():
test_data = '{"networkInference":"1234.56","inferrerInferences":[{"node":"allo1inf1","value":"1234.01"},{"node":"allo1inf2","value":"1235.01"},{"node":"allo1inf0000","value":"1234.61"}],"forecasterInferences":[{"node":"allo1inf1","value":"1234.20"},{"node":"allo1inf2","value":"1235.70"},{"node":"allo1inf1111","value":"1234.52"}],"naiveNetworkInference":"1234.30","oneOutNetworkInferences":[{"node":"allo1inf1","value":"1234.20"},{"node":"allo1inf2","value":"1234.70"},{"node":"allo1inf0000","value":"1235.45"}],"oneInNetworkInferences":[{"node":"allo1inf1","value":"1234.20"},{"node":"allo1inf2","value":"1234.70"},{"node":"allo1inf1111","value":"1235.45"}]}'
return test_data, 200

def get_losses_data(topic):
try:
response = requests.get(ALLORA_VALIDATOR_API_URL + topic)
response.raise_for_status() # Raise exception if request fails
return response.json(), 200
except Exception as e:
print(f'Failed to get data for {topic} token: {str(e)}')
print(f'Not providing last losses for {topic} token')
return '{}', 200

@app.route('/losses/<topic>')
def get_losses(topic):
print(f"Getting losses for {topic}")
try:
# Change this when real data is available
# get losses data(topic)
return get_test_data()

except Exception as e:
print(f'Failed to get data for {topic} token: {str(e)}')
print(f'Not providing last losses for {topic} token')
return '{}', 200

if __name__ == '__main__':
init_price_token(ETHUSD_TOKEN, 'ethereum', 'usd')
app.run(host='0.0.0.0', port=API_PORT)
Expand Down
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ services:
command: python -u /app/app.py
environment:
- TRUTH_API_PORT=8000
# - ALLORA_VALIDATOR_API_URL=https://allora-api.testnet.allora.network/emissions/v1/network_loss/
- ALLORA_VALIDATOR_API_URL=https://localhost:1317/emissions/v1/network_loss/
# For local testing via URL without workers/heads up:
ports:
- "8000:8000"
Expand Down
31 changes: 23 additions & 8 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,36 @@
ETHUSD_TOKEN = "ETHUSD"
TRUTH_ADDRESS = os.environ['TRUTH_API_ADDRESS']

def process(token_name, timestamp):
url = f"{TRUTH_ADDRESS}/get/{token_name}/{timestamp}"
def get_ground_truth(token_name, timestamp):
url = f"{TRUTH_ADDRESS}/gt/{token_name}/{timestamp}"
response = requests.get(url)
return response.text

def get_previous_losses(topic):
url = f"{TRUTH_ADDRESS}/losses/{topic}"
response = requests.get(url)
return response.text


if __name__ == "__main__":
# Your code logic with the parsed argument goes here
try:
# Not using to discriminate by topicId for simplicity.
# topic_id = sys.argv[1]
topic_id = sys.argv[1]
if len(sys.argv) >= 3:
timestamp = sys.argv[2]
response = process(token_name=ETHUSD_TOKEN, timestamp=timestamp)

response_gt = get_ground_truth(token_name=ETHUSD_TOKEN, timestamp=timestamp)
json_gt = json.loads(response_gt)
try:
response_losses = get_previous_losses(topic=topic_id)
json_losses = json.loads(response_losses)
response_dict = {"gt": json_gt, "losses": json_losses}
# Serialize as JSON
value = json.dumps(response_dict)
except Exception as e:
# Print only ground truth if losses are not available
response_dict = {"gt": json_gt}
value = json.dumps(response_dict)
except Exception as e:
response = json.dumps({"error": {str(e)}})
print(response)
# No gt, no value - error
value = json.dumps({"error": {str(e)}})
print(value)

0 comments on commit 0ce34bb

Please sign in to comment.