AIdeaText commited on
Commit
e16e5fe
1 Parent(s): e39e070

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -115
app.py CHANGED
@@ -8,118 +8,56 @@ import spacy
8
  from spacy import displacy
9
  import re
10
 
11
- # Configure the page to use the full width
12
- st.set_page_config(
13
- page_title="AIdeaText",
14
- layout="wide",
15
- page_icon="random"
16
- )
17
-
18
- from modules.syntax_analysis import visualize_syntax, highlight_repeated_words, get_repeated_words_colors, POS_COLORS, POS_TRANSLATIONS
19
-
20
- @st.cache_resource
21
- def load_spacy_models():
22
- return {
23
- 'es': spacy.load("es_core_news_lg"),
24
- 'en': spacy.load("en_core_web_lg"),
25
- 'fr': spacy.load("fr_core_news_lg")
26
- }
27
-
28
- # Load spaCy models
29
- nlp_models = load_spacy_models()
30
-
31
- # Language selection
32
- languages = {
33
- 'Español': 'es',
34
- 'English': 'en',
35
- 'Français': 'fr'
36
- }
37
- selected_lang = st.sidebar.selectbox("Select Language / Seleccione el idioma / Choisissez la langue", list(languages.keys()))
38
- lang_code = languages[selected_lang]
39
-
40
- # Translations
41
- translations = {
42
- 'es': {
43
- 'title': "AIdeaText - Análisis morfológico y sintáctico",
44
- 'input_label': "Ingrese un texto para analizar (máx. 5,000 palabras):",
45
- '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.",
46
- 'analyze_button': "Analizar texto",
47
- 'repeated_words': "Palabras repetidas",
48
- 'legend': "Leyenda: Categorías gramaticales",
49
- 'arc_diagram': "Análisis sintáctico: Diagrama de arco",
50
- 'network_diagram': "Análisis sintáctico: Diagrama de red",
51
- 'sentence': "Oración"
52
- },
53
- 'en': {
54
- 'title': "AIdeaText - Morphological and Syntactic Analysis",
55
- 'input_label': "Enter a text to analyze (max 5,000 words):",
56
- '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.",
57
- 'analyze_button': "Analyze text",
58
- 'repeated_words': "Repeated words",
59
- 'legend': "Legend: Grammatical categories",
60
- 'arc_diagram': "Syntactic analysis: Arc diagram",
61
- 'network_diagram': "Syntactic analysis: Network diagram",
62
- 'sentence': "Sentence"
63
- },
64
- 'fr': {
65
- 'title': "AIdeaText - Analyse morphologique et syntaxique",
66
- 'input_label': "Entrez un texte à analyser (max 5 000 mots) :",
67
- '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.",
68
- 'analyze_button': "Analyser le texte",
69
- 'repeated_words': "Mots répétés",
70
- 'legend': "Légende : Catégories grammaticales",
71
- 'arc_diagram': "Analyse syntaxique : Diagramme en arc",
72
- 'network_diagram': "Analyse syntaxique : Diagramme de réseau",
73
- 'sentence': "Phrase"
74
- }
75
- }
76
-
77
- # Use translations
78
- t = translations[lang_code]
79
-
80
- st.markdown(f"### {t['title']}")
81
-
82
- # Initialize session state for input text if it doesn't exist
83
- if 'input_text' not in st.session_state:
84
- st.session_state.input_text = ""
85
-
86
- # Text Input with instructions
87
- sentence_input = st.text_area(t['input_label'], height=150, placeholder=t['input_placeholder'], value=st.session_state.input_text)
88
-
89
- # Update session state with current input
90
- st.session_state.input_text = sentence_input
91
-
92
- if st.button(t['analyze_button']):
93
- if sentence_input:
94
- doc = nlp_models[lang_code](sentence_input)
95
-
96
- # Highlighted Repeated Words
97
- with st.expander(t['repeated_words'], expanded=True):
98
- word_colors = get_repeated_words_colors(doc)
99
- highlighted_text = highlight_repeated_words(doc, word_colors)
100
- st.markdown(highlighted_text, unsafe_allow_html=True)
101
-
102
- # Legend for grammatical categories
103
- st.markdown(f"##### {t['legend']}")
104
- legend_html = "<div style='display: flex; flex-wrap: wrap;'>"
105
- for pos, color in POS_COLORS.items():
106
- if pos in POS_TRANSLATIONS:
107
- legend_html += f"<div style='margin-right: 10px;'><span style='background-color: {color}; padding: 2px 5px;'>{POS_TRANSLATIONS[pos]}</span></div>"
108
- legend_html += "</div>"
109
- st.markdown(legend_html, unsafe_allow_html=True)
110
-
111
- # Arc Diagram
112
- with st.expander(t['arc_diagram'], expanded=True):
113
- sentences = list(doc.sents)
114
- for i, sent in enumerate(sentences):
115
- st.subheader(f"{t['sentence']} {i+1}")
116
- html = displacy.render(sent, style="dep", options={"distance": 100})
117
- html = html.replace('height="375"', 'height="200"')
118
- html = re.sub(r'<svg[^>]*>', lambda m: m.group(0).replace('height="450"', 'height="300"'), html)
119
- html = re.sub(r'<g [^>]*transform="translate\((\d+),(\d+)\)"', lambda m: f'<g transform="translate({m.group(1)},50)"', html)
120
- st.write(html, unsafe_allow_html=True)
121
-
122
- # Network graph
123
- with st.expander(t['network_diagram'], expanded=True):
124
- fig = visualize_syntax(sentence_input, nlp_models[lang_code], lang_code)
125
- st.pyplot(fig)
 
8
  from spacy import displacy
9
  import re
10
 
11
+ from modules.auth import register_user, authenticate_user
12
+ from modules.morpho_analysis import get_repeated_words_colors, highlight_repeated_words, POS_COLORS, POS_TRANSLATIONS
13
+ from modules.syntax_analysis import visualize_syntax
14
+
15
+ # ... (resto de tus importaciones y configuraciones)
16
+
17
+ def login_page():
18
+ st.title("Iniciar Sesión")
19
+ username = st.text_input("Usuario")
20
+ password = st.text_input("Contraseña", type='password')
21
+ if st.button("Iniciar Sesión"):
22
+ if authenticate_user(username, password):
23
+ st.success(f"Bienvenido, {username}!")
24
+ st.session_state.logged_in = True
25
+ st.session_state.username = username
26
+ st.experimental_rerun()
27
+ else:
28
+ st.error("Usuario o contraseña incorrectos")
29
+
30
+ def register_page():
31
+ st.title("Registrarse")
32
+ new_username = st.text_input("Nuevo Usuario")
33
+ new_password = st.text_input("Nueva Contraseña", type='password')
34
+ role = st.selectbox("Rol", ["Estudiante", "Profesor"])
35
+ if st.button("Registrarse"):
36
+ if register_user(new_username, new_password, role):
37
+ st.success("Registro exitoso. Por favor, inicia sesión.")
38
+ else:
39
+ st.error("El usuario ya existe")
40
+
41
+ def main_app():
42
+ # Aquí va tu código principal de la aplicación
43
+ # ... (el resto de tu código actual en app.py)
44
+
45
+ def main():
46
+ if 'logged_in' not in st.session_state:
47
+ st.session_state.logged_in = False
48
+
49
+ if not st.session_state.logged_in:
50
+ menu = ["Iniciar Sesión", "Registrarse"]
51
+ choice = st.sidebar.selectbox("Menu", menu)
52
+ if choice == "Iniciar Sesión":
53
+ login_page()
54
+ elif choice == "Registrarse":
55
+ register_page()
56
+ else:
57
+ if st.sidebar.button("Cerrar Sesión"):
58
+ st.session_state.logged_in = False
59
+ st.experimental_rerun()
60
+ main_app()
61
+
62
+ if __name__ == "__main__":
63
+ main()