Delete src
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- src/.streamlit/config.tomlDeleted-9
- src/23-7-2024_app.pyDeleted-62
- src/Test_app.pyDeleted-8
- src/app.pyDeleted-196
- src/assets/img/AIdeaTextCard.jpgDeleted
- src/assets/img/AIdeaText_Logo_vectores.pngDeleted
- src/assets/img/ALPHA_Startup Badges.pngDeleted
- src/assets/img/Ico-20x20.icoDeleted
- src/assets/img/Logo20x20.pngDeleted
- src/assets/img/Logo24x24.pngDeleted
- src/assets/img/Logo32x32.pngDeleted
- src/assets/img/Logo40x40.pngDeleted
- src/assets/img/Logo48x48.pngDeleted
- src/assets/img/Logo64x64.pngDeleted
- src/assets/img/Logo_100x100.pngDeleted
- src/assets/img/Logo_300x300.pngDeleted
- src/assets/img/Mesa de trabajo 1png 0.3.pngDeleted
- src/assets/img/aideaText-ICO.pngDeleted
- src/assets/img/aideaText-Logo-32x32.pngDeleted
- src/assets/img/aideaText_icon.icoDeleted
- src/assets/img/aideaText_logo.pngDeleted
- src/assets/img/assets_img_logo_92x92.icoDeleted
- src/assets/img/logo120x120.pngDeleted
- src/assets/img/logo_92x92.jpgDeleted
- src/assets/img/logo_92x92.pngDeleted
- src/assets/img/socialmedia/AIdeaTextCard.jpgDeleted
- src/assets/img/socialmedia/Facebook_CoverPhoto-1_820x312.jpgDeleted
- src/assets/img/socialmedia/Facebook_CoverPhoto_820x312.jpgDeleted
- src/assets/img/socialmedia/_MG_2535.jpgDeleted
- src/assets/img/socialmedia/_MG_2585.jpgDeleted
- src/assets/img/socialmedia/_MG_2587.jpgDeleted
- src/assets/img/socialmedia/_MG_2590.jpgDeleted
- src/assets/img/socialmedia/_MG_2678.jpgDeleted
- src/assets/img/socialmedia/_MG_2727.jpgDeleted
- src/assets/img/socialmedia/_MG_2735.jpgDeleted
- src/assets/img/socialmedia/_MG_2790.jpgDeleted
- src/assets/img/socialmedia/_MG_2845.JPGDeleted
- src/assets/img/socialmedia/txt.txtDeleted-1
- src/assets/img/text.txtDeleted
- src/modules/23-7-2024_auth.pyDeleted-135
- src/modules/23-7-2024_ui.pyDeleted-344
- src/modules/__init__.pyDeleted-319
- src/modules/__init__Old-V3.pyDeleted-180
- src/modules/__pycache__/__init__.cpython-311.pycDeleted
- src/modules/admin/__init__.pyDeleted
- src/modules/admin/__pycache__/__init__.cpython-311.pycDeleted
- src/modules/admin/__pycache__/admin_ui.cpython-311.pycDeleted
- src/modules/admin/admin_ui.pyDeleted-250
- src/modules/admin/txt.txtDeleted
- src/modules/auth/__init__.pyDeleted
123456789[server]port = 8501address = "0.0.0.0"maxUploadSize = 5 # Tamaño máximo en MBenableCORS = falseenableXsrfProtection = false
[browser]gatherUsageStats = false1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162## app.py
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import streamlit as st
from modules.database import initialize_mongodb_connection, get_student_data, store_analysis_result
from modules.auth import authenticate_user, get_user_role
from modules.ui import login_page, register_page, display_chat_interface, display_student_progress, display_text_analysis_interface
from modules.morpho_analysis import get_repeated_words_colors, highlight_repeated_words, POS_COLORS, POS_TRANSLATIONS
from modules.syntax_analysis import visualize_syntax
from modules.spacy_utils import load_spacy_models
st.set_page_config(page_title="AIdeaText", layout="wide", page_icon="random")
def main_app():
nlp_models = load_spacy_models()
languages = {'Español': 'es', 'English': 'en', 'Français': 'fr'}
selected_lang = st.sidebar.selectbox("Select Language / Seleccione el idioma / Choisissez la langue", list(languages.keys()))
lang_code = languages[selected_lang]
col1, col2 = st.columns([1, 2])
with col1:
display_chat_interface()
with col2:
st.markdown("### AIdeaText - Análisis morfológico y sintáctico")
if st.session_state.role == "Estudiante":
tabs = st.tabs(["Análisis de Texto", "Mi Progreso"])
with tabs[0]:
display_text_analysis_interface(nlp_models, lang_code)
with tabs[1]:
display_student_progress(st.session_state.username)
elif st.session_state.role == "Profesor":
st.write("Bienvenido, profesor. Aquí podrás ver el progreso de tus estudiantes.")
# Agregar lógica para mostrar el progreso de los estudiantes
def main():
if not initialize_mongodb_connection():
st.warning("La conexión a la base de datos MongoDB no está disponible. Algunas funciones pueden no estar operativas.")
if 'logged_in' not in st.session_state:
st.session_state.logged_in = False
if not st.session_state.logged_in:
menu = ["Iniciar Sesión", "Registrarse"]
choice = st.sidebar.selectbox("Menu", menu)
if choice == "Iniciar Sesión":
login_page()
elif choice == "Registrarse":
register_page()
else:
if st.sidebar.button("Cerrar Sesión"):
st.session_state.logged_in = False
st.rerun()
main_app()
if __name__ == "__main__":
main()12345678import streamlit as st
def main():
st.title("Test de Streamlit")
st.write("Si puedes ver esto, Streamlit está funcionando correctamente.")
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196# AIdeaText v3# app.pyimport osos.environ['TORCH_DISABLE_MLC'] = '1' # Desactiva la carga de componentes conflictivos
import streamlit as stfrom streamlit.runtime.scriptrunner import RerunException
import torchimport threading
import sys
from dotenv import load_dotenvfrom datetime import datetimefrom PIL import Image
import logging
# Configuración básicaload_dotenv()logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# Configuración básica de la páginast.set_page_config( page_title="AIdeaText", layout="wide", initial_sidebar_state="collapsed" # Para dar más espacio al logo)
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Importaciones localesfrom translations import get_translations, get_landing_translationsfrom session_state import initialize_session_statefrom modules.ui.ui import main as ui_mainfrom modules.utils.spacy_utils import load_spacy_modelsfrom modules.utils.widget_utils import generate_unique_key
# Importaciones de interfacesfrom modules.morphosyntax.morphosyntax_interface import ( display_morphosyntax_interface, display_arc_diagram #display_morphosyntax_results)
from modules.semantic.semantic_interface import ( display_semantic_interface, display_semantic_results)
from modules.discourse.discourse_interface import ( display_discourse_interface, display_discourse_results)
# Importaciones de base de datos
from modules.database.database_init import initialize_database_connections
from modules.database.sql_db import ( get_user, get_admin_user, get_student_user, get_teacher_user, create_user, create_student_user, create_teacher_user, create_admin_user, update_student_user, # Agregada delete_student_user, # Agregada record_login, record_logout, get_recent_sessions, get_user_total_time, store_application_request, store_student_feedback)
from modules.database.mongo_db import ( get_collection, insert_document, find_documents, update_document, delete_document)
from modules.database.morphosintax_mongo_db import ( store_student_morphosyntax_result, get_student_morphosyntax_analysis)
from modules.database.semantic_mongo_db import ( store_student_semantic_result, get_student_semantic_analysis)
from modules.database.chat_mongo_db import ( store_chat_history, get_chat_history)
# Importaciones de base de datosfrom modules.studentact.student_activities_v2 import display_student_activitiesfrom modules.studentact.current_situation_interface import display_current_situation_interface
from modules.auth.auth import ( authenticate_student, register_student, update_student_info, delete_student)from modules.admin.admin_ui import admin_page
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
@st.cache_resource(show_spinner=False)def initialize_nlp_models(): logger.info("Cargando modelos de spaCy") models = load_spacy_models() logger.info("Modelos de spaCy cargados exitosamente") return models
# Solución para el error de torch.classesdef _patched_get_module_paths(module): if 'torch' in str(module.__file__): return [] return original_get_module_paths(module)
# Aplicar el parche solo si es necesariotry: from streamlit.watcher.local_sources_watcher import get_module_paths as original_get_module_paths import streamlit.watcher.local_sources_watcher streamlit.watcher.local_sources_watcher.get_module_paths = _patched_get_module_pathsexcept ImportError: pass
def app_main(): try: logger.info("Entrando en app_main()")
# Inicializar el estado de la sesión if 'initialized' not in st.session_state: initialize_session_state() st.session_state.initialized = True
# Inicializar conexiones a bases de datos si no se ha hecho if 'db_initialized' not in st.session_state: st.session_state.db_initialized = initialize_database_connections()
# Cargar modelos NLP si no se ha hecho if 'nlp_models' not in st.session_state: logger.info("Inicializando modelos NLP en la sesión") st.session_state.nlp_models = initialize_nlp_models() logger.info("Modelos NLP inicializados y almacenados en la sesión")
# Inicializar estados de análisis si no existen if 'morphosyntax_state' not in st.session_state: st.session_state.morphosyntax_state = { 'last_analysis': None, 'analysis_count': 0 } if 'semantic_state' not in st.session_state: st.session_state.semantic_state = { 'last_analysis': None, 'analysis_count': 0 }
# Configurar la página inicial si no está configurada if 'page' not in st.session_state: st.session_state.page = 'login'
# Prevenir reinicios innecesarios preservando el estado if 'selected_tab' not in st.session_state: st.session_state.selected_tab = 0
logger.info(f"Página actual: {st.session_state.page}") logger.info(f"Rol del usuario: {st.session_state.role}")
# Dirigir el flujo a la interfaz de usuario principal logger.info(f"Llamando a ui_main() desde app_main()") ui_main()
except Exception as e: logger.error(f"Error en app_main: {str(e)}", exc_info=True) st.error("Se ha producido un error en la aplicación. Por favor, inténtelo de nuevo más tarde.") if st.button("Reiniciar aplicación", key=generate_unique_key("app", "reset_button")): st.session_state.clear() st.rerun()
if __name__ == "__main__": app_main()1txtx123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135### auth.py
import os
from azure.cosmos import CosmosClient, exceptions
import bcrypt
import base64
################################################################################################################
def clean_and_validate_key(key):
key = key.strip()
while len(key) % 4 != 0:
key += '='
try:
base64.b64decode(key)
return key
except:
raise ValueError("La clave proporcionada no es válida")
# Azure Cosmos DB configuration
endpoint = os.environ.get("COSMOS_ENDPOINT")
key = os.environ.get("COSMOS_KEY")
if not endpoint or not key:
raise ValueError("Las variables de entorno COSMOS_ENDPOINT y COSMOS_KEY deben estar configuradas")
key = clean_and_validate_key(key)
try:
client = CosmosClient(endpoint, key)
database = client.get_database_client("user_database")
container = database.get_container_client("users")
# Prueba de conexión
database_list = list(client.list_databases())
print(f"Conexión exitosa. Bases de datos encontradas: {len(database_list)}")
except Exception as e:
print(f"Error al conectar con Cosmos DB: {str(e)}")
raise
#############################################################################################################3
def hash_password(password):
"""Hash a password for storing."""
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
################################################################################################################
def verify_password(stored_password, provided_password):
"""Verify a stored password against one provided by user"""
return bcrypt.checkpw(provided_password.encode('utf-8'), stored_password.encode('utf-8'))
################################################################################################################
def register_user(username, password, additional_info=None):
try:
query = f"SELECT * FROM c WHERE c.id = '{username}'"
existing_user = list(container.query_items(query=query, enable_cross_partition_query=True))
if existing_user:
return False # User already exists
new_user = {
'id': username,
'password': hash_password(password),
'role': 'Estudiante',
'additional_info': additional_info or {}
}
new_user['partitionKey'] = username
container.create_item(body=new_user)
return True
except exceptions.CosmosHttpResponseError as e:
print(f"Error al registrar usuario: {str(e)}")
return False
################################################################################################################
def authenticate_user(username, password):
"""Authenticate a user."""
try:
query = f"SELECT * FROM c WHERE c.id = '{username}'"
results = list(container.query_items(query=query, partition_key=username))
if results:
stored_user = results[0]
if verify_password(stored_user['password'], password):
return True
except exceptions.CosmosHttpResponseError:
pass
return False
################################################################################################################
def get_user_role(username):
"""Get the role of a user."""
try:
query = f"SELECT c.role FROM c WHERE c.id = '{username}'"
results = list(container.query_items(query=query, partition_key=username))
if results:
return results[0]['role']
except exceptions.CosmosHttpResponseError:
pass
return None
################################################################################################################
def update_user_info(username, new_info):
"""Update user information."""
try:
query = f"SELECT * FROM c WHERE c.id = '{username}'"
results = list(container.query_items(query=query, partition_key=username))
if results:
user = results[0]
user['additional_info'].update(new_info)
container.upsert_item(user, partition_key=username)
return True
except exceptions.CosmosHttpResponseError:
pass
return False
################################################################################################################
def delete_user(username):
"""Delete a user."""
try:
query = f"SELECT * FROM c WHERE c.id = '{username}'"
results = list(container.query_items(query=query, partition_key=username))
if results:
user = results[0]
container.delete_item(item=user['id'], partition_key=username)
return True
except exceptions.CosmosHttpResponseError:
pass
return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344# modules/ui.py
# Importaciones estandar de python
import io
import streamlit as st
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import squarify
import pandas as pd
from datetime import datetime
import base64
from spacy import displacy
import re
from .morpho_analysis import POS_COLORS, POS_TRANSLATIONS # Asegúrate de que esta importación esté presente
print("POS_COLORS:", POS_COLORS)
print("POS_TRANSLATIONS:", POS_TRANSLATIONS)
# Importaciones locales
from .auth import authenticate_user, register_user, get_user_role
from .database import get_student_data, store_analysis_result
from .morpho_analysis import get_repeated_words_colors, highlight_repeated_words, POS_COLORS, POS_TRANSLATIONS
from .syntax_analysis import visualize_syntax
#########################################################################
# Define colors for grammatical categories
POS_COLORS = {
'ADJ': '#FFA07A', # Light Salmon
'ADP': '#98FB98', # Pale Green
'ADV': '#87CEFA', # Light Sky Blue
'AUX': '#DDA0DD', # Plum
'CCONJ': '#F0E68C', # Khaki
'DET': '#FFB6C1', # Light Pink
'INTJ': '#FF6347', # Tomato
'NOUN': '#90EE90', # Light Green
'NUM': '#FAFAD2', # Light Goldenrod Yellow
'PART': '#D3D3D3', # Light Gray
'PRON': '#FFA500', # Orange
'PROPN': '#20B2AA', # Light Sea Green
'SCONJ': '#DEB887', # Burlywood
'SYM': '#7B68EE', # Medium Slate Blue
'VERB': '#FF69B4', # Hot Pink
'X': '#A9A9A9', # Dark Gray
}
POS_TRANSLATIONS = {
'es': {
'ADJ': 'Adjetivo',
'ADP': 'Adposición',
'ADV': 'Adverbio',
'AUX': 'Auxiliar',
'CCONJ': 'Conjunción Coordinante',
'DET': 'Determinante',
'INTJ': 'Interjección',
'NOUN': 'Sustantivo',
'NUM': 'Número',
'PART': 'Partícula',
'PRON': 'Pronombre',
'PROPN': 'Nombre Propio',
'SCONJ': 'Conjunción Subordinante',
'SYM': 'Símbolo',
'VERB': 'Verbo',
'X': 'Otro',
},
'en': {
'ADJ': 'Adjective',
'ADP': 'Adposition',
'ADV': 'Adverb',
'AUX': 'Auxiliary',
'CCONJ': 'Coordinating Conjunction',
'DET': 'Determiner',
'INTJ': 'Interjection',
'NOUN': 'Noun',
'NUM': 'Number',
'PART': 'Particle',
'PRON': 'Pronoun',
'PROPN': 'Proper Noun',
'SCONJ': 'Subordinating Conjunction',
'SYM': 'Symbol',
'VERB': 'Verb',
'X': 'Other',
},
'fr': {
'ADJ': 'Adjectif',
'ADP': 'Adposition',
'ADV': 'Adverbe',
'AUX': 'Auxiliaire',
'CCONJ': 'Conjonction de Coordination',
'DET': 'Déterminant',
'INTJ': 'Interjection',
'NOUN': 'Nom',
'NUM': 'Nombre',
'PART': 'Particule',
'PRON': 'Pronom',
'PROPN': 'Nom Propre',
'SCONJ': 'Conjonction de Subordination',
'SYM': 'Symbole',
'VERB': 'Verbe',
'X': 'Autre',
}
}
##########################################################################
def login_page():
st.title("Iniciar Sesión")
username = st.text_input("Usuario")
password = st.text_input("Contraseña", type='password')
if st.button("Iniciar Sesión"):
if authenticate_user(username, password):
st.success(f"Bienvenido, {username}!")
st.session_state.logged_in = True
st.session_state.username = username
st.session_state.role = get_user_role(username)
st.experimental_rerun()
else:
st.error("Usuario o contraseña incorrectos")
##########################################################################
def register_page():
st.title("Registrarse")
new_username = st.text_input("Nuevo Usuario")
new_password = st.text_input("Nueva Contraseña", type='password')
additional_info = {}
additional_info['carrera'] = st.text_input("Carrera")
if st.button("Registrarse"):
if register_user(new_username, new_password, additional_info):
st.success("Registro exitoso. Por favor, inicia sesión.")
else:
st.error("El usuario ya existe o ocurrió un error durante el registro")
##########################################################################
def get_chatbot_response(input_text):
# Esta función debe ser implementada o importada de otro módulo
# Por ahora, retornamos un mensaje genérico
return "Lo siento, el chatbot no está disponible en este momento."
##########################################################################
def display_chat_interface():
st.markdown("### Chat con AIdeaText")
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
for i, (role, text) in enumerate(st.session_state.chat_history):
if role == "user":
st.text_area(f"Tú:", value=text, height=50, key=f"user_message_{i}", disabled=True)
else:
st.text_area(f"AIdeaText:", value=text, height=50, key=f"bot_message_{i}", disabled=True)
user_input = st.text_input("Escribe tu mensaje aquí:")
if st.button("Enviar"):
if user_input:
st.session_state.chat_history.append(("user", user_input))
response = get_chatbot_response(user_input)
st.session_state.chat_history.append(("bot", response))
st.experimental_rerun()
##########################################################################
def display_student_progress(username, lang_code='es'):
print("lang_code:", lang_code)
student_data = get_student_data(username)
if student_data is None:
st.warning("No se encontraron datos para este estudiante.")
st.info("Intenta realizar algunos análisis de texto primero.")
return
st.title(f"Progreso de {username}")
if student_data['entries_count'] > 0:
if 'word_count' in student_data and student_data['word_count']:
st.subheader("Total de palabras por categoría gramatical")
df = pd.DataFrame(list(student_data['word_count'].items()), columns=['category', 'count'])
df['label'] = df.apply(lambda x: f"{POS_TRANSLATIONS[lang_code].get(x['category'], x['category'])}", axis=1)
# Ordenar el DataFrame por conteo de palabras, de mayor a menor
df = df.sort_values('count', ascending=False)
fig, ax = plt.subplots(figsize=(12, 6))
bars = ax.bar(df['label'], df['count'], color=[POS_COLORS.get(cat, '#CCCCCC') for cat in df['category']])
ax.set_xlabel('Categoría Gramatical')
ax.set_ylabel('Cantidad de Palabras')
ax.set_title('Total de palabras por categoría gramatical')
plt.xticks(rotation=45, ha='right')
# Añadir etiquetas de valor en las barras
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height,
f'{height}',
ha='center', va='bottom')
plt.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
st.image(buf, use_column_width=True)
else:
st.info("No hay datos de conteo de palabras disponibles.")
# Diagramas de Arco (consolidados)
st.header("Diagramas de Arco")
with st.expander("Ver todos los Diagramas de Arco"):
for i, entry in enumerate(student_data['entries']):
if 'arc_diagrams' in entry and entry['arc_diagrams']:
st.subheader(f"Entrada {i+1} - {entry['timestamp']}")
st.write(entry['arc_diagrams'][0], unsafe_allow_html=True)
# Diagramas de Red (consolidados)
st.header("Diagramas de Red")
with st.expander("Ver todos los Diagramas de Red"):
for i, entry in enumerate(student_data['entries']):
if 'network_diagram' in entry and entry['network_diagram']:
st.subheader(f"Entrada {i+1} - {entry['timestamp']}")
try:
# Decodificar la imagen base64
image_bytes = base64.b64decode(entry['network_diagram'])
st.image(image_bytes)
except Exception as e:
st.error(f"Error al mostrar el diagrama de red: {str(e)}")
else:
st.warning("No se encontraron entradas para este estudiante.")
st.info("Intenta realizar algunos análisis de texto primero.")
##############################################################Mostrar entradas recientes######################################################################
#st.header("Entradas Recientes")
#for i, entry in enumerate(student_data['entries'][:5]): # Mostrar las 5 entradas más recientes
#with st.expander(f"Entrada {i+1} - {entry['timestamp']}"):
#st.write(entry['text'])
#else:
#st.warning("No se encontraron entradas para este estudiante.")
#st.info("Intenta realizar algunos análisis de texto primero.")
##########################################################################
def display_text_analysis_interface(nlp_models, lang_code):
translations = {
'es': {
'title': "AIdeaText - Análisis morfológico y sintáctico",
'input_label': "Ingrese un texto para analizar (máx. 5,000 palabras):",
'input_placeholder': "El objetivo de esta aplicación es que mejore sus habilidades de redacción. Para ello, después de ingresar su texto y presionar el botón obtendrá tres vistas horizontales. La primera, le indicará las palabras que se repiten por categoría gramátical; la segunda, un diagrama de arco le indicara las conexiones sintácticas en cada oración; y la tercera, es un grafo en el cual visualizara la configuración de su texto.",
'analyze_button': "Analizar texto",
'repeated_words': "Palabras repetidas",
'legend': "Leyenda: Categorías gramaticales",
'arc_diagram': "Análisis sintáctico: Diagrama de arco",
'network_diagram': "Análisis sintáctico: Diagrama de red",
'sentence': "Oración"
},
'en': {
'title': "AIdeaText - Morphological and Syntactic Analysis",
'input_label': "Enter a text to analyze (max 5,000 words):",
'input_placeholder': "The goal of this app is for you to improve your writing skills. To do this, after entering your text and pressing the button you will get three horizontal views. The first will indicate the words that are repeated by grammatical category; second, an arc diagram will indicate the syntactic connections in each sentence; and the third is a graph in which you will visualize the configuration of your text.",
'analyze_button': "Analyze text",
'repeated_words': "Repeated words",
'legend': "Legend: Grammatical categories",
'arc_diagram': "Syntactic analysis: Arc diagram",
'network_diagram': "Syntactic analysis: Network diagram",
'sentence': "Sentence"
},
'fr': {
'title': "AIdeaText - Analyse morphologique et syntaxique",
'input_label': "Entrez un texte à analyser (max 5 000 mots) :",
'input_placeholder': "Le but de cette application est d'améliorer vos compétences en rédaction. Pour ce faire, après avoir saisi votre texte et appuyé sur le bouton vous obtiendrez trois vues horizontales. Le premier indiquera les mots répétés par catégorie grammaticale; deuxièmement, un diagramme en arcs indiquera les connexions syntaxiques dans chaque phrase; et le troisième est un graphique dans lequel vous visualiserez la configuration de votre texte.",
'analyze_button': "Analyser le texte",
'repeated_words': "Mots répétés",
'legend': "Légende : Catégories grammaticales",
'arc_diagram': "Analyse syntaxique : Diagramme en arc",
'network_diagram': "Analyse syntaxique : Diagramme de réseau",
'sentence': "Phrase"
}
}
t = translations[lang_code]
if 'input_text' not in st.session_state:
st.session_state.input_text = ""
# Añadimos una clave única basada en el idioma seleccionado
sentence_input = st.text_area(
t['input_label'],
height=150,
placeholder=t['input_placeholder'],
value=st.session_state.input_text,
key=f"text_input_{lang_code}" # Clave única basada en el idioma
)
st.session_state.input_text = sentence_input
# sentence_input = st.text_area(t['input_label'], height=150, placeholder=t['input_placeholder'], value=st.session_state.input_text)
# st.session_state.input_text = sentence_input
if st.button(t['analyze_button'], key=f"analyze_button_{lang_code}"):
if sentence_input:
doc = nlp_models[lang_code](sentence_input)
with st.expander(t['repeated_words'], expanded=True):
word_colors = get_repeated_words_colors(doc)
highlighted_text = highlight_repeated_words(doc, word_colors)
st.markdown(highlighted_text, unsafe_allow_html=True)
st.markdown(f"##### {t['legend']}")
legend_html = "<div style='display: flex; flex-wrap: wrap;'>"
for pos, color in POS_COLORS.items():
if pos in POS_TRANSLATIONS:
legend_html += f"<div style='margin-right: 10px;'><span style='background-color: {color}; padding: 2px 5px;'>{POS_TRANSLATIONS[pos]}</span></div>"
legend_html += "</div>"
st.markdown(legend_html, unsafe_allow_html=True)
with st.expander(t['arc_diagram'], expanded=True):
sentences = list(doc.sents)
arc_diagrams = []
for i, sent in enumerate(sentences):
st.subheader(f"{t['sentence']} {i+1}")
html = displacy.render(sent, style="dep", options={"distance": 100})
html = html.replace('height="375"', 'height="200"')
html = re.sub(r'<svg[^>]*>', lambda m: m.group(0).replace('height="450"', 'height="300"'), html)
html = re.sub(r'<g [^>]*transform="translate\((\d+),(\d+)\)"', lambda m: f'<g transform="translate({m.group(1)},50)"', html)
st.write(html, unsafe_allow_html=True)
arc_diagrams.append(html)
with st.expander(t['network_diagram'], expanded=True):
fig = visualize_syntax(sentence_input, nlp_models[lang_code], lang_code)
st.pyplot(fig)
if store_analysis_result(
st.session_state.username,
sentence_input,
word_colors,
arc_diagrams,
fig
):
st.success("Análisis guardado correctamente.")
else:
st.error("Hubo un problema al guardar el análisis. Por favor, inténtelo de nuevo.")
st.error(f"Falló el guardado del análisis. Username: {st.session_state.username}")
##########################################################################
def display_teacher_interface():
st.write("Bienvenido, profesor. Aquí podrás ver el progreso de tus estudiantes.")
# Aquí puedes agregar la lógica para mostrar el progreso de los estudiantes123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319# modules/__init__.py
def load_auth_functions():
from .auth.auth import authenticate_student, register_student, update_student_info, delete_student
return {
'authenticate_student': authenticate_student,
'register_student': register_student,
'update_student_info': update_student_info,
'delete_student': delete_student
}
# Agregar nuevo import para current_situation
def load_current_situation_functions():
"""
Carga las funciones relacionadas con el análisis de situación actual.
Returns:
dict: Diccionario con las funciones de situación actual
"""
from .studentact.current_situation_interface import (
display_current_situation_interface,
display_metrics_in_one_row,
display_empty_metrics_row,
display_metrics_analysis,
display_comparison_results,
display_metrics_and_suggestions,
display_radar_chart,
suggest_improvement_tools,
prepare_metrics_config
)
from .studentact.current_situation_analysis import (
correlate_metrics,
analyze_text_dimensions,
analyze_clarity,
analyze_vocabulary_diversity,
analyze_cohesion,
analyze_structure,
get_dependency_depths,
normalize_score,
generate_sentence_graphs,
generate_word_connections,
generate_connection_paths,
create_vocabulary_network,
create_syntax_complexity_graph,
create_cohesion_heatmap
)
return {
'display_current_situation_interface': display_current_situation_interface,
'display_metrics_in_one_row': display_metrics_in_one_line,
'display_empty_metrics_row': display_empty_metrics_row,
'display_metrics_analysis': display_metrics_analysis,
'display_comparison_results': display_comparison_results,
'display_metrics_and_suggestions': display_metrics_and_suggestions,
'display_radar_chart': display_radar_chart,
'suggest_improvement_tools': suggest_improvement_tools,
'prepare_metrics_config': prepare_metrics_config,
'display_empty_metrics_row' : display_empty_metrics_row,
'correlate_metrics': correlate_metrics,
'analyze_text_dimensions': analyze_text_dimensions,
'analyze_clarity': analyze_clarity,
'analyze_vocabulary_diversity': analyze_vocabulary_diversity,
'analyze_cohesion': analyze_cohesion,
'analyze_structure': analyze_structure,
'get_dependency_depths': get_dependency_depths,
'normalize_score': normalize_score,
'generate_sentence_graphs': generate_sentence_graphs,
'generate_word_connections': generate_word_connections,
'generate_connection_paths': generate_connection_paths,
'create_vocabulary_network': create_vocabulary_network,
'create_syntax_complexity_graph': create_syntax_complexity_graph,
'create_cohesion_heatmap': create_cohesion_heatmap
}
def load_database_functions():
from .database.database_init import (
initialize_database_connections,
get_container,
get_mongodb
)
# Importar funciones SQL
from .database.sql_db import (
create_student_user,
get_student_user,
update_student_user,
delete_student_user,
store_application_request,
store_student_feedback,
record_login,
record_logout,
get_recent_sessions,
get_user_total_time
)
from .database.mongo_db import (
get_collection,
insert_document,
find_documents,
update_document,
delete_document,
)
from .database.morphosintax_mongo_db import (
store_student_morphosyntax_result,
get_student_morphosyntax_analysis,
update_student_morphosyntax_analysis,
delete_student_morphosyntax_analysis,
get_student_morphosyntax_data
)
from .database.semantic_mongo_db import (
store_student_semantic_result,
get_student_semantic_analysis,
update_student_semantic_analysis,
delete_student_semantic_analysis,
get_student_semantic_data
)
from .database.discourse_mongo_db import (
store_student_discourse_result,
get_student_discourse_analysis,
update_student_discourse_analysis,
delete_student_discourse_analysis,
get_student_discourse_data
)
# Agregar nueva importación para current_situation
from .database.current_situation_mongo_db import (
store_current_situation_result,
verify_storage,
get_recent_sessions,
get_student_situation_history,
update_exercise_status
)
# Importar nuevas funciones de análisis morfosintáctico iterativo
from .morphosyntax_iterative_mongo_db import (
store_student_morphosyntax_base,
store_student_morphosyntax_iteration,
get_student_morphosyntax_analysis,
update_student_morphosyntax_analysis,
delete_student_morphosyntax_analysis,
get_student_morphosyntax_data
)
from .database.chat_mongo_db import store_chat_history, get_chat_history
return {
# Nuevas funciones morfosintácticas iterativas
'store_student_morphosyntax_base': store_student_morphosyntax_base,
'store_student_morphosyntax_iteration': store_student_morphosyntax_iteration,
'get_student_morphosyntax_iterative_analysis': get_student_morphosyntax_analysis, # Renombrada para evitar conflicto
'update_student_morphosyntax_iterative': update_student_morphosyntax_analysis, # Renombrada para evitar conflicto
'delete_student_morphosyntax_iterative': delete_student_morphosyntax_analysis, # Renombrada para evitar conflicto
'get_student_morphosyntax_iterative_data': get_student_morphosyntax_data,
'store_current_situation_result': store_current_situation_result,
'verify_storage': verify_storage,
'get_recent_sessions': get_recent_sessions,
'get_student_situation_history': get_student_situation_history,
'update_exercise_status': update_exercise_status,
'initialize_database_connections': initialize_database_connections,
'get_container': get_container,
'get_mongodb': get_mongodb,
'create_student_user': create_student_user,
'get_student_user': get_student_user,
'update_student_user': update_student_user,
'delete_student_user': delete_student_user,
'store_application_request': store_application_request,
'store_student_feedback': store_student_feedback,
'get_collection': get_collection,
'insert_document': insert_document,
'find_documents': find_documents,
'update_document': update_document,
'delete_document': delete_document,
'store_student_morphosyntax_result': store_student_morphosyntax_result,
'get_student_morphosyntax_analysis': get_student_morphosyntax_analysis,
'update_student_morphosyntax_analysis': update_student_morphosyntax_analysis,
'delete_student_morphosyntax_analysis': delete_student_morphosyntax_analysis,
'get_student_morphosyntax_data': get_student_morphosyntax_data,
'store_student_semantic_result': store_student_semantic_result,
'get_student_semantic_analysis': get_student_semantic_analysis,
'update_student_semantic_analysis': update_student_semantic_analysis,
'delete_student_semantic_analysis': delete_student_semantic_analysis,
'get_student_semantic_data': get_student_semantic_data,
'store_chat_history': store_chat_history,
'get_chat_history': get_chat_history,
'store_student_discourse_result': store_student_discourse_result,
'get_student_discourse_analysis': get_student_discourse_analysis,
'update_student_discourse_analysis': update_student_discourse_analysis,
'delete_student_discourse_analysis': delete_student_discourse_analysis,
'get_student_discourse_data': get_student_discourse_data,
'record_login': record_login,
'record_logout': record_logout,
'get_recent_sessions': get_recent_sessions,
'get_user_total_time': get_user_total_time
}
def load_ui_functions():
# No importamos nada de ui.py aquí
return {} # Retornamos un diccionario vacío
def load_student_activities_v2_functions():
from .studentact.student_activities_v2 import display_student_activities
return {
'display_student_progress': display_student_activities
}
def load_morphosyntax_functions():
from .morphosyntax.morphosyntax_interface import (
initialize_arc_analysis_state,
reset_arc_analysis_state,
display_arc_diagrams,
display_morphosyntax_results
)
from .morphosyntax.morphosyntax_process import (
process_morphosyntactic_input,
format_analysis_results,
perform_advanced_morphosyntactic_analysis # Añadir esta función
)
return {
#Interface
'initialize_arc_analysis_state': initialize_arc_analysis_state,
'reset_arc_analysis_state': reset_morpho_state,
'display_arc_diagrams': display_arc_diagrams,
'display_morphosyntax_interface': display_morphosyntax_interface,
#Process
'process_morphosyntactic_input': process_morphosyntactic_input,
'format_analysis_results': format_analysis_results,
'perform_advanced_morphosyntactic_analysis': perform_advanced_morphosyntactic_analysis
}
def load_semantic_functions():
from .semantic.semantic_interface import (
display_semantic_interface,
display_semantic_results
)
from modules.semantic.semantic_process import (
process_semantic_input,
format_semantic_results
)
return {
'display_semantic_interface': display_semantic_interface,
'display_semantic_results': display_semantic_results,
'process_semantic_input': process_semantic_input,
'format_semantic_results': format_analysis_results,
}
def load_discourse_functions():
from .discourse.discourse_interface import (
display_discourse_interface,
display_discourse_results
)
from modules.discourse.discourse_process import (
perform_discourse_analysis, # Este es el nombre correcto de la función
extract_key_concepts, # Función adicional que necesitamos
generate_concept_graph, # Función adicional que necesitamos
calculate_similarity_matrix # Función adicional que necesitamos
)
return {
'display_discourse_interface': display_discourse_interface,
'display_discourse_results': display_discourse_results,
'perform_discourse_analysis': perform_discourse_analysis,
'extract_key_concepts': extract_key_concepts,
'generate_concept_graph': generate_concept_graph,
'calculate_similarity_matrix': calculate_similarity_matrix
}
def load_admin_functions():
from .admin.admin_ui import admin_page
return {
'admin_page': admin_page
}
def load_utils_functions():
from .utils.spacy_utils import load_spacy_models
return {
'load_spacy_models': load_spacy_models
}
def load_chatbot_functions():
"""
Carga las funciones del módulo de chatbot
Returns:
dict: Diccionario con las funciones del chatbot
"""
from modules.chatbot.sidebar_chat import (
display_sidebar_chat
)
from modules.chatbot.chat_process import (
ChatProcessor
)
return {
'display_sidebar_chat': display_sidebar_chat,
'ChatProcessor': ChatProcessor
}
# Función para cargar todas las funciones
def load_all_functions():
return {
**load_auth_functions(),
**load_database_functions(),
# **load_ui_functions(),
**load_admin_functions(),
**load_morphosyntax_functions(),
**load_semantic_functions(),
**load_discourse_functions(),
**load_utils_functions(),
**load_chatbot_functions(),
**load_student_activities_functions(),
**load_current_situation_functions() # Agregar el nuevo loader
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180# modules/__init__.py
def load_auth_functions():
from .auth.auth import authenticate_user, register_user
return {
'authenticate_user': authenticate_user,
'register_user': register_user
}
def load_database_function():
from .database.database_oldFromV2 import (
initialize_mongodb_connection,
initialize_database_connections,
create_admin_user,
create_student_user,
get_user,
get_student_data,
get_user_files,
delete_file,
store_application_request,
store_user_feedback,
store_morphosyntax_result,
store_semantic_result,
store_discourse_analysis_result,
store_chat_history,
export_analysis_and_chat,
manage_file_contents
)
return {
'initialize_mongodb_connection': initialize_mongodb_connection,
'initialize_database_connections': initialize_database_connections,
'create_admin_user': create_admin_user,
'create_student_user': create_student_user,
'get_user': get_user,
'get_student_data': get_student_data,
'get_user_files': get_user_files,
'delete_file': delete_file,
'store_application_request': store_application_request,
'store_user_feedback': store_user_feedback,
'store_morphosyntax_result': store_morphosyntax_result,
'store_semantic_result': store_semantic_result,
'store_discourse_analysis_result': store_discourse_analysis_result,
'store_chat_history': store_chat_history,
'export_analysis_and_chat': export_analysis_and_chat,
'manage_file_contents': manage_file_contents
}
def load_ui_functions():
# No importamos nada de ui.py aquí
return {} # Retornamos un diccionario vacío
def load_student_activities_functions():
from .studentact.student_activities_v2 import display_student_progress
return {
'display_student_progress': display_student_progress
}
def load_morphosyntax_functions():
from .morphosyntax.morphosyntax_interface import display_morphosyntax_interface
from .morphosyntax.morphosyntax_process import process_morphosyntactic_input
return {
'display_morphosyntax_interface': display_morphosyntax_interface,
'process_morphosyntactic_input': process_morphosyntactic_input
}
def load_semantic_functions():
from .semantic.semantic_interface_68ok import display_semantic_interface
from .semantic.semantic_process import process_semantic_input
return {
'display_semantic_interface': display_semantic_interface,
'process_semantic_input': process_semantic_input
}
def load_discourse_functions():
from .discourse.discourse_interface import display_discourse_interface
from .discourse.discourse_process import process_discourse_input
return {
'display_discourse_interface': display_discourse_interface,
'process_discourse_input': process_discourse_input
}
def load_email_functions():
from .email.email import send_email_notification
return {
'send_email_notification': send_email_notification
}
def load_admin_functions():
from .admin.admin_ui import admin_page
return {
'admin_page': admin_page
}
def load_text_analysis_functions():
from .text_analysis.morpho_analysis import (
generate_arc_diagram,
perform_advanced_morphosyntactic_analysis,
perform_pos_analysis,
perform_morphological_analysis,
analyze_sentence_structure,
get_repeated_words_colors,
highlight_repeated_words,
)
from .text_analysis.semantic_analysis import (
perform_semantic_analysis,
generate_summary,
extract_entities,
analyze_sentiment,
create_topic_graph,
visualize_topic_graph,
ENTITY_LABELS
)
from .text_analysis.discourse_analysis import (
perform_discourse_analysis,
compare_semantic_analysis
)
return {
'generate_arc_diagram': generate_arc_diagram,
'perform_advanced_morphosyntactic_analysis': perform_advanced_morphosyntactic_analysis,
'perform_pos_analysis': perform_pos_analysis,
'perform_morphological_analysis': perform_morphological_analysis,
'analyze_sentence_structure': analyze_sentence_structure,
'get_repeated_words_colors': get_repeated_words_colors,
'highlight_repeated_words': highlight_repeated_words,
'perform_semantic_analysis': perform_semantic_analysis,
'generate_summary': generate_summary,
'extract_entities': extract_entities,
'analyze_sentiment': analyze_sentiment,
'create_topic_graph': create_topic_graph,
'visualize_topic_graph': visualize_topic_graph,
'ENTITY_LABELS': ENTITY_LABELS,
'perform_discourse_analysis': perform_discourse_analysis,
'compare_semantic_analysis': compare_semantic_analysis
}
def load_utils_functions():
from .utils.spacy_utils import load_spacy_models
return {
'load_spacy_models': load_spacy_models
}
def load_chatbot_functions():
from .chatbot.chatbot import (
ClaudeAPIChat,
initialize_chatbot,
process_chat_input,
get_connectors,
handle_semantic_commands,
generate_topics_visualization,
extract_topics,
get_semantic_chatbot_response
)
return {
'ClaudeAPIChat': ClaudeAPIChat,
'initialize_chatbot': initialize_chatbot,
'process_chat_input': process_chat_input,
'get_connectors': get_connectors,
'handle_semantic_commands': handle_semantic_commands,
'generate_topics_visualization': generate_topics_visualization,
'extract_topics': extract_topics,
'get_semantic_chatbot_response': get_semantic_chatbot_response
}
# Función para cargar todas las funciones
def load_all_functions():
return {
**load_auth_functions(),
**load_database_function(),
# **load_ui_functions(),
**load_admin_functions(),
**load_morphosyntax_functions(),
**load_semantic_functions(),
**load_discourse_functions(),
**load_text_analysis_functions(),
**load_utils_functions(),
**load_chatbot_functions(),
**load_email_functions()
**load_student_activities_functions() # Añadimos las nuevas funciones de actividades del estudiante
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250#modules/admin/admin_ui.py
import streamlit as st
from datetime import datetime
from ..database.sql_db import (
get_user,
get_student_user,
get_admin_user,
get_teacher_user,
create_student_user,
update_student_user,
delete_student_user,
record_login,
record_logout,
get_recent_sessions,
get_user_total_time
)
from ..database.morphosintax_mongo_db import get_student_morphosyntax_analysis
from ..auth.auth import hash_password # Agregar esta importación al inicio
#######################################################################################
def format_duration(seconds):
"""Convierte segundos a formato legible"""
if not seconds:
return "0h 0m"
hours = seconds // 3600
minutes = (seconds % 3600) // 60
return f"{hours}h {minutes}m"
def admin_page():
st.title("Panel de Administración")
st.write(f"Bienvenido, {st.session_state.username}")
# Crear tres tabs para las diferentes secciones
tab1, tab2, tab3 = st.tabs([
"Gestión de Usuarios",
"Búsqueda de Usuarios",
"Actividad de la Plataforma"
])
########################################################
# Tab 1: Gestión de Usuarios
with tab1:
st.header("Crear Nuevo Usuario Estudiante")
# Crear dos columnas para el formulario
col1, col2 = st.columns(2)
with col1:
new_username = st.text_input(
"Correo electrónico del nuevo usuario",
key="admin_new_username"
)
with col2:
new_password = st.text_input(
"Contraseña",
type="password",
key="admin_new_password"
)
if st.button("Crear Usuario", key="admin_create_user", type="primary"):
if new_username and new_password: # Verificamos que ambos campos tengan valor
try:
# Hashear la contraseña antes de crear el usuario
hashed_password = hash_password(new_password)
if create_student_user(new_username, hashed_password, {'partitionKey': new_username}):
st.success(f"Usuario estudiante {new_username} creado exitosamente")
else:
st.error("Error al crear el usuario estudiante")
except Exception as e:
st.error(f"Error al crear usuario: {str(e)}")
else:
st.warning("Por favor complete todos los campos")
#######################################################################
# Tab 2: Búsqueda de Usuarios
with tab2:
st.header("Búsqueda de Usuarios")
search_col1, search_col2 = st.columns([2,1])
with search_col1:
student_username = st.text_input(
"Nombre de usuario del estudiante",
key="admin_view_student"
)
with search_col2:
search_button = st.button(
"Buscar",
key="admin_view_student_data",
type="primary"
)
if search_button:
student = get_student_user(student_username)
if student:
# Crear tabs para diferentes tipos de información
info_tab1, info_tab2, info_tab3 = st.tabs([
"Información Básica",
"Análisis Realizados",
"Tiempo en Plataforma"
])
with info_tab1:
st.subheader("Información del Usuario")
st.json(student)
with info_tab2:
st.subheader("Análisis Realizados")
student_data = get_student_morphosyntax_analysis(student_username)
if student_data:
st.json(student_data)
else:
st.info("No hay datos de análisis para este estudiante.")
with info_tab3:
st.subheader("Tiempo en Plataforma")
total_time = get_user_total_time(student_username)
if total_time:
st.metric(
"Tiempo Total",
format_duration(total_time)
)
else:
st.info("No hay registros de tiempo para este usuario")
else:
st.error("Estudiante no encontrado")
#######################################################################
# Tab 3: Actividad de la Plataforma
with tab3:
st.header("Actividad Reciente")
# Agregar botón de actualización
if st.button("Actualizar datos", key="refresh_sessions", type="primary"):
st.rerun()
# Mostrar spinner mientras carga
with st.spinner("Cargando datos de sesiones..."):
# Obtener sesiones recientes
recent_sessions = get_recent_sessions(20) # Aumentado a 20 para más datos
if recent_sessions:
# Crear dataframe para mostrar los datos
sessions_data = []
for session in recent_sessions:
try:
# Manejar el formato de fecha con manejo de excepciones
try:
login_time = datetime.fromisoformat(
session['loginTime'].replace('Z', '+00:00')
).strftime("%Y-%m-%d %H:%M:%S")
except Exception as e:
login_time = session['loginTime']
# Manejar el caso de logout_time cuando la sesión está activa
if session.get('logoutTime') and session['logoutTime'] != "Activo":
try:
logout_time = datetime.fromisoformat(
session['logoutTime'].replace('Z', '+00:00')
).strftime("%Y-%m-%d %H:%M:%S")
except Exception as e:
logout_time = session['logoutTime']
else:
logout_time = "Activo"
# Agregar datos a la lista
sessions_data.append({
"Usuario": session.get('username', 'Desconocido'),
"Inicio de Sesión": login_time,
"Fin de Sesión": logout_time,
"Duración": format_duration(session.get('sessionDuration', 0))
})
except Exception as e:
st.error(f"Error procesando sesión: {str(e)}")
continue
# Mostrar información de depuración si hay problemas
with st.expander("Información de depuración", expanded=False):
st.write("Datos crudos recuperados:")
st.json(recent_sessions)
st.write("Datos procesados para mostrar:")
st.json(sessions_data)
# Mostrar tabla con estilos
st.dataframe(
sessions_data,
hide_index=True,
column_config={
"Usuario": st.column_config.TextColumn(
"Usuario",
width="medium"
),
"Inicio de Sesión": st.column_config.TextColumn(
"Inicio de Sesión",
width="medium"
),
"Fin de Sesión": st.column_config.TextColumn(
"Fin de Sesión",
width="medium"
),
"Duración": st.column_config.TextColumn(
"Duración",
width="small"
)
}
)
# Añadir métricas resumen
total_sessions = len(sessions_data)
total_users = len(set(session['Usuario'] for session in sessions_data))
metric_col1, metric_col2 = st.columns(2)
with metric_col1:
st.metric("Total de Sesiones", total_sessions)
with metric_col2:
st.metric("Usuarios Únicos", total_users)
else:
st.info("No hay registros de sesiones recientes o hubo un problema al recuperarlos.")
# Ayuda de depuración
if st.button("Mostrar diagnóstico"):
st.write("Verificando la función get_recent_sessions:")
container = get_container("users_sessions")
if container:
st.success("✅ Conectado al contenedor users_sessions")
else:
st.error("❌ No se pudo conectar al contenedor users_sessions")
#######################################################################
# Agregar una línea divisoria antes del botón
st.markdown("---")
#######################################################################
# Centrar el botón de cierre de sesión
col1, col2, col3 = st.columns([2,1,2])
with col2:
if st.button("Cerrar Sesión", key="admin_logout", type="primary", use_container_width=True):
from ..auth.auth import logout
logout()
st.rerun()src/.streamlit/config.tomlDeleted-9
src/23-7-2024_app.pyDeleted-62
src/Test_app.pyDeleted-8
src/app.pyDeleted-196
src/assets/img/AIdeaTextCard.jpgDeleted

Large File Pointer Details
- SHA256: 7a2728751bd949172ae2a2980a34f77931f3bb9f3d5843a479c2275b1316272e
- Pointer size: 131 Bytes
- Size of remote file: 268 kB
src/assets/img/AIdeaText_Logo_vectores.pngDeleted

Large File Pointer Details
- SHA256: 49e82e34b75e707b9fb46563347c64570aa7360a33adc3b18f82e7969f448917
- Pointer size: 132 Bytes
- Size of remote file: 1.01 MB
src/assets/img/ALPHA_Startup Badges.pngDeleted

Large File Pointer Details
- SHA256: f55cb163a87ef69660185da4654e796edd66f30ac85a0db7c8f172fca8b02b09
- Pointer size: 131 Bytes
- Size of remote file: 602 kB
src/assets/img/Ico-20x20.icoDeleted
src/assets/img/Logo20x20.pngDeleted
src/assets/img/Logo24x24.pngDeleted
src/assets/img/Logo32x32.pngDeleted
src/assets/img/Logo40x40.pngDeleted
src/assets/img/Logo48x48.pngDeleted
src/assets/img/Logo64x64.pngDeleted
src/assets/img/Logo_100x100.pngDeleted
src/assets/img/Logo_300x300.pngDeleted
src/assets/img/Mesa de trabajo 1png 0.3.pngDeleted
src/assets/img/aideaText-ICO.pngDeleted
src/assets/img/aideaText-Logo-32x32.pngDeleted
src/assets/img/aideaText_icon.icoDeleted
src/assets/img/aideaText_logo.pngDeleted
src/assets/img/assets_img_logo_92x92.icoDeleted
Large File Pointer Details
- SHA256: d2a957f8116c5f5658526a763b5280aaf589e9b57aea3ab59ac8fd683d374ef3
- Pointer size: 131 Bytes
- Size of remote file: 372 kB
src/assets/img/logo120x120.pngDeleted
src/assets/img/logo_92x92.jpgDeleted
src/assets/img/logo_92x92.pngDeleted
src/assets/img/socialmedia/AIdeaTextCard.jpgDeleted

Large File Pointer Details
- SHA256: 7a2728751bd949172ae2a2980a34f77931f3bb9f3d5843a479c2275b1316272e
- Pointer size: 131 Bytes
- Size of remote file: 268 kB
src/assets/img/socialmedia/Facebook_CoverPhoto-1_820x312.jpgDeleted

Large File Pointer Details
- SHA256: b24221fd528714afc31c87ee586ed3d173eb0767f1755decf5f192946f96743c
- Pointer size: 131 Bytes
- Size of remote file: 245 kB
src/assets/img/socialmedia/Facebook_CoverPhoto_820x312.jpgDeleted

Large File Pointer Details
- SHA256: 5733fa2fe5d1d76f9a01f7346536dd7ecd6e5f223006386a81b3188bcfa985bb
- Pointer size: 131 Bytes
- Size of remote file: 289 kB
src/assets/img/socialmedia/_MG_2535.jpgDeleted

Large File Pointer Details
- SHA256: a94188b158e88ff1cec1db6b39a6d28e564c77f685e7c076a7f3b76dffa0fe19
- Pointer size: 131 Bytes
- Size of remote file: 328 kB
src/assets/img/socialmedia/_MG_2585.jpgDeleted

Large File Pointer Details
- SHA256: 8997c5e41a528400b818088548162c2c13315ceb87803148af64dd9932207838
- Pointer size: 131 Bytes
- Size of remote file: 336 kB
src/assets/img/socialmedia/_MG_2587.jpgDeleted

Large File Pointer Details
- SHA256: def2e98c90c7c55aa8ee7b2ee31b81ca3c950fd12149e1c23742c236aad85ee9
- Pointer size: 131 Bytes
- Size of remote file: 331 kB
src/assets/img/socialmedia/_MG_2590.jpgDeleted

Large File Pointer Details
- SHA256: 128dd26ddb18fe0008818f78535305b79fc4c258a123db4076cd2f9b67c1ae3d
- Pointer size: 131 Bytes
- Size of remote file: 332 kB
src/assets/img/socialmedia/_MG_2678.jpgDeleted

Large File Pointer Details
- SHA256: 5bdf2d4d2ddc6d974c2a9b21d44c24a3b98b952e31032df83b60e6ebde61c836
- Pointer size: 131 Bytes
- Size of remote file: 335 kB
src/assets/img/socialmedia/_MG_2727.jpgDeleted

Large File Pointer Details
- SHA256: c2d4a162817cbebba5738f564a92a48546f5208877152cf0545962f74c3f495e
- Pointer size: 131 Bytes
- Size of remote file: 336 kB
src/assets/img/socialmedia/_MG_2735.jpgDeleted

Large File Pointer Details
- SHA256: 527d01d3e09061d1a77513b75b55bcceb2840dbc8631e85b9542b7aaa9a85841
- Pointer size: 131 Bytes
- Size of remote file: 331 kB
src/assets/img/socialmedia/_MG_2790.jpgDeleted

Large File Pointer Details
- SHA256: 21bcc1b99cf3d1ab4ab6d480ffeb3867ee4ef17a18d8e1873e3ea46cc548722b
- Pointer size: 131 Bytes
- Size of remote file: 340 kB
src/assets/img/socialmedia/_MG_2845.JPGDeleted
Large File Pointer Details
- SHA256: ad3a77f44abe700d87e36e3125890aeb29a2194f8ef006fc895c8eff49eeed8a
- Pointer size: 131 Bytes
- Size of remote file: 347 kB
src/assets/img/socialmedia/txt.txtDeleted-1
src/assets/img/text.txtDeleted
src/modules/23-7-2024_auth.pyDeleted-135
src/modules/23-7-2024_ui.pyDeleted-344
src/modules/__init__.pyDeleted-319
src/modules/__init__Old-V3.pyDeleted-180
src/modules/__pycache__/__init__.cpython-311.pycDeleted
src/modules/admin/__init__.pyDeleted
src/modules/admin/__pycache__/__init__.cpython-311.pycDeleted
src/modules/admin/__pycache__/admin_ui.cpython-311.pycDeleted
src/modules/admin/admin_ui.pyDeleted-250
src/modules/admin/txt.txtDeleted
src/modules/auth/__init__.pyDeleted