from flask import Flask, render_template_string import yfinance as yf import re import threading import time import os app = Flask(__name__) HTML_FILE = "NEW_AI_INFRA.html" SYNC_INTERVAL = 60 # Seconds (Recommended: 60+) def sync_logic(): """Background task to sync prices.""" while True: print(f"🔄 [Background Sync] Starting update at {time.ctime()}...", flush=True) try: with open(HTML_FILE, 'r', encoding='utf-8') as f: content = f.read() match = re.search(r'const\s+companies\s*=\s*\[(.*?)\]\s*;', content, re.DOTALL) if match: raw_array = match.group(1) tickers = re.findall(r'ticker:\s*"([^"]+)"', raw_array) # Batch fetch is faster data_map = {} for ticker in tickers: try: stock = yf.Ticker(ticker) hist = stock.history(period="2d") if not hist.empty: price = hist['Close'].iloc[-1] change = ((price - hist['Close'].iloc[-2]) / hist['Close'].iloc[-2]) * 100 if len(hist) > 1 else 0 data_map[ticker] = {"p": round(price, 2), "c": round(change, 2)} except: continue def update_entry(m): block = m.group(0) t_match = re.search(r'ticker:\s*"([^"]+)"', block) if t_match and t_match.group(1) in data_map: ticker = t_match.group(1) block = re.sub(r'price:\s*[\d\.\-]+', f'price: {data_map[ticker]["p"]}', block) block = re.sub(r'change:\s*[\d\.\-]+', f'change: {data_map[ticker]["c"]}', block) return block updated_array = re.sub(r'\{.*?\}(?=\s*,|\s*\])', update_entry, raw_array, flags=re.DOTALL) updated_content = content.replace(raw_array, updated_array) with open(HTML_FILE, 'w', encoding='utf-8') as f: f.write(updated_content) print("✅ [Background Sync] HTML File Updated.", flush=True) except Exception as e: print(f"❌ [Background Sync] Error: {e}", flush=True) time.sleep(SYNC_INTERVAL) @app.route('/') def index(): with open(HTML_FILE, 'r', encoding='utf-8') as f: return render_template_string(f.read()) if __name__ == "__main__": # Start the background sync thread threading.Thread(target=sync_logic, daemon=True).start() # Run Flask app.run(debug=True, host='0.0.0.0', port=7860)