Spaces:
Sleeping
Sleeping
Etiquetado distinto, diagramas
Browse filesFiles changed (6)
- backend/server.py+683-12
- chatbot/dist/index.htmlAdded+12
- chatbot/src/components/emotionchat.jsx+183-7
- graphics/flowchart TD.mmdAdded+33
- graphics/flowchart_funciones.mmdAdded+51
- graphics/sequence_funciones.mmdAdded+54
123456789101112134 unmodified lines1819202122232425262728298 unmodified lines383940414243446 unmodified lines5152535455565758596061626364653 unmodified lines697071727374757677787980818283848586878889909192939495from pathlib import Pathimport csvfrom flask import Flask, jsonify, requestfrom flask_cors import CORSfrom transformers import pipelineapp = Flask(__name__)CORS(app)EMOTION_MAP = {"joy": "alegria","sadness": "tristeza",4 unmodified lines"others": "neutral",}def load_movies_dataset() -> list[dict]:root_dir = Path(__file__).resolve().parent.parentcandidates = [root_dir / "data" / "procesado" / "peliculas_100_emociones.csv",root_dir / "data" / "procesado" / "peliculas_conocidas.csv",]for path in candidates:8 unmodified linesreturn []def recommend_movies(emotion_es: str, limit: int = 12) -> list[dict]:if not MOVIES_DF:return []6 unmodified linesif not filtered:return []filtered.sort(key=lambda r: (float(r.get("rating_count", 0) or 0),float(r.get("rating_mean", 0) or 0),),reverse=True,)return filtered[:limit]print("Cargando modelo...")3 unmodified linestop_k=None,device=-1,)MOVIES_DF = load_movies_dataset()print(f"Listo. Dataset de recomendaciones: {len(MOVIES_DF)} peliculas")@app.route("/analizar", methods=["POST"])def analizar():texto = request.json.get("texto", "")resultado = sorted(clf(texto)[0], key=lambda x: x["score"], reverse=True)dominant_model = resultado[0]["label"] if resultado else "others"dominant_es = EMOTION_MAP.get(dominant_model, "neutral")recomendaciones = recommend_movies(dominant_es, limit=12)return jsonify({"emociones": resultado,"emocion_dominante": dominant_es,"recomendaciones": recomendaciones,})if __name__ == "__main__":app.run(port=5000)1234567891011121314151617181920214 unmodified lines262728293031323334353637383940414243444546474849508 unmodified lines59606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251266 unmodified lines1331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814823 unmodified lines486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766from pathlib import Pathimport csvimport randomimport sqlite3from collections import Counterfrom datetime import datetime, timezonefrom flask import Flask, jsonify, requestfrom flask_cors import CORSimport requests as http_requestsfrom transformers import pipelineapp = Flask(__name__)CORS(app)ROOT_DIR = Path(__file__).resolve().parent.parentHISTORY_DB_PATH = ROOT_DIR / "backend" / "history.db"EMOTION_MAP = {"joy": "alegria","sadness": "tristeza",4 unmodified lines"others": "neutral",}POSITIVE_EMOTIONS = {"alegria", "sorpresa", "neutral"}NEGATIVE_EMOTIONS = {"tristeza", "ira", "miedo", "asco"}TEXT_MODEL_NAME = "llama3.2"OLLAMA_URL = "http://localhost:11434/api/generate"LIKE_THRESHOLD = 4.0def emotion_to_valence(emotion: str) -> str:if emotion in POSITIVE_EMOTIONS:return "positivo"if emotion in NEGATIVE_EMOTIONS:return "negativo"return "neutro"def load_movies_dataset() -> list[dict]:candidates = [ROOT_DIR / "data" / "procesado" / "peliculas_100_emociones.csv",ROOT_DIR / "data" / "procesado" / "peliculas_conocidas.csv",]for path in candidates:8 unmodified linesreturn []def _movie_genres(row: dict) -> set[str]:return {g.strip() for g in row.get("genres", "").split("|") if g.strip()}def _get_user_history_rows(user_id: str, limit: int = 200) -> list[dict]:with get_db_connection() as conn:rows = conn.execute("""SELECT movie_id, user_ratingFROM view_historyWHERE user_id = ?ORDER BY viewed_at DESCLIMIT ?""",(user_id, limit),).fetchall()return [dict(row) for row in rows]def _build_history_profile(history_rows: list[dict]) -> tuple[set[str], Counter, Counter]:viewed_ids = {str(row.get("movie_id", "")).strip() for row in history_rows if row.get("movie_id")}viewed_genres_counter: Counter = Counter()liked_ids = {str(row.get("movie_id", "")).strip()for row in history_rowsif row.get("movie_id") and (row.get("user_rating") is not None) and float(row.get("user_rating") or 0) >= LIKE_THRESHOLD}liked_genres_counter: Counter = Counter()if not viewed_ids:return viewed_ids, viewed_genres_counter, liked_genres_counterfor movie in MOVIES_DF:movie_id = str(movie.get("movieId", "")).strip()if movie_id in viewed_ids:genres = _movie_genres(movie)viewed_genres_counter.update(genres)if movie_id in liked_ids:liked_genres_counter.update(genres)return viewed_ids, viewed_genres_counter, liked_genres_counterdef _quality_key(row: dict) -> tuple[float, float]:return (float(row.get("rating_count", 0) or 0),float(row.get("rating_mean", 0) or 0),)def _similarity_to_history(row: dict, history_genres: set[str]) -> float:if not history_genres:return 0.0genres = _movie_genres(row)if not genres:return 0.0return len(genres & history_genres) / len(genres)def recommend_movies(emotion_es: str, user_id: str = "", limit: int = 12) -> list[dict]:if not MOVIES_DF:return []6 unmodified linesif not filtered:return []history_rows = _get_user_history_rows(user_id) if user_id else []viewed_ids, viewed_genres_counter, liked_genres_counter = _build_history_profile(history_rows)viewed_genres = set(viewed_genres_counter.keys())liked_genres = set(liked_genres_counter.keys())has_history = len(viewed_ids) > 0if not has_history:filtered.sort(key=_quality_key, reverse=True)pool_size = min(len(filtered), max(limit * 4, limit))candidate_pool = filtered[:pool_size]if len(candidate_pool) <= limit:random.shuffle(candidate_pool)return candidate_poolreturn random.sample(candidate_pool, k=limit)unseen_filtered = [row for row in filtered if str(row.get("movieId", "")).strip() not in viewed_ids]candidates = unseen_filtered if unseen_filtered else filteredis_positive = emotion_es in POSITIVE_EMOTIONS# Negativo: parecido a peliculas valoradas positivamente; fallback a todo el historial si no hay valoraciones altas.reference_genres = viewed_genres if is_positive else (liked_genres if liked_genres else viewed_genres)ranked = sorted(candidates,key=lambda r: (_similarity_to_history(r, reference_genres), *_quality_key(r)),reverse=not is_positive,)return ranked[:limit]def save_emotion_event(user_id: str, text: str, emotion: str, analyzed_at: str) -> int | None:if not user_id:return Nonewith get_db_connection() as conn:cur = conn.execute("""INSERT INTO emotion_events (user_id, text, emotion, analyzed_at)VALUES (?, ?, ?, ?)""",(user_id, text, emotion, analyzed_at),)conn.commit()return cur.lastrowiddef create_recommendation_cycle(user_id: str,pre_text: str,pre_emotion: str,recommendation_mode: str,created_at: str,) -> int | None:if not user_id:return Nonepre_valence = emotion_to_valence(pre_emotion)with get_db_connection() as conn:cur = conn.execute("""INSERT INTO recommendation_cycles (user_id,pre_text,pre_emotion,pre_valence,recommendation_mode,created_at)VALUES (?, ?, ?, ?, ?, ?)""",(user_id, pre_text, pre_emotion, pre_valence, recommendation_mode, created_at),)conn.commit()return cur.lastrowiddef get_recommendation_cycle(cycle_id: int, user_id: str) -> dict | None:with get_db_connection() as conn:row = conn.execute("""SELECT id, user_id, pre_text, pre_emotion, pre_valence, recommendation_mode,created_at, selected_movie_id, selected_movie_title,post_text, post_emotion, post_valence, post_analyzed_atFROM recommendation_cyclesWHERE id = ? AND user_id = ?LIMIT 1""",(cycle_id, user_id),).fetchone()return dict(row) if row else Nonedef save_post_recommendation_state(cycle_id: int,user_id: str,post_text: str,post_emotion: str,post_analyzed_at: str,movie_id: str,movie_title: str,) -> None:post_valence = emotion_to_valence(post_emotion)with get_db_connection() as conn:conn.execute("""UPDATE recommendation_cyclesSET selected_movie_id = ?,selected_movie_title = ?,post_text = ?,post_emotion = ?,post_valence = ?,post_analyzed_at = ?WHERE id = ? AND user_id = ?""",(movie_id, movie_title, post_text, post_emotion, post_valence, post_analyzed_at, cycle_id, user_id),)conn.commit()def get_last_emotion_event(user_id: str) -> dict | None:if not user_id:return Nonewith get_db_connection() as conn:row = conn.execute("""SELECT id, user_id, text, emotion, analyzed_atFROM emotion_eventsWHERE user_id = ?ORDER BY analyzed_at DESCLIMIT 1""",(user_id,),).fetchone()return dict(row) if row else Nonedef get_last_viewed_between(user_id: str, start_iso: str, end_iso: str) -> dict | None:with get_db_connection() as conn:row = conn.execute("""SELECT movie_id, title, viewed_atFROM view_historyWHERE user_id = ?AND viewed_at > ?AND viewed_at <= ?ORDER BY viewed_at DESCLIMIT 1""",(user_id, start_iso, end_iso),).fetchone()return dict(row) if row else Nonedef build_chatbot_response(dominant_emotion: str,recommendation_mode: str,recommendations: list[dict],previous_event: dict | None,transition_movie: dict | None,) -> str:if recommendation_mode == "diferente":mode_text = "Como estas en un estado positivo, te propongo explorar peliculas distintas a tu historial."else:mode_text = "Como estas en un estado negativo, te propongo peliculas similares a tu historial para mantener una zona conocida."if recommendations:top_title = recommendations[0].get("title", "una pelicula")reco_text = f"Primera sugerencia: {top_title}."else:reco_text = "No encontre recomendaciones para ese estado emocional en este momento."if not previous_event:transition_text = "Este es tu primer punto de referencia emocional para analizar transiciones futuras."else:prev_emotion = previous_event.get("emotion", "neutral")if prev_emotion == dominant_emotion:transition_text = f"Tu estado se mantiene en {dominant_emotion}."else:transition_text = f"Detecto una transicion de {prev_emotion} a {dominant_emotion}."if transition_movie:movie_title = transition_movie.get("title") or transition_movie.get("movie_id", "pelicula marcada")transition_text += f" Ultima pelicula vista entre ambos estados: {movie_title}."return f"Estado actual: {dominant_emotion}. {mode_text} {reco_text} {transition_text}"def _build_text_generation_prompt(dominant_emotion: str,recommendation_mode: str,recommendations: list[dict],previous_event: dict | None,transition_movie: dict | None,) -> str:top_titles = [str(row.get("title", "")).strip() for row in recommendations[:3] if row.get("title")]top_titles_text = ", ".join(top_titles) if top_titles else "sin recomendaciones"prev_emotion = previous_event.get("emotion") if previous_event else "ninguna"transition_movie_title = ""if transition_movie:transition_movie_title = str(transition_movie.get("title") or transition_movie.get("movie_id") or "").strip()return ("Eres un asistente de recomendaciones de peliculas. ""Redacta una respuesta breve en espanol (maximo 3 frases), clara y empatica. ""Incluye estado emocional actual, explicacion de por que el modo de recomendacion es ese, ""y menciona una pelicula sugerida si existe. "f"Estado actual: {dominant_emotion}. "f"Modo: {recommendation_mode}. "f"Emocion anterior: {prev_emotion}. "f"Peliculas sugeridas: {top_titles_text}. "f"Pelicula asociada a transicion: {transition_movie_title or 'ninguna'}.")def generate_chatbot_text(dominant_emotion: str,recommendation_mode: str,recommendations: list[dict],previous_event: dict | None,transition_movie: dict | None,) -> tuple[str, str]:template_text = build_chatbot_response(dominant_emotion=dominant_emotion,recommendation_mode=recommendation_mode,recommendations=recommendations,previous_event=previous_event,transition_movie=transition_movie,)try:prompt = _build_text_generation_prompt(dominant_emotion=dominant_emotion,recommendation_mode=recommendation_mode,recommendations=recommendations,previous_event=previous_event,transition_movie=transition_movie,)payload = {"model": TEXT_MODEL_NAME,"prompt": prompt,"stream": False,"options": {"temperature": 0.7,"top_p": 0.9,"num_predict": 120,},}res = http_requests.post(OLLAMA_URL, json=payload, timeout=20)if res.ok:data = res.json()generated = str(data.get("response", "")).strip()if generated:return generated, "ollama"print(f"Aviso: Ollama devolvio HTTP {res.status_code}. Se usa plantilla.")except Exception as exc:print(f"Aviso: fallo generando texto con Ollama ({exc}). Se usa plantilla.")return template_text, "template-fallback"def get_db_connection() -> sqlite3.Connection:conn = sqlite3.connect(HISTORY_DB_PATH)conn.row_factory = sqlite3.Rowreturn conndef init_history_db() -> None:with get_db_connection() as conn:conn.execute("""CREATE TABLE IF NOT EXISTS view_history (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id TEXT NOT NULL,movie_id TEXT NOT NULL,title TEXT,emotion TEXT,user_rating REAL,session_text TEXT,viewed_at TEXT NOT NULL)""")# Compatibilidad con BDs existentes creadas sin columna de valoracion.columns = conn.execute("PRAGMA table_info(view_history)").fetchall()column_names = {row[1] for row in columns}if "user_rating" not in column_names:conn.execute("ALTER TABLE view_history ADD COLUMN user_rating REAL")conn.execute("""CREATE INDEX IF NOT EXISTS idx_view_history_user_viewed_atON view_history (user_id, viewed_at DESC)""")conn.execute("""CREATE TABLE IF NOT EXISTS emotion_events (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id TEXT NOT NULL,text TEXT,emotion TEXT NOT NULL,analyzed_at TEXT NOT NULL)""")conn.execute("""CREATE INDEX IF NOT EXISTS idx_emotion_events_user_analyzed_atON emotion_events (user_id, analyzed_at DESC)""")conn.execute("""CREATE TABLE IF NOT EXISTS recommendation_cycles (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id TEXT NOT NULL,pre_text TEXT,pre_emotion TEXT NOT NULL,pre_valence TEXT NOT NULL,recommendation_mode TEXT NOT NULL,created_at TEXT NOT NULL,selected_movie_id TEXT,selected_movie_title TEXT,post_text TEXT,post_emotion TEXT,post_valence TEXT,post_analyzed_at TEXT)""")conn.execute("""CREATE INDEX IF NOT EXISTS idx_recommendation_cycles_user_created_atON recommendation_cycles (user_id, created_at DESC)""")conn.commit()print("Cargando modelo...")3 unmodified linestop_k=None,device=-1,)MOVIES_DF = load_movies_dataset()init_history_db()print(f"Listo. Dataset de recomendaciones: {len(MOVIES_DF)} peliculas")@app.route("/analizar", methods=["POST"])def analizar():texto = request.json.get("texto", "")user_id = str(request.json.get("user_id", "")).strip()previous_event = get_last_emotion_event(user_id)analyzed_at = datetime.now(timezone.utc).isoformat()resultado = sorted(clf(texto)[0], key=lambda x: x["score"], reverse=True)dominant_model = resultado[0]["label"] if resultado else "others"dominant_es = EMOTION_MAP.get(dominant_model, "neutral")dominant_valence = emotion_to_valence(dominant_es)recomendaciones = recommend_movies(dominant_es, user_id=user_id, limit=12)recommendation_mode = "diferente" if dominant_es in POSITIVE_EMOTIONS else "similar"cycle_id = create_recommendation_cycle(user_id=user_id,pre_text=texto,pre_emotion=dominant_es,recommendation_mode=recommendation_mode,created_at=analyzed_at,)save_emotion_event(user_id=user_id, text=texto, emotion=dominant_es, analyzed_at=analyzed_at)transition_movie = Noneif previous_event:transition_movie = get_last_viewed_between(user_id=user_id,start_iso=previous_event.get("analyzed_at", ""),end_iso=analyzed_at,)chatbot_text, chatbot_source = generate_chatbot_text(dominant_emotion=dominant_es,recommendation_mode=recommendation_mode,recommendations=recomendaciones,previous_event=previous_event,transition_movie=transition_movie,)return jsonify({"emociones": resultado,"emocion_dominante": dominant_es,"valencia_dominante": dominant_valence,"emocion_anterior": previous_event.get("emotion") if previous_event else None,"modo_recomendacion": recommendation_mode,"ciclo_recomendacion_id": cycle_id,"chatbot_texto": chatbot_text,"chatbot_fuente": chatbot_source,"pelicula_transicion": transition_movie,"recomendaciones": recomendaciones,})@app.route("/recomendacion/seguimiento", methods=["POST"])def seguimiento_recomendacion():payload = request.json or {}user_id = str(payload.get("user_id", "")).strip()post_text = str(payload.get("texto_post", "")).strip()movie_id = str(payload.get("movie_id", "")).strip()movie_title = str(payload.get("title", "")).strip()try:cycle_id = int(payload.get("ciclo_recomendacion_id", 0))except (TypeError, ValueError):cycle_id = 0if not user_id or not cycle_id or not post_text:return jsonify({"error": "user_id, ciclo_recomendacion_id y texto_post son obligatorios"}), 400cycle = get_recommendation_cycle(cycle_id=cycle_id, user_id=user_id)if not cycle:return jsonify({"error": "ciclo de recomendacion no encontrado"}), 404analyzed_at = datetime.now(timezone.utc).isoformat()result_post = sorted(clf(post_text)[0], key=lambda x: x["score"], reverse=True)post_model = result_post[0]["label"] if result_post else "others"post_emotion = EMOTION_MAP.get(post_model, "neutral")post_valence = emotion_to_valence(post_emotion)save_emotion_event(user_id=user_id, text=post_text, emotion=post_emotion, analyzed_at=analyzed_at)save_post_recommendation_state(cycle_id=cycle_id,user_id=user_id,post_text=post_text,post_emotion=post_emotion,post_analyzed_at=analyzed_at,movie_id=movie_id,movie_title=movie_title,)return jsonify({"ciclo_recomendacion_id": cycle_id,"movie_id": movie_id,"title": movie_title,"pre_emotion": cycle.get("pre_emotion"),"pre_valence": cycle.get("pre_valence"),"post_emotion": post_emotion,"post_valence": post_valence,"cambio_emocional": cycle.get("pre_emotion") != post_emotion,"cambio_valencia": cycle.get("pre_valence") != post_valence,"emociones_post": result_post,})@app.route("/historial/visto", methods=["POST"])def guardar_visto():payload = request.json or {}user_id = str(payload.get("user_id", "")).strip()movie_id = str(payload.get("movie_id", "")).strip()if not user_id or not movie_id:return jsonify({"error": "user_id y movie_id son obligatorios"}), 400viewed_at = datetime.now(timezone.utc).isoformat()title = str(payload.get("title", "")).strip()emotion = str(payload.get("emotion", "")).strip()session_text = str(payload.get("session_text", "")).strip()user_rating_raw = payload.get("user_rating")user_rating = Noneif user_rating_raw is not None and str(user_rating_raw).strip() != "":try:user_rating = float(user_rating_raw)except (TypeError, ValueError):return jsonify({"error": "user_rating debe ser numerica entre 1 y 5"}), 400if user_rating < 1 or user_rating > 5:return jsonify({"error": "user_rating debe estar entre 1 y 5"}), 400with get_db_connection() as conn:cur = conn.execute("""INSERT INTO view_history (user_id, movie_id, title, emotion, user_rating, session_text, viewed_at)VALUES (?, ?, ?, ?, ?, ?, ?)""",(user_id, movie_id, title, emotion, user_rating, session_text, viewed_at),)conn.commit()inserted_id = cur.lastrowidreturn jsonify({"id": inserted_id,"user_id": user_id,"movie_id": movie_id,"title": title,"emotion": emotion,"user_rating": user_rating,"session_text": session_text,"viewed_at": viewed_at,}), 201@app.route("/historial", methods=["GET"])def obtener_historial():user_id = str(request.args.get("user_id", "")).strip()if not user_id:return jsonify({"error": "user_id es obligatorio"}), 400try:limit = int(request.args.get("limit", 30))except ValueError:limit = 30limit = max(1, min(limit, 200))with get_db_connection() as conn:rows = conn.execute("""SELECT id, user_id, movie_id, title, emotion, user_rating, session_text, viewed_atFROM view_historyWHERE user_id = ?ORDER BY viewed_at DESCLIMIT ?""",(user_id, limit),).fetchall()historial = [dict(row) for row in rows]return jsonify({"items": historial, "count": len(historial)})@app.route("/historial/transiciones", methods=["GET"])def obtener_transiciones():user_id = str(request.args.get("user_id", "")).strip()if not user_id:return jsonify({"error": "user_id es obligatorio"}), 400try:limit = int(request.args.get("limit", 20))except ValueError:limit = 20limit = max(1, min(limit, 100))with get_db_connection() as conn:event_rows = conn.execute("""SELECT id, user_id, text, emotion, analyzed_atFROM emotion_eventsWHERE user_id = ?ORDER BY analyzed_at ASCLIMIT 500""",(user_id,),).fetchall()view_rows = conn.execute("""SELECT movie_id, title, viewed_atFROM view_historyWHERE user_id = ?ORDER BY viewed_at ASCLIMIT 1000""",(user_id,),).fetchall()events = [dict(row) for row in event_rows]views = [dict(row) for row in view_rows]transition_counter: dict[tuple[str, str, str, str], int] = {}for idx in range(1, len(events)):prev_event = events[idx - 1]curr_event = events[idx]if prev_event.get("emotion") == curr_event.get("emotion"):continuestart = prev_event.get("analyzed_at", "")end = curr_event.get("analyzed_at", "")matched_movie = Nonefor view in reversed(views):viewed_at = view.get("viewed_at", "")if start < viewed_at <= end:matched_movie = viewbreakif not matched_movie:continuekey = (str(matched_movie.get("movie_id", "")),matched_movie.get("title") or "",prev_event.get("emotion", ""),curr_event.get("emotion", ""),)transition_counter[key] = transition_counter.get(key, 0) + 1items = []for (movie_id, title, from_emotion, to_emotion), count in transition_counter.items():items.append({"movie_id": movie_id,"title": title,"from_emotion": from_emotion,"to_emotion": to_emotion,"count": count,})items.sort(key=lambda x: x["count"], reverse=True)return jsonify({"items": items[:limit], "count": len(items)})if __name__ == "__main__":app.run(port=5000)
123456789101112<!DOCTYPE html><html lang="es"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Analizador de Emociones</title> <script type="module" crossorigin src="/assets/index-deVpqPI7.js"></script> </head> <body> <div id="root"></div> </body></html>12349 unmodified lines1415161718196 unmodified lines262728293031321 unmodified line343536373839404110 unmodified lines5253545556577 unmodified lines6566676869709 unmodified lines80818283848586878811 unmodified lines1001011021031041051061 unmodified line10810911011111211311411511611711811912038 unmodified lines1591601611621631641651661677 unmodified lines175176177178179180181182183import { useState } from "react";const EMOTIONS = {joy: { label: "Alegría", emoji: "😄", color: "#FFD93D" },9 unmodified linesconst [messages, setMessages] = useState([]);const [input, setInput] = useState("");const [loading, setLoading] = useState(false);async function analyze() {if (!input.trim() || loading) return;6 unmodified linesconst res = await fetch("http://localhost:5000/analizar", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ texto: text }),});const data = await res.json();setMessages(prev => [1 unmodified line{type: "result",text,emotions: data.emociones || [],dominantEmotion: data.emocion_dominante || "neutral",recommendations: data.recomendaciones || [],},]);10 unmodified linesreturn { ...info, score: top.score };};return (<div style={styles.page}><header style={styles.header}>7 unmodified lines</header><div style={styles.feed}>{messages.length === 0 && (<div style={styles.empty}><div style={{ fontSize: 48 }}>💬</div>9 unmodified linesreturn (<div key={i} style={{ ...styles.card, borderColor: dom.color }}><div style={styles.cardText}>"{msg.text}"</div><div style={{ ...styles.dominantBadge, background: dom.color + "22", color: dom.color }}>{dom.emoji} {dom.label} — {(dom.score * 100).toFixed(1)}%</div><div style={styles.bars}>{msg.emotions.map((e) => {const info = EMOTIONS[e.label] || EMOTIONS.others;11 unmodified lines<div style={styles.recoSection}><div style={styles.recoTitle}>Peliculas recomendadas para: <strong>{msg.dominantEmotion}</strong></div>{msg.recommendations.length === 0 ? (<div style={styles.recoEmpty}>No hay recomendaciones disponibles.</div>1 unmodified line<ul style={styles.recoList}>{msg.recommendations.slice(0, 8).map((movie) => (<li key={movie.movieId} style={styles.recoItem}><span style={styles.recoMovie}>{movie.title}</span><span style={styles.recoGenres}>{movie.genres}</span></li>))}</ul>)}</div></div>);}38 unmodified linessubtitle: { fontSize: 11, color: "#64748b", letterSpacing: 1, textTransform: "uppercase" },feed: { flex: 1, overflowY: "auto", padding: 20, display: "flex", flexDirection: "column", gap: 16 },empty: { textAlign: "center", color: "#475569", marginTop: 60, lineHeight: 2 },card: { background: "#1e2535", borderRadius: 12, padding: 20, border: "1px solid #334155", borderLeft: "4px solid" },cardText: { fontSize: 15, color: "#cbd5e1", marginBottom: 12, fontStyle: "italic" },dominantBadge: { display: "inline-block", padding: "4px 12px", borderRadius: 20, fontSize: 14, fontWeight: "bold", marginBottom: 14 },bars: { display: "flex", flexDirection: "column", gap: 8 },barRow: { display: "flex", alignItems: "center", gap: 8 },barLabel: { width: 110, fontSize: 12, color: "#94a3b8" },7 unmodified linesrecoTitle: { fontSize: 13, color: "#cbd5e1", marginBottom: 10 },recoEmpty: { fontSize: 12, color: "#64748b" },recoList: { margin: 0, paddingLeft: 18, display: "flex", flexDirection: "column", gap: 6 },recoItem: { fontSize: 12, color: "#cbd5e1" },recoMovie: { fontWeight: "bold", marginRight: 6 },recoGenres: { color: "#94a3b8" },inputArea: { display: "flex", gap: 10, padding: "14px 20px", borderTop: "1px solid #1e2535", background: "#0f1117" },textarea: { flex: 1, background: "#1e2535", border: "1px solid #334155", borderRadius: 10, color: "#e2e8f0", padding: "10px 14px", fontSize: 14, resize: "none", fontFamily: "inherit", outline: "none" },sendBtn: { background: "#FFD93D", color: "#0f1117", border: "none", borderRadius: 10, padding: "0 20px", fontWeight: "bold", cursor: "pointer", fontSize: 14 },12349 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455566 unmodified lines636465666768691 unmodified line717273747576777879808182838410 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711727 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012029 unmodified lines21221321421521621721821922022122222322422522622722822911 unmodified lines2412422432442452462471 unmodified line24925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428538 unmodified lines3243253263273283293303313323333343353363373383393407 unmodified lines348349350351352353354355356357358359import { useEffect, useMemo, useState } from "react";const EMOTIONS = {joy: { label: "Alegría", emoji: "😄", color: "#FFD93D" },9 unmodified linesconst [messages, setMessages] = useState([]);const [input, setInput] = useState("");const [loading, setLoading] = useState(false);const [userId, setUserId] = useState("");const [history, setHistory] = useState([]);const [followupByCycle, setFollowupByCycle] = useState({});useEffect(() => {const existing = localStorage.getItem("vs_user_id");if (existing) {setUserId(existing);return;}const generated =typeof crypto !== "undefined" && crypto.randomUUID? crypto.randomUUID(): `anon_${Date.now()}_${Math.random().toString(16).slice(2)}`;localStorage.setItem("vs_user_id", generated);setUserId(generated);}, []);useEffect(() => {if (!userId) return;async function fetchHistory() {try {const res = await fetch(`http://localhost:5000/historial?user_id=${encodeURIComponent(userId)}&limit=20`);const data = await res.json();setHistory(data.items || []);} catch {setHistory([]);}}fetchHistory();}, [userId]);async function analyze() {if (!input.trim() || loading) return;6 unmodified linesconst res = await fetch("http://localhost:5000/analizar", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ texto: text, user_id: userId }),});const data = await res.json();setMessages(prev => [1 unmodified line{type: "result",text,chatbotText: data.chatbot_texto || "",emotions: data.emociones || [],dominantEmotion: data.emocion_dominante || "neutral",dominantValence: data.valencia_dominante || "neutro",previousEmotion: data.emocion_anterior || null,transitionMovie: data.pelicula_transicion || null,recommendationMode: data.modo_recomendacion || "similar",recommendationCycleId: data.ciclo_recomendacion_id || null,recommendations: data.recomendaciones || [],},]);10 unmodified linesreturn { ...info, score: top.score };};const viewedMovieIds = useMemo(() => {return new Set(history.map((item) => String(item.movie_id)));}, [history]);function askMovieRating() {const raw = window.prompt("Valora la pelicula recomendada del 1 al 5 (puedes usar decimales)");if (raw === null) return null;const value = Number(raw.trim());if (!Number.isFinite(value) || value < 1 || value > 5) {window.alert("La valoracion debe ser un numero entre 1 y 5.");return null;}return Math.round(value * 10) / 10;}async function markAsViewed(movie, dominantEmotion, sourceText, recommendationCycleId) {if (!userId) return;const rating = askMovieRating();if (rating === null) return;const payload = {user_id: userId,movie_id: String(movie.movieId),title: movie.title || "",emotion: dominantEmotion || "",user_rating: rating,session_text: sourceText || "",};try {const res = await fetch("http://localhost:5000/historial/visto", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(payload),});if (!res.ok) return;const saved = await res.json();setHistory((prev) => [saved, ...prev].slice(0, 20));const postText = window.prompt("Despues de ver la recomendacion, como te sientes ahora?");if (!postText || !postText.trim() || !recommendationCycleId) return;const followupRes = await fetch("http://localhost:5000/recomendacion/seguimiento", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({user_id: userId,ciclo_recomendacion_id: recommendationCycleId,movie_id: String(movie.movieId),title: movie.title || "",texto_post: postText.trim(),}),});if (!followupRes.ok) return;const followupData = await followupRes.json();setFollowupByCycle((prev) => ({...prev,[String(recommendationCycleId)]: followupData,}));} catch {// No bloquea la experiencia principal del chat si falla el historial.}}return (<div style={styles.page}><header style={styles.header}>7 unmodified lines</header><div style={styles.feed}>{history.length > 0 && (<div style={styles.historyCard}><div style={styles.historyTitle}>Tu historial de visualizacion</div><ul style={styles.historyList}>{history.slice(0, 6).map((item) => (<li key={item.id} style={styles.historyItem}><span style={styles.historyMovie}>{item.title || item.movie_id}</span><span style={styles.historyMeta}>{item.emotion || "neutral"}{item.user_rating != null ? ` · ${item.user_rating}/5` : ""}</span></li>))}</ul></div>)}{messages.length === 0 && (<div style={styles.empty}><div style={{ fontSize: 48 }}>💬</div>9 unmodified linesreturn (<div key={i} style={{ ...styles.card, borderColor: dom.color }}><div style={styles.cardText}>"{msg.text}"</div>{msg.chatbotText && <div style={styles.botText}>{msg.chatbotText}</div>}<div style={{ ...styles.dominantBadge, background: dom.color + "22", color: dom.color }}>{dom.emoji} {dom.label} — {(dom.score * 100).toFixed(1)}% · valencia {msg.dominantValence}</div>{msg.previousEmotion && (<div style={styles.transitionHint}>Transicion detectada: <strong>{msg.previousEmotion}</strong> → <strong>{msg.dominantEmotion}</strong>{msg.transitionMovie?.title ? ` (pelicula asociada: ${msg.transitionMovie.title})` : ""}</div>)}<div style={styles.bars}>{msg.emotions.map((e) => {const info = EMOTIONS[e.label] || EMOTIONS.others;11 unmodified lines<div style={styles.recoSection}><div style={styles.recoTitle}>Peliculas recomendadas para: <strong>{msg.dominantEmotion}</strong> ({msg.recommendationMode})</div>{msg.recommendations.length === 0 ? (<div style={styles.recoEmpty}>No hay recomendaciones disponibles.</div>1 unmodified line<ul style={styles.recoList}>{msg.recommendations.slice(0, 8).map((movie) => (<li key={movie.movieId} style={styles.recoItem}><div style={styles.recoMain}><span style={styles.recoMovie}>{movie.title}</span><span style={styles.recoGenres}>{movie.genres}</span></div><buttonstyle={styles.viewBtn}onClick={() => markAsViewed(movie, msg.dominantEmotion, msg.text, msg.recommendationCycleId)}disabled={viewedMovieIds.has(String(movie.movieId))}>{viewedMovieIds.has(String(movie.movieId)) ? "Vista" : "Marcar vista"}</button></li>))}</ul>)}</div>{msg.recommendationCycleId && followupByCycle[String(msg.recommendationCycleId)] && (<div style={styles.followupCard}><div>Seguimiento circunflejo: <strong>{followupByCycle[String(msg.recommendationCycleId)].pre_emotion}</strong>({followupByCycle[String(msg.recommendationCycleId)].pre_valence}) →<strong> {followupByCycle[String(msg.recommendationCycleId)].post_emotion}</strong>({followupByCycle[String(msg.recommendationCycleId)].post_valence})</div><div>Cambio emocional: {followupByCycle[String(msg.recommendationCycleId)].cambio_emocional ? "si" : "no"} ·Cambio valencia: {followupByCycle[String(msg.recommendationCycleId)].cambio_valencia ? "si" : "no"}</div></div>)}</div>);}38 unmodified linessubtitle: { fontSize: 11, color: "#64748b", letterSpacing: 1, textTransform: "uppercase" },feed: { flex: 1, overflowY: "auto", padding: 20, display: "flex", flexDirection: "column", gap: 16 },empty: { textAlign: "center", color: "#475569", marginTop: 60, lineHeight: 2 },historyCard: { background: "#1e2535", borderRadius: 12, padding: 14, border: "1px solid #334155" },historyTitle: { fontSize: 13, color: "#cbd5e1", marginBottom: 8, fontWeight: "bold" },historyList: { margin: 0, paddingLeft: 18, display: "flex", flexDirection: "column", gap: 6 },historyItem: { display: "flex", justifyContent: "space-between", gap: 8, fontSize: 12, color: "#cbd5e1" },historyMovie: { fontWeight: "bold" },historyMeta: { color: "#94a3b8", textTransform: "capitalize" },card: { background: "#1e2535", borderRadius: 12, padding: 20, border: "1px solid #334155", borderLeft: "4px solid" },cardText: { fontSize: 15, color: "#cbd5e1", marginBottom: 12, fontStyle: "italic" },botText: { fontSize: 13, color: "#dbeafe", background: "#1d4ed822", border: "1px solid #1d4ed855", borderRadius: 8, padding: "10px 12px", marginBottom: 12, lineHeight: 1.4 },dominantBadge: { display: "inline-block", padding: "4px 12px", borderRadius: 20, fontSize: 14, fontWeight: "bold", marginBottom: 14 },transitionHint: { marginBottom: 10, fontSize: 12, color: "#cbd5e1", background: "#0ea5e922", border: "1px solid #0ea5e955", borderRadius: 8, padding: "8px 10px" },bars: { display: "flex", flexDirection: "column", gap: 8 },barRow: { display: "flex", alignItems: "center", gap: 8 },barLabel: { width: 110, fontSize: 12, color: "#94a3b8" },7 unmodified linesrecoTitle: { fontSize: 13, color: "#cbd5e1", marginBottom: 10 },recoEmpty: { fontSize: 12, color: "#64748b" },recoList: { margin: 0, paddingLeft: 18, display: "flex", flexDirection: "column", gap: 6 },recoItem: { fontSize: 12, color: "#cbd5e1", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 },recoMain: { display: "flex", flexDirection: "column", gap: 3 },recoMovie: { fontWeight: "bold", marginRight: 6 },recoGenres: { color: "#94a3b8" },viewBtn: { background: "#334155", border: "1px solid #475569", color: "#e2e8f0", borderRadius: 8, padding: "4px 8px", fontSize: 11, cursor: "pointer" },followupCard: { marginTop: 12, fontSize: 12, color: "#e2e8f0", background: "#22c55e22", border: "1px solid #22c55e55", borderRadius: 8, padding: "8px 10px", display: "flex", flexDirection: "column", gap: 4 },inputArea: { display: "flex", gap: 10, padding: "14px 20px", borderTop: "1px solid #1e2535", background: "#0f1117" },textarea: { flex: 1, background: "#1e2535", border: "1px solid #334155", borderRadius: 10, color: "#e2e8f0", padding: "10px 14px", fontSize: 14, resize: "none", fontFamily: "inherit", outline: "none" },sendBtn: { background: "#FFD93D", color: "#0f1117", border: "none", borderRadius: 10, padding: "0 20px", fontWeight: "bold", cursor: "pointer", fontSize: 14 },
123456789101112131415161718192021222324252627282930313233flowchart TD A[Usuario escribe texto en chat] --> B[POST analizar] B --> C[Modelo emocion pysentimiento] C --> D[Mapeo a emocion ES y valencia] D --> E[recommend_movies]
E --> F{Hay historial} F -- No --> G[Filtrar por emocion y calidad] F -- Si --> H[Perfil historial vistas y gustadas]
H --> I{Estado actual} I -- Positivo --> J[Priorizar peliculas nuevas] I -- Negativo --> K[Priorizar similares a gustadas]
G --> L[Crear ciclo recomendacion pre] J --> L K --> L
L --> M[Guardar emotion event pre] M --> N[Generar texto con Ollama llama3.2] N --> O[Respuesta frontend con ciclo_id]
O --> P[Usuario marca vista] P --> Q[Pedir valoracion 1 a 5] Q --> R[POST historial visto con user_rating]
R --> S[Pedir estado posterior] S --> T[POST recomendacion seguimiento] T --> U[Analizar texto posterior y valencia] U --> V[Actualizar ciclo con estado post] V --> W[Mostrar transicion emocional y valencia]
W --> X[Datos para recomendaciones futuras]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051flowchart TD U[Frontend React emotionchat.jsx] -->|POST analizar texto y user_id| A[backend.server.analizar]
subgraph Analisis_Pre A --> B[clf text classification pysentimiento robertuito] B --> C[EMOTION_MAP a emocion_es] C --> D[emotion_to_valence] C --> E[recommend_movies emotion_es user_id] A --> F[create_recommendation_cycle] A --> G[save_emotion_event pre] A --> H[generate_chatbot_text] H --> I{Ollama disponible} I -- si --> J[chatbot_fuente ollama] I -- no --> K[chatbot_fuente template_fallback] end
subgraph Motor_Recomendacion E --> R1[Filtrar MOVIES_DF por estados_emocionales] R1 --> R2{Existe historial user_id} R2 -- no --> R3[Top calidad rating_count rating_mean] R2 -- si --> R4[_get_user_history_rows movie_id user_rating] R4 --> R5[_build_history_profile viewed_ids viewed_genres liked_genres] R5 --> R6{emotion_es positiva} R6 -- si --> R7[reference_genres viewed_genres priorizar novedad] R6 -- no --> R8[reference_genres liked_genres o viewed priorizar similitud] R7 --> R9[rank por similarity y quality] R8 --> R9 end
J --> Z[JSON respuesta analizar] K --> Z R3 --> Z R9 --> Z
Z --> U2[UI render tarjetas y boton Marcar vista] U2 -->|POST historial visto user_rating| V[backend.server.guardar_visto] V --> DB1[(view_history)]
U2 -->|POST recomendacion seguimiento texto_post| S[backend.server.seguimiento_recomendacion] S --> S1[clf sobre texto_post] S1 --> S2[post_emotion y post_valence] S --> S3[save_emotion_event post] S --> S4[save_post_recommendation_state] S3 --> DB2[(emotion_events)] S4 --> DB3[(recommendation_cycles)] S --> SR[JSON pre_valence post_valence cambio_valencia] SR --> U3[UI muestra transicion pre a post]
DB1 --> T1[GET historial] DB2 --> T2[GET historial transiciones] DB3 --> T2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354sequenceDiagram autonumber participant UI as Frontend EmotionChat participant API as Flask API backend/server.py participant CLF as Clasificador Emocion participant REC as Motor Recomendacion participant OLL as Ollama llama3.2 participant DBV as DB view_history participant DBE as DB emotion_events participant DBC as DB recommendation_cycles
UI->>API: POST /analizar (texto, user_id) API->>CLF: clf(texto) CLF-->>API: scores emociones API->>API: EMOTION_MAP + emotion_to_valence
API->>REC: recommend_movies(emotion_es, user_id) REC->>DBV: SELECT movie_id, user_rating por user_id DBV-->>REC: historial vistas y valoradas REC-->>API: recomendaciones rankeadas
API->>DBC: INSERT ciclo pre (pre_emotion, pre_valence, mode) API->>DBE: INSERT emotion_event pre
API->>OLL: POST /api/generate (prompt tecnico) OLL-->>API: chatbot_texto
API-->>UI: JSON analizar (emocion, valencia, recomendaciones, ciclo_id, texto)
UI->>UI: Usuario pulsa Marcar vista UI->>UI: Prompt valoracion pelicula (1..5) UI->>API: POST /historial/visto (movie_id, user_rating, emotion, session_text) API->>DBV: INSERT view_history DBV-->>API: ok API-->>UI: movie guardada
UI->>UI: Prompt estado posterior (texto_post) UI->>API: POST /recomendacion/seguimiento (ciclo_id, texto_post, movie) API->>CLF: clf(texto_post) CLF-->>API: scores emociones post API->>API: post_emotion + post_valence API->>DBE: INSERT emotion_event post API->>DBC: UPDATE ciclo con pelicula y estado post API-->>UI: JSON seguimiento (pre vs post, cambio_valencia)
UI->>API: GET /historial API->>DBV: SELECT historial con user_rating DBV-->>API: filas historial API-->>UI: items historial
UI->>API: GET /historial/transiciones API->>DBE: SELECT emotion_events API->>DBV: SELECT view_history API-->>UI: agregados de transiciones por peliculabackend/server.py+683-12
chatbot/dist/index.htmlAdded+12
chatbot/src/components/emotionchat.jsx+183-7
graphics/flowchart TD.mmdAdded+33
graphics/flowchart_funciones.mmdAdded+51
graphics/sequence_funciones.mmdAdded+54