Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import google.generativeai as genai
|
| 3 |
+
from supabase import create_client
|
| 4 |
+
import os, json, random
|
| 5 |
+
from datetime import datetime, timedelta
|
| 6 |
+
import streamlit.components.v1 as components
|
| 7 |
+
import trafilatura
|
| 8 |
+
|
| 9 |
+
# --- CONFIGURAZIONE UI ---
|
| 10 |
+
st.set_page_config(page_title="Elite Finance Summit 2026", layout="wide")
|
| 11 |
+
|
| 12 |
+
# --- CONNESSIONI API (Pesca i dati dalla cassaforte di Hugging Face) ---
|
| 13 |
+
try:
|
| 14 |
+
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
|
| 15 |
+
supabase = create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"])
|
| 16 |
+
model = genai.GenerativeModel('gemini-3-flash')
|
| 17 |
+
except Exception as e:
|
| 18 |
+
st.error("Errore: Impossibile connettersi. Controlla i Secrets in Hugging Face!")
|
| 19 |
+
|
| 20 |
+
# --- WIDGET TRADINGVIEW ---
|
| 21 |
+
def mostra_grafico(ticker):
|
| 22 |
+
if ticker and ticker != "NONE":
|
| 23 |
+
html = f"""
|
| 24 |
+
<div style="height:400px;"><script src="https://s3.tradingview.com/tv.js"></script>
|
| 25 |
+
<script>new TradingView.widget({{"width": "100%", "height": 400, "symbol": "{ticker}", "interval": "D", "theme": "dark", "container_id": "tv_chart"}});</script>
|
| 26 |
+
<div id="tv_chart"></div></div>
|
| 27 |
+
"""
|
| 28 |
+
components.html(html, height=410)
|
| 29 |
+
|
| 30 |
+
# --- MOTORE GEMINI 3 FLASH (Ottimizzato per risparmio token) ---
|
| 31 |
+
def genera_summit(testo_completo, post_id):
|
| 32 |
+
prompt = f"""
|
| 33 |
+
ANALIZZA: {testo_completo}
|
| 34 |
+
|
| 35 |
+
TASK: Genera discussione in ITALIANO tra 15 esperti viventi: Buffett, Dalio, Yardeni, Taleb, Roubini, Wood, El-Erian, Marks, Powell, Krugman, Schiff, Yellen, Piketty, Fink, Lagarde.
|
| 36 |
+
|
| 37 |
+
REGOLE:
|
| 38 |
+
1. 15 commenti totali, 60-90 parole l'uno. Sostanza tecnica elevata.
|
| 39 |
+
2. Stile fedele al personaggio reale.
|
| 40 |
+
3. Almeno 7 commenti devono citare un altro esperto con @Nome.
|
| 41 |
+
4. Output SOLO JSON pulito:
|
| 42 |
+
{{
|
| 43 |
+
"ticker": "SIMBOLO_FINANZIARIO_O_NONE",
|
| 44 |
+
"commenti": [ {{"user": "Nome", "mood": "Bullish/Bearish/Neutrale", "text": "...", "reply_to": "Nome_o_null"}}, ... ]
|
| 45 |
+
}}
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
response = model.generate_content(prompt)
|
| 49 |
+
raw_res = response.text.replace('```json', '').replace('```', '').strip()
|
| 50 |
+
data = json.loads(raw_res)
|
| 51 |
+
|
| 52 |
+
supabase.table("posts").update({"ticker": data['ticker']}).eq("id", post_id).execute()
|
| 53 |
+
|
| 54 |
+
for c in data['commenti']:
|
| 55 |
+
ritardo = random.randint(5, 300) # Appariranno un po' alla volta nei prossimi 5 minuti
|
| 56 |
+
pub_date = datetime.now() + timedelta(seconds=ritardo)
|
| 57 |
+
supabase.table("comments").insert({
|
| 58 |
+
"post_id": post_id,
|
| 59 |
+
"username": c['user'],
|
| 60 |
+
"personality": c['mood'],
|
| 61 |
+
"comment_text": c['text'],
|
| 62 |
+
"reply_to": c.get('reply_to'),
|
| 63 |
+
"scheduled_at": pub_date.isoformat()
|
| 64 |
+
}).execute()
|
| 65 |
+
|
| 66 |
+
# --- INTERFACCIA WEB ---
|
| 67 |
+
st.title("ποΈ Elite Finance Summit 2026")
|
| 68 |
+
|
| 69 |
+
with st.sidebar:
|
| 70 |
+
st.header("βοΈ Pannello Admin")
|
| 71 |
+
input_news = st.text_area("Incolla un Link o una News:", placeholder="Es: https://www.ilsole24ore.com/...")
|
| 72 |
+
|
| 73 |
+
# LA TUA PASSWORD IMPOSTATA PER SBLOCCARE IL FORUM
|
| 74 |
+
password = st.text_input("Password Admin", type="password")
|
| 75 |
+
|
| 76 |
+
if st.button("π Lancia il Dibattito"):
|
| 77 |
+
if password != "1WSOtpSbFnpfoYnW":
|
| 78 |
+
st.error("β Password errata!")
|
| 79 |
+
elif not input_news:
|
| 80 |
+
st.warning("β οΈ Inserisci un link o un testo.")
|
| 81 |
+
else:
|
| 82 |
+
with st.spinner("Estrazione dati e convocazione esperti..."):
|
| 83 |
+
testo_da_analizzare = input_news
|
| 84 |
+
|
| 85 |
+
# SCRAPER: Se Γ¨ un link, estrae il testo da solo
|
| 86 |
+
if input_news.startswith("http"):
|
| 87 |
+
st.info("π Link rilevato, lettura articolo in corso...")
|
| 88 |
+
downloaded = trafilatura.fetch_url(input_news)
|
| 89 |
+
extracted = trafilatura.extract(downloaded)
|
| 90 |
+
if extracted:
|
| 91 |
+
testo_da_analizzare = f"Articolo estratto:\n\n{extracted}"
|
| 92 |
+
else:
|
| 93 |
+
st.warning("Sito protetto, passo l'URL direttamente.")
|
| 94 |
+
|
| 95 |
+
res = supabase.table("posts").insert({"content": input_news}).execute()
|
| 96 |
+
genera_summit(testo_da_analizzare, res.data[0]['id'])
|
| 97 |
+
st.success("News elaborata! I commenti stanno arrivando...")
|
| 98 |
+
st.rerun()
|
| 99 |
+
|
| 100 |
+
# --- FEED DEL FORUM ---
|
| 101 |
+
posts = supabase.table("posts").select("*").order("created_at", desc=True).execute()
|
| 102 |
+
|
| 103 |
+
for p in posts.data:
|
| 104 |
+
with st.container(border=True):
|
| 105 |
+
c_news, c_graph = st.columns([1, 1.5])
|
| 106 |
+
with c_news:
|
| 107 |
+
st.caption(f"π
Pubblicato il: {p['created_at'][:16]}")
|
| 108 |
+
st.info(p['content'])
|
| 109 |
+
with c_graph:
|
| 110 |
+
if p['ticker']: mostra_grafico(p['ticker'])
|
| 111 |
+
|
| 112 |
+
st.divider()
|
| 113 |
+
|
| 114 |
+
ora = datetime.now().isoformat()
|
| 115 |
+
coms = supabase.table("comments").select("*").eq("post_id", p['id']).lte("scheduled_at", ora).order("scheduled_at").execute()
|
| 116 |
+
|
| 117 |
+
if not coms.data:
|
| 118 |
+
st.write("β±οΈ *Gli esperti stanno scrivendo le loro analisi...*")
|
| 119 |
+
|
| 120 |
+
for c in coms.data:
|
| 121 |
+
with st.container():
|
| 122 |
+
box_style = "border-left: 5px solid red; background: rgba(255,0,0,0.05);" if c['is_warned'] else ""
|
| 123 |
+
st.markdown(f'<div style="{box_style} padding:10px; margin-bottom:10px;">', unsafe_allow_html=True)
|
| 124 |
+
|
| 125 |
+
with st.chat_message("user", avatar=f"https://api.dicebear.com/7.x/bottts/svg?seed={c['username']}"):
|
| 126 |
+
t_col, b_col = st.columns([0.85, 0.15])
|
| 127 |
+
with t_col:
|
| 128 |
+
if c['is_warned']: st.error(f"π¨ RICHIAMO UFFICIALE: {c['username'].upper()}")
|
| 129 |
+
if c['reply_to']: st.caption(f"β³ In risposta a @{c['reply_to']}")
|
| 130 |
+
st.write(f"**{c['username']}** ({c['personality']}): \n{c['comment_text']}")
|
| 131 |
+
with b_col:
|
| 132 |
+
if not c['is_warned']:
|
| 133 |
+
if st.button("π«", key=f"w_{c['id']}"):
|
| 134 |
+
supabase.table("comments").update({"is_warned": True}).eq("id", c['id']).execute()
|
| 135 |
+
st.rerun()
|
| 136 |
+
st.markdown('</div>', unsafe_allow_html=True)
|