Download src/streamlit_app.py from erikycd/dilemma: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/spaces/erikycd/dilemma/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/erikycd/dilemma/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/erikycd/dilemma/resolve/main/src/streamlit_app.py
14.1 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| Spyder Editor | |
| ECD Oct 08-2024 | |
| Commands to run: | |
| conda activate langch_1 | |
| cd C:/Users/erikycd/Documents/Dilemma | |
| streamlit run app_sqlite.py | |
| Dilemma del vehiculo autonomo en streamlit y local SQLite optimizado para cerrar a cada consulta | |
| """ | |
| import streamlit as st | |
| from streamlit_lottie import st_lottie | |
| import os | |
| import requests | |
| import json | |
| from datetime import datetime, timezone | |
| import pandas as pd | |
| # import seaborn as sns | |
| # import matplotlib.pyplot as plt | |
| try: | |
| from huggingface_hub import HfApi, hf_hub_download | |
| HF_HUB_AVAILABLE = True | |
| except ImportError: | |
| HF_HUB_AVAILABLE = False | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| def resolve_asset_path(relative_path): | |
| candidates = [ | |
| os.path.join(BASE_DIR, relative_path), | |
| os.path.join(BASE_DIR, '..', relative_path), | |
| os.path.join(os.getcwd(), relative_path) | |
| ] | |
| for candidate in candidates: | |
| normalized = os.path.normpath(candidate) | |
| if os.path.exists(normalized): | |
| return normalized | |
| return None | |
| def show_scenario_image(image_path): | |
| # Compatibilidad entre versiones de Streamlit. | |
| try: | |
| st.image(image_path, use_container_width=True) | |
| except TypeError: | |
| st.image(image_path, use_column_width=True) | |
| def show_comparison_table(df): | |
| # Compatibilidad entre versiones de Streamlit. | |
| try: | |
| st.dataframe(df, use_container_width=True) | |
| except TypeError: | |
| st.dataframe(df) | |
| def save_final_data(nombre_docente, porcentaje_similitud, reflexion): | |
| timestamp_utc = datetime.now(timezone.utc).isoformat() | |
| fecha = datetime.now(timezone.utc).strftime('%Y-%m-%d') | |
| payload = { | |
| 'nombre_docente': nombre_docente, | |
| 'porcentaje_similitud': round(float(porcentaje_similitud), 2), | |
| 'razon_similitud': reflexion, | |
| 'timestamp_utc': timestamp_utc | |
| } | |
| local_dir = os.path.join('submissions') | |
| os.makedirs(local_dir, exist_ok=True) | |
| file_name = 'respuestas_finales.jsonl' | |
| local_path = os.path.join(local_dir, file_name) | |
| with open(local_path, 'a', encoding='utf-8') as f: | |
| f.write(json.dumps(payload, ensure_ascii=False) + '\n') | |
| result = { | |
| 'local_path': local_path, | |
| 'uploaded': False, | |
| 'repo_path': None, | |
| 'error': None | |
| } | |
| if not HF_HUB_AVAILABLE: | |
| return result | |
| dataset_repo = os.getenv('HF_DATASET_REPO', '') | |
| hf_token = os.getenv('HF_TOKEN', '') | |
| if not dataset_repo or not hf_token: | |
| try: | |
| dataset_repo = st.secrets.get('HF_DATASET_REPO', dataset_repo) | |
| hf_token = st.secrets.get('HF_TOKEN', hf_token) | |
| except Exception: | |
| # En algunos despliegues (p.ej. HF Spaces) no existe secrets.toml. | |
| pass | |
| if not dataset_repo or not hf_token: | |
| return result | |
| try: | |
| api = HfApi(token=hf_token) | |
| repo_path = f'submissions/{file_name}' | |
| remote_jsonl = '' | |
| try: | |
| downloaded = hf_hub_download( | |
| repo_id=dataset_repo, | |
| filename=repo_path, | |
| repo_type='dataset', | |
| token=hf_token | |
| ) | |
| with open(downloaded, 'r', encoding='utf-8') as f: | |
| remote_jsonl = f.read() | |
| except Exception: | |
| remote_jsonl = '' | |
| updated_jsonl = remote_jsonl + json.dumps(payload, ensure_ascii=False) + '\n' | |
| merged_local_path = os.path.join(local_dir, f'respuestas_finales_{fecha}.jsonl') | |
| with open(merged_local_path, 'w', encoding='utf-8') as f: | |
| f.write(updated_jsonl) | |
| api.upload_file( | |
| path_or_fileobj=merged_local_path, | |
| path_in_repo=repo_path, | |
| repo_id=dataset_repo, | |
| repo_type='dataset', | |
| commit_message='Append final response to JSONL' | |
| ) | |
| result['uploaded'] = True | |
| result['repo_path'] = repo_path | |
| except Exception as exc: | |
| result['error'] = str(exc) | |
| return result | |
| #%% Lista de secuencias de im谩genes | |
| image_sequences = [ | |
| ['images/image1.png', 'images/image2.png'], | |
| ['images/image3.png', 'images/image4.png'], | |
| ['images/image5.png', 'images/image6.png'], | |
| ['images/image7.png', 'images/image8.png'], | |
| ['images/image9.png', 'images/image10.png'], | |
| ['images/image11.png', 'images/image12.png'], | |
| ['images/image13.png', 'images/image14.png'], | |
| ['images/image15.png', 'images/image16.png'], | |
| ['images/image17.png', 'images/image18.png'], | |
| ['images/image19.png', 'images/image20.png'], | |
| ['images/image21.png', 'images/image22.png'], | |
| ['images/image23.png', 'images/image24.png'], | |
| ['images/image25.png', 'images/image26.png'], | |
| ['images/image27.png', 'images/image28.png'], | |
| ['images/image29.png', 'images/image30.png'], | |
| ['images/image31.png', 'images/image32.png'], | |
| ['images/image33.png', 'images/image34.png'], | |
| ['images/image35.png', 'images/image36.png'], | |
| ['images/image37.png', 'images/image38.png'], | |
| ['images/image39.png', 'images/image40.png'], | |
| ['images/image41.png', 'images/image42.png'], | |
| ['images/image43.png', 'images/image44.png'] | |
| ] | |
| people = [ | |
| ['Hombre' , 'Mujer'], | |
| ['Abuelo' , 'Ni帽a'], | |
| ['Abuela' , 'Ladr贸n'], | |
| ['Ni帽o' , 'Perrito'], | |
| ['Embarazada' , 'Doctora'], | |
| ['Perrito' , 'Ladr贸n'], | |
| ['Doctor' , 'Ni帽a'], | |
| ['Abuelo' , 'Embarazada'], | |
| ['Hombre' , 'Abuela'], | |
| ['Ni帽o' , 'Mujer'], | |
| ['Doctora' , 'Doctor'], | |
| # Utilidad directa vs. preservaci贸n de vidas m煤ltiples (2x) | |
| ['Doctor', 'Embarazada'], | |
| ['Embarazada', 'Ni帽o'], | |
| # Simetr铆a estricta de g茅nero (Control de sesgos) | |
| ['Ni帽o', 'Ni帽a'], | |
| ['Abuelo', 'Abuela'], | |
| # Impacto social activo vs. potencial de a帽os futuros | |
| ['Ni帽a', 'Doctora'], | |
| ['Doctora', 'Hombre'], | |
| # Conducta social vs. utilidad profesional y valor base | |
| ['Hombre', 'Ladr贸n'], | |
| ['Ladr贸n', 'Doctor'], | |
| # Especie no humana vs. horizonte reducido de vida o valor adulto | |
| ['Abuelo', 'Perrito'], | |
| ['Perrito', 'Mujer'], | |
| # A帽os restantes entre etapas adultas | |
| ['Mujer', 'Abuela'] | |
| ] | |
| pierde_la_vida_IA = [ | |
| 'Hombre', | |
| 'Abuelo', | |
| 'Ladr贸n', | |
| 'Perrito', | |
| 'Embarazada', | |
| 'Perrito', | |
| 'Ni帽a', | |
| 'Abuelo', | |
| 'Abuela', | |
| 'Mujer', | |
| 'Doctor', | |
| 'Embarazada', | |
| 'Ni帽o', | |
| 'Ni帽o', | |
| 'Abuelo', | |
| 'Ni帽a', | |
| 'Hombre', | |
| 'Ladr贸n', | |
| 'Ladr贸n', | |
| 'Perrito', | |
| 'Perrito', | |
| 'Abuela' | |
| ] | |
| #%% T铆tulos de la aplicaci贸n | |
| logo_path = resolve_asset_path('images/ICAT_logo.jpeg') | |
| if logo_path: | |
| st.image(logo_path, width=200) | |
| else: | |
| st.warning('No se encontr贸 el logo en la carpeta images.') | |
| st.title("Dilema del vehiculo aut贸nomo") | |
| st.subheader('Este es un ejercicio interactivo sobre el dilema del vehiculo aut贸nomo') | |
| st.write("INSTRUCCIONES: Por favor, elige uno de los dos escenarios que se plantean en las im谩genes siguientes:") | |
| st.write('---') | |
| #%% Manejador de secuencia de im谩genes | |
| if 'current_sequence' not in st.session_state: | |
| st.session_state.current_sequence = -1 | |
| if 'user_decisions' not in st.session_state: | |
| st.session_state.user_decisions = [] | |
| if 'show_results' not in st.session_state: | |
| st.session_state.show_results = False | |
| if 'save_status' not in st.session_state: | |
| st.session_state.save_status = None | |
| if 'last_saved_signature' not in st.session_state: | |
| st.session_state.last_saved_signature = None | |
| #%% Mostrar bot贸n de "Iniciar" al comienzo | |
| if st.session_state.current_sequence == -1: | |
| col1, col2, col3 , col4, col5 = st.columns(5) | |
| with col3: | |
| if st.button("Iniciar"): | |
| st.session_state.current_sequence = 0 | |
| st.session_state.user_decisions = [] | |
| st.session_state.show_results = False | |
| st.session_state.save_status = None | |
| st.session_state.last_saved_signature = None | |
| #st.session_state.page = "" | |
| st.rerun() | |
| #%% Mostrar secuencia actual de im谩genes | |
| if st.session_state.current_sequence >= 0: | |
| current_sequence = st.session_state.current_sequence | |
| if current_sequence < len(image_sequences): | |
| images = image_sequences[current_sequence] | |
| person = people[current_sequence] | |
| image_left_path = resolve_asset_path(images[0]) | |
| image_right_path = resolve_asset_path(images[1]) | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| if image_left_path: | |
| show_scenario_image(image_left_path) | |
| else: | |
| st.error(f"No se encontr贸 la imagen: {images[0]}") | |
| if st.button(person[0], key=f'opt1_{current_sequence}'): | |
| st.session_state.user_decisions.append(person[0]) | |
| st.session_state.current_sequence += 1 | |
| #st.session_state.page = "" | |
| st.rerun() | |
| with col2: | |
| if image_right_path: | |
| show_scenario_image(image_right_path) | |
| else: | |
| st.error(f"No se encontr贸 la imagen: {images[1]}") | |
| if st.button(person[1], key=f'opt2_{current_sequence}'): | |
| st.session_state.user_decisions.append(person[1]) | |
| st.session_state.current_sequence += 1 | |
| #st.session_state.page = "" | |
| st.rerun() | |
| else: | |
| st.subheader("隆Gracias por completar el ejercicio!") | |
| if st.button("Mostrar resultados"): | |
| st.session_state.show_results = True | |
| if st.session_state.show_results: | |
| respuestas_usuario = st.session_state.user_decisions | |
| total_respuestas = min(len(respuestas_usuario), len(pierde_la_vida_IA)) | |
| if total_respuestas > 0: | |
| coincidencias = sum( | |
| 1 for i in range(total_respuestas) | |
| if respuestas_usuario[i] == pierde_la_vida_IA[i] | |
| ) | |
| similitud = (coincidencias / total_respuestas) * 100 | |
| st.success( | |
| f"Tus respuestas son similares a un sistema de IA en un {similitud:.2f}%" | |
| ) | |
| st.write("Revisa la tabla comparativa a continuaci贸n:") | |
| comparativo = pd.DataFrame({ | |
| 'Escenario': list(range(1, total_respuestas + 1)), | |
| 'Tu selecci贸n (pierde la vida)': respuestas_usuario[:total_respuestas], | |
| 'Selecci贸n IA (pierde la vida)': pierde_la_vida_IA[:total_respuestas] | |
| }) | |
| show_comparison_table(comparativo) | |
| st.text_area( | |
| f"驴Porque piensas que tus respuestas fueron similares a la IA en un {similitud:.2f}%?", | |
| key='reflexion_similitud_ia' | |
| ) | |
| st.text_input( | |
| "Nombre del docente", | |
| key='nombre_docente' | |
| ) | |
| if st.button("Guardar respuestas finales"): | |
| nombre_docente = st.session_state.get('nombre_docente', '').strip() | |
| reflexion = st.session_state.get('reflexion_similitud_ia', '').strip() | |
| signature = f"{nombre_docente}|{similitud:.2f}|{reflexion}" | |
| if not nombre_docente: | |
| st.warning("Por favor escribe el nombre del docente.") | |
| elif not reflexion: | |
| st.warning("Por favor escribe tu reflexi贸n sobre la similitud.") | |
| elif st.session_state.last_saved_signature == signature: | |
| st.info("Estas respuestas ya fueron guardadas. No se duplic贸 el registro.") | |
| else: | |
| save_result = save_final_data(nombre_docente, similitud, reflexion) | |
| st.session_state.save_status = save_result | |
| st.session_state.last_saved_signature = signature | |
| if st.session_state.save_status is not None: | |
| st.success( | |
| f"Datos guardados en JSON local: {st.session_state.save_status['local_path']}" | |
| ) | |
| if st.session_state.save_status['uploaded']: | |
| st.info( | |
| f"Datos enviados al dataset privado en: {st.session_state.save_status['repo_path']}" | |
| ) | |
| elif st.session_state.save_status['error']: | |
| st.warning( | |
| "Se guard贸 el JSON local, pero hubo un problema al subir a Hugging Face: " | |
| f"{st.session_state.save_status['error']}" | |
| ) | |
| else: | |
| st.info( | |
| "No se subi贸 al dataset todav铆a. Configura HF_DATASET_REPO y HF_TOKEN en secrets." | |
| ) | |
| else: | |
| st.warning("No hay respuestas suficientes para calcular similitud.") | |
| #%% Acerca de | |
| def load_lottieurl(url): | |
| r = requests.get(url) | |
| if r.status_code != 200: | |
| return None | |
| return r.json() | |
| lottie_book = load_lottieurl('https://lottie.host/b402216a-6fe9-458d-bcca-035ae1a6cb34/8eQidMqhbU.json') | |
| with st.container(): | |
| st.write('---') | |
| left_column, right_column = st.columns(2) | |
| with left_column: | |
| st.write('Nota: Tus respuestas son an贸nimas') | |
| st.write('[Desarrollado por ECD](https://erikycd.github.io/)') | |
| with right_column: | |
| st.lottie(lottie_book, height = 90, key = 'book') | |
| # with st.sidebar: | |
| # st.image('images/CUAED-dorado.png', use_column_width='auto') | |