ntdservices commited on
Commit
5819bad
·
verified ·
1 Parent(s): 85405d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -44
app.py CHANGED
@@ -1,56 +1,81 @@
1
- from flask import Flask, render_template, jsonify
2
- import requests
3
- from datetime import datetime, timedelta, timezone
 
 
 
 
4
 
5
- app = Flask(__name__)
 
 
6
 
7
- API_URL = "https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny"
 
 
 
 
 
 
8
 
9
- @app.route('/')
10
- def index():
11
- return render_template('index.html')
12
 
13
- @app.route('/api/debt')
14
- def get_debt_data():
15
- try:
16
- params = {
17
- "fields": "record_date,tot_pub_debt_out_amt",
18
- "sort": "-record_date",
19
- "limit": 2
20
- }
21
- response = requests.get(API_URL, params=params)
22
- data = response.json()["data"]
23
 
24
- # Extract debt values
25
- latest_debt = float(data[0]["tot_pub_debt_out_amt"])
26
- previous_debt = float(data[1]["tot_pub_debt_out_amt"])
 
 
27
 
28
- # Calculate daily growth rate (per second)
29
- rate_per_second = (latest_debt - previous_debt) / 86400 # 86400 seconds/day
 
 
 
 
30
 
31
- # Get the latest record date from the API
32
- latest_record_date = data[0]["record_date"] # e.g., "2025-07-29"
33
- latest_date = datetime.strptime(latest_record_date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
 
 
 
 
 
 
 
34
 
35
- # Calculate the beginning of the next day (midnight after latest data)
36
- start_of_next_day = latest_date + timedelta(days=1)
 
 
37
 
38
- # Get current time in UTC
39
- now = datetime.now(timezone.utc)
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- # Calculate how many seconds have passed since the end of the latest recorded day
42
- elapsed_seconds = (now - start_of_next_day).total_seconds()
43
- elapsed_seconds = max(0, elapsed_seconds) # prevent negative if latest date is today
44
-
45
- # Adjust starting debt to now
46
- adjusted_debt = latest_debt + (rate_per_second * elapsed_seconds)
47
-
48
- return jsonify({
49
- "startingDebt": adjusted_debt,
50
- "ratePerSecond": rate_per_second
51
- })
52
- except Exception as e:
53
- return jsonify({"error": str(e)}), 500
54
 
55
  if __name__ == "__main__":
56
- app.run(host="0.0.0.0", port=7860)
 
 
1
+ # app.py
2
+ #
3
+ # Hugging Face Space for a live U.S.-debt counter
4
+ # now exposes:
5
+ # • /api/debt – JSON with current total and per-second rate
6
+ # • /embed.js – tiny loader that paints any <div class="ntd-debt-clock">
7
+ # inside the host page (works under HF CSP)
8
 
9
+ import os, time
10
+ from flask import Flask, jsonify, send_from_directory
11
+ from flask_cors import CORS
12
 
13
+ # ---------------------------------------------------------------------
14
+ # Configuration – replace with your own authoritative numbers
15
+ # ---------------------------------------------------------------------
16
+ STARTING_DEBT = 34_457_892_345_678.12 # dollars at START_TIMESTAMP
17
+ RATE_PER_SECOND = 10_000.23 # dollars added each second
18
+ START_TIMESTAMP = time.time() # set when the container starts
19
+ # ---------------------------------------------------------------------
20
 
21
+ app = Flask(__name__, static_folder="templates")
22
+ CORS(app) # allow cross-origin fetches
 
23
 
24
+ @app.route("/")
25
+ def root():
26
+ return send_from_directory("static", "index.html")
 
 
 
 
 
 
 
27
 
28
+ @app.route("/api/debt")
29
+ def api_debt():
30
+ elapsed = time.time() - START_TIMESTAMP
31
+ current = STARTING_DEBT + RATE_PER_SECOND * elapsed
32
+ return jsonify(startingDebt=current, ratePerSecond=RATE_PER_SECOND)
33
 
34
+ @app.route("/embed.js")
35
+ def embed():
36
+ js = """
37
+ (() => {
38
+ const API = "https://ntdservices-debt-clock.hf.space/api/debt";
39
+ const CLS = "ntd-debt-clock";
40
 
41
+ function mount(el) {
42
+ // simple green-on-black styling; change or remove if you prefer CSS
43
+ Object.assign(el.style, {
44
+ font: "700 2rem/1 monospace",
45
+ color: "#0f0",
46
+ background: "#111",
47
+ padding: "6px 10px",
48
+ borderRadius: "6px",
49
+ whiteSpace: "nowrap"
50
+ });
51
 
52
+ fetch(API).then(r => r.json()).then(d => {
53
+ let debt = d.startingDebt;
54
+ const rate = d.ratePerSecond;
55
+ let last = performance.now();
56
 
57
+ function tick(now) {
58
+ const dt = (now - last) / 1000;
59
+ last = now;
60
+ debt += rate * dt;
61
+ el.textContent = "$" + debt.toLocaleString(undefined, {
62
+ minimumFractionDigits: 2,
63
+ maximumFractionDigits: 2
64
+ });
65
+ requestAnimationFrame(tick);
66
+ }
67
+ requestAnimationFrame(tick);
68
+ }).catch(() => { el.textContent = "N/A"; });
69
+ }
70
 
71
+ document.querySelectorAll("." + CLS).forEach(mount);
72
+ })();
73
+ """
74
+ return js, 200, {
75
+ "Content-Type": "application/javascript; charset=utf-8",
76
+ "Cache-Control": "public, max-age=31536000, immutable"
77
+ }
 
 
 
 
 
 
78
 
79
  if __name__ == "__main__":
80
+ port = int(os.environ.get("PORT", 7860))
81
+ app.run(host="0.0.0.0", port=port)