Spaces:
Runtime error
Runtime error
Download app.py from giangimene/Chatprof: direct link, hf CLI and curl.
- Browser
- Download file 16.9 kB
-
https://huggingface.co/spaces/giangimene/Chatprof/resolve/main/app.py
- Command line
-
hf download hf://spaces/giangimene/Chatprof/app.py
-
curl -L -o app.py https://huggingface.co/spaces/giangimene/Chatprof/resolve/main/app.py
16.9 kB
| import os | |
| import json | |
| import random | |
| import re | |
| from datetime import datetime, timedelta, timezone | |
| import streamlit as st | |
| import streamlit.components.v1 as components | |
| import google.generativeai as genai | |
| from supabase import create_client | |
| import trafilatura | |
| # ========================================================= | |
| # CONFIGURAZIONE APP | |
| # ========================================================= | |
| st.set_page_config(page_title="Elite Finance Summit", layout="wide") | |
| # ========================================================= | |
| # COSTANTI | |
| # ========================================================= | |
| EXPERTS = [ | |
| "Warren Buffett", | |
| "Ray Dalio", | |
| "Ed Yardeni", | |
| "Nassim Taleb", | |
| "Nouriel Roubini", | |
| "Cathie Wood", | |
| "Mohamed El-Erian", | |
| "Howard Marks", | |
| "Jerome Powell", | |
| "Paul Krugman", | |
| "Peter Schiff", | |
| "Janet Yellen", | |
| "Thomas Piketty", | |
| "Larry Fink", | |
| "Christine Lagarde", | |
| ] | |
| VALID_MOODS = {"Bullish", "Bearish"} | |
| # ========================================================= | |
| # INIZIALIZZAZIONE SERVIZI | |
| # ========================================================= | |
| supabase = None | |
| model = None | |
| try: | |
| genai.configure(api_key=os.environ["GEMINI_API_KEY"]) | |
| supabase = create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"]) | |
| model = genai.GenerativeModel("gemini-2.5-flash") | |
| except Exception as e: | |
| st.error(f"🚨 Errore di connessione ai Secrets: {e}") | |
| st.stop() | |
| # ========================================================= | |
| # SESSION STATE | |
| # ========================================================= | |
| if "visible_posts" not in st.session_state: | |
| st.session_state.visible_posts = 10 | |
| # ========================================================= | |
| # UTILS GENERALI | |
| # ========================================================= | |
| def now_utc(): | |
| return datetime.now(timezone.utc) | |
| def safe_str(value, default=""): | |
| return value if isinstance(value, str) else default | |
| def normalize_reply_to(value): | |
| if value is None: | |
| return None | |
| value = str(value).strip() | |
| if value.lower() in {"null", "none", ""}: | |
| return None | |
| return value | |
| def extract_json_object(raw_text: str) -> dict: | |
| """ | |
| Estrae il primo oggetto JSON valido dal testo del modello. | |
| Gestisce sia blocchi ```json ... ``` sia testo sporco intorno. | |
| """ | |
| if not raw_text or not isinstance(raw_text, str): | |
| raise ValueError("Risposta vuota dal modello") | |
| cleaned = raw_text.strip() | |
| cleaned = cleaned.replace("```json", "").replace("```", "").strip() | |
| try: | |
| return json.loads(cleaned) | |
| except json.JSONDecodeError: | |
| pass | |
| match = re.search(r"\{.*\}", cleaned, re.DOTALL) | |
| if match: | |
| candidate = match.group(0) | |
| return json.loads(candidate) | |
| raise ValueError("Nessun JSON valido trovato nella risposta del modello") | |
| def validate_model_output(data: dict) -> dict: | |
| """ | |
| Validazione forte dell'output del modello. | |
| Controlla: | |
| - struttura JSON | |
| - esattamente 15 commenti | |
| - un solo commento per esperto | |
| - primi 3 root | |
| - i successivi 12 devono essere reply validi | |
| """ | |
| if not isinstance(data, dict): | |
| raise ValueError("L'output del modello non è un oggetto JSON") | |
| ticker = safe_str(data.get("ticker"), "NONE").strip() or "NONE" | |
| comments = data.get("commenti") | |
| if not isinstance(comments, list): | |
| raise ValueError("Il campo 'commenti' non è una lista") | |
| if len(comments) != 15: | |
| raise ValueError(f"Il modello deve restituire esattamente 15 commenti, non {len(comments)}") | |
| validated_comments = [] | |
| used_users = set() | |
| for idx, c in enumerate(comments): | |
| if not isinstance(c, dict): | |
| raise ValueError(f"Commento {idx + 1} non valido") | |
| user = safe_str(c.get("user")).strip() | |
| mood = safe_str(c.get("mood")).strip() | |
| text = safe_str(c.get("text")).strip() | |
| reply_to = normalize_reply_to(c.get("reply_to")) | |
| if not user: | |
| raise ValueError(f"Commento {idx + 1}: user mancante") | |
| if user not in EXPERTS: | |
| raise ValueError(f"Commento {idx + 1}: user non ammesso ({user})") | |
| if user in used_users: | |
| raise ValueError(f"Commento {idx + 1}: esperto duplicato ({user})") | |
| if not text: | |
| raise ValueError(f"Commento {idx + 1}: testo vuoto") | |
| if mood not in VALID_MOODS: | |
| mood = "Bearish" | |
| text = re.sub(r"\s+", " ", text).strip() | |
| validated_comments.append({ | |
| "user": user, | |
| "mood": mood, | |
| "text": text, | |
| "reply_to": reply_to | |
| }) | |
| used_users.add(user) | |
| for i in range(3): | |
| if validated_comments[i]["reply_to"] is not None: | |
| raise ValueError(f"Il commento {i + 1} deve avere reply_to = null") | |
| seen_users = { | |
| validated_comments[0]["user"], | |
| validated_comments[1]["user"], | |
| validated_comments[2]["user"], | |
| } | |
| for i in range(3, 15): | |
| reply_to = validated_comments[i]["reply_to"] | |
| if reply_to is None: | |
| raise ValueError(f"Il commento {i + 1} deve essere una risposta, non un root") | |
| if reply_to not in seen_users: | |
| raise ValueError( | |
| f"Il commento {i + 1} risponde a '{reply_to}', ma quel nome non è ancora apparso prima" | |
| ) | |
| seen_users.add(validated_comments[i]["user"]) | |
| return { | |
| "ticker": ticker, | |
| "commenti": validated_comments | |
| } | |
| def format_created_at(value: str) -> str: | |
| if not value: | |
| return "-" | |
| try: | |
| dt = datetime.fromisoformat(value.replace("Z", "+00:00")) | |
| return dt.strftime("%d/%m/%Y %H:%M") | |
| except Exception: | |
| return value[:16] | |
| # ========================================================= | |
| # WIDGET TRADINGVIEW | |
| # ========================================================= | |
| def mostra_grafico(ticker: str, chart_id: str): | |
| if not ticker or ticker == "NONE": | |
| return | |
| html = f""" | |
| <div style="height:400px;"> | |
| <script src="https://s3.tradingview.com/tv.js"></script> | |
| <div id="{chart_id}"></div> | |
| <script> | |
| new TradingView.widget({{ | |
| "width": "100%", | |
| "height": 400, | |
| "symbol": "{ticker}", | |
| "interval": "D", | |
| "theme": "dark", | |
| "container_id": "{chart_id}" | |
| }}); | |
| </script> | |
| </div> | |
| """ | |
| components.html(html, height=410) | |
| # ========================================================= | |
| # ESTRAZIONE TESTO DA URL | |
| # ========================================================= | |
| def prepara_testo_da_analizzare(input_news: str) -> str: | |
| testo = input_news.strip() | |
| if not testo.startswith("http"): | |
| return testo | |
| try: | |
| downloaded = trafilatura.fetch_url(testo) | |
| if not downloaded: | |
| return testo | |
| extracted = trafilatura.extract(downloaded) | |
| if extracted: | |
| return f"Articolo estratto:\n\n{extracted}" | |
| return testo | |
| except Exception: | |
| return testo | |
| # ========================================================= | |
| # GEMINI | |
| # ========================================================= | |
| def build_prompt(testo_completo: str) -> str: | |
| expert_list = ", ".join(EXPERTS) | |
| return f""" | |
| ANALIZZA QUESTO CONTENUTO: | |
| {testo_completo} | |
| TASK: | |
| Genera un acceso dibattito in ITALIANO tra questi 15 esperti viventi: | |
| {expert_list} | |
| REGOLE OBBLIGATORIE: | |
| - Esattamente 15 commenti totali. | |
| - Ogni commento deve essere tra 50 e 80 parole. | |
| - I primi 3 commenti devono lanciare il tema e avere "reply_to": null. | |
| - Gli altri 12 devono rispondere ai primi o ad altri commenti precedenti, criticando o concordando in modo tecnico. | |
| - Se è una risposta, il campo "reply_to" deve contenere il nome esatto di uno degli esperti già comparsi prima. | |
| - Il campo "user" deve essere uno e uno solo tra i 15 nomi indicati. | |
| - Ogni esperto deve comparire una sola volta. | |
| - Il campo "mood" deve essere solo "Bullish" oppure "Bearish". | |
| - Il campo "ticker" deve essere un simbolo finanziario plausibile oppure "NONE". | |
| RESTITUISCI SOLO JSON PURO, senza testo introduttivo, senza markdown, senza commenti. | |
| Formato richiesto: | |
| {{ | |
| "ticker": "SIMBOLO_FINANZIARIO_O_NONE", | |
| "commenti": [ | |
| {{ | |
| "user": "Nome Cognome", | |
| "mood": "Bullish", | |
| "text": "testo commento", | |
| "reply_to": null | |
| }} | |
| ] | |
| }} | |
| """ | |
| def genera_summit(testo_completo: str, post_id: str): | |
| prompt = build_prompt(testo_completo) | |
| try: | |
| response = model.generate_content(prompt) | |
| raw_text = safe_str(getattr(response, "text", ""), "") | |
| parsed = extract_json_object(raw_text) | |
| data = validate_model_output(parsed) | |
| except Exception as e: | |
| raise RuntimeError(f"Errore nella generazione o nel parsing Gemini: {e}") | |
| try: | |
| supabase.table("posts").update({"ticker": data["ticker"]}).eq("id", post_id).execute() | |
| except Exception as e: | |
| raise RuntimeError(f"Errore aggiornando il ticker del post: {e}") | |
| for c in data["commenti"]: | |
| ritardo = random.randint(5, 90) | |
| pub_date = now_utc() + timedelta(seconds=ritardo) | |
| payload = { | |
| "post_id": post_id, | |
| "username": c["user"], | |
| "personality": c["mood"], | |
| "comment_text": c["text"], | |
| "reply_to": c["reply_to"], | |
| "scheduled_at": pub_date.isoformat() | |
| } | |
| try: | |
| supabase.table("comments").insert(payload).execute() | |
| except Exception: | |
| continue | |
| # ========================================================= | |
| # THREADING COMMENTI | |
| # ========================================================= | |
| def build_threaded_comments(comments: list) -> list: | |
| if not comments: | |
| return [] | |
| threaded = [] | |
| processed_ids = set() | |
| usernames_present = {c.get("username") for c in comments if c.get("username")} | |
| roots = [ | |
| c for c in comments | |
| if not c.get("reply_to") or c.get("reply_to") not in usernames_present | |
| ] | |
| def walk(comment, level): | |
| comment_id = comment.get("id") | |
| if not comment_id or comment_id in processed_ids: | |
| return | |
| processed_ids.add(comment_id) | |
| enriched = dict(comment) | |
| enriched["thread_level"] = level | |
| threaded.append(enriched) | |
| replies = [ | |
| r for r in comments | |
| if r.get("reply_to") == comment.get("username") and r.get("id") not in processed_ids | |
| ] | |
| replies.sort(key=lambda x: x.get("scheduled_at") or "") | |
| for r in replies: | |
| walk(r, level + 1) | |
| roots.sort(key=lambda x: x.get("scheduled_at") or "") | |
| for root in roots: | |
| walk(root, 0) | |
| for c in comments: | |
| if c.get("id") not in processed_ids: | |
| walk(c, 0) | |
| return threaded | |
| # ========================================================= | |
| # DB HELPERS | |
| # ========================================================= | |
| def crea_post(content: str): | |
| res = supabase.table("posts").insert({"content": content}).execute() | |
| if not res.data: | |
| raise RuntimeError("Inserimento post fallito") | |
| return res.data[0]["id"] | |
| def get_posts(limit=10): | |
| res = ( | |
| supabase.table("posts") | |
| .select("*") | |
| .order("created_at", desc=True) | |
| .limit(limit) | |
| .execute() | |
| ) | |
| return res.data or [] | |
| def get_visible_comments(post_id: str): | |
| current_time = now_utc().isoformat() | |
| res = ( | |
| supabase.table("comments") | |
| .select("*") | |
| .eq("post_id", post_id) | |
| .lte("scheduled_at", current_time) | |
| .order("scheduled_at") | |
| .execute() | |
| ) | |
| return res.data or [] | |
| def warn_comment(comment_id: str): | |
| supabase.table("comments").update({"is_warned": True}).eq("id", comment_id).execute() | |
| # ========================================================= | |
| # UI SIDEBAR | |
| # ========================================================= | |
| st.title("🏛️ Elite Finance Summit") | |
| with st.sidebar: | |
| st.header("⚙️ Pannello Admin") | |
| input_news = st.text_area("Incolla un Link o una News:") | |
| password = st.text_input("Password Admin", type="password") | |
| if st.button("🚀 Lancia il Dibattito"): | |
| if password != "Riccardo74$": | |
| st.error("❌ Password errata!") | |
| elif not input_news.strip(): | |
| st.warning("⚠️ Inserisci un link o un testo.") | |
| else: | |
| with st.spinner("I titani stanno scrivendo..."): | |
| try: | |
| testo_da_analizzare = prepara_testo_da_analizzare(input_news) | |
| post_id = crea_post(input_news) | |
| genera_summit(testo_da_analizzare, post_id) | |
| st.success("Thread lanciato! Guarda la bacheca.") | |
| st.rerun() | |
| except Exception as e: | |
| st.error(f"Errore durante la generazione del thread: {e}") | |
| st.divider() | |
| st.subheader("🧹 Gestione Dati") | |
| if st.button("🗑️ Svuota tutto il Forum"): | |
| if password != "Riccardo74$": | |
| st.error("❌ Serve la password per svuotare!") | |
| else: | |
| with st.spinner("Piallatura in corso..."): | |
| supabase.table("posts").delete().neq( | |
| "id", "00000000-0000-0000-0000-000000000000" | |
| ).execute() | |
| st.success("Boom! Forum svuotato, pulito come nuovo.") | |
| st.rerun() | |
| # ========================================================= | |
| # FEED FORUM | |
| # ========================================================= | |
| posts = get_posts(limit=st.session_state.visible_posts) | |
| for p in posts: | |
| post_id = p.get("id") | |
| ticker = p.get("ticker") | |
| content = p.get("content", "") | |
| created_at = format_created_at(p.get("created_at", "")) | |
| with st.container(border=True): | |
| if ticker and ticker != "NONE": | |
| c_news, c_graph = st.columns([1, 1.5]) | |
| with c_news: | |
| st.caption(f"📅 Pubblicato il: {created_at}") | |
| st.info(content) | |
| with c_graph: | |
| mostra_grafico(ticker, chart_id=f"tv_chart_{post_id}") | |
| else: | |
| st.caption(f"📅 Pubblicato il: {created_at}") | |
| st.info(content) | |
| st.divider() | |
| coms = get_visible_comments(post_id) | |
| if not coms: | |
| st.write("⏱️ *Attendi qualche secondo... i primi commenti stanno per apparire.*") | |
| else: | |
| threaded_comments = build_threaded_comments(coms) | |
| for c in threaded_comments: | |
| level = c.get("thread_level", 0) | |
| is_reply = level > 0 | |
| is_warned = bool(c.get("is_warned", False)) | |
| username = c.get("username", "Sconosciuto") | |
| personality = c.get("personality", "Bearish") | |
| comment_text = c.get("comment_text", "") | |
| reply_to = c.get("reply_to") | |
| comment_id = c.get("id") | |
| if is_reply: | |
| left_pad = min(0.06 * level, 0.30) | |
| cols = st.columns([left_pad, 1 - left_pad]) | |
| chat_box = cols[1] | |
| else: | |
| chat_box = st.container() | |
| with chat_box: | |
| box_style = "" | |
| if is_warned: | |
| box_style = "border-left: 4px solid red; background: rgba(255,0,0,0.05);" | |
| st.markdown( | |
| f'<div style="{box_style} padding:5px; margin-bottom:5px; border-radius:8px;">', | |
| unsafe_allow_html=True | |
| ) | |
| with st.chat_message( | |
| "user", | |
| avatar=f"https://api.dicebear.com/7.x/bottts/svg?seed={username}" | |
| ): | |
| t_col, b_col = st.columns([0.85, 0.15]) | |
| with t_col: | |
| if is_warned: | |
| st.error(f"🚨 RICHIAMO DISCIPLINARE PER {username.upper()}") | |
| if is_reply and reply_to: | |
| st.markdown(f"↪️ *In risposta a **@{reply_to}***") | |
| st.write(f"**{username}** ({personality}): {comment_text}") | |
| with b_col: | |
| if not is_warned and comment_id: | |
| if st.button("🚫", key=f"w_{comment_id}"): | |
| warn_comment(comment_id) | |
| st.rerun() | |
| st.markdown("</div>", unsafe_allow_html=True) | |
| if len(posts) == st.session_state.visible_posts: | |
| st.divider() | |
| if st.button("Carica altri post"): | |
| st.session_state.visible_posts += 10 | |
| st.rerun() |