Update modules/studentact/current_situation_analysis.py
Browse files
modules/studentact/current_situation_analysis.py
CHANGED
@@ -23,6 +23,9 @@ logging.basicConfig(
|
|
23 |
# 3. Obtener el logger específico para este módulo
|
24 |
logger = logging.getLogger(__name__)
|
25 |
|
|
|
|
|
|
|
26 |
#########################################################################
|
27 |
|
28 |
def correlate_metrics(scores):
|
@@ -247,7 +250,7 @@ def analyze_clarity(doc):
|
|
247 |
logger.error(f"Error en analyze_clarity: {str(e)}")
|
248 |
return 0.0, {}
|
249 |
|
250 |
-
|
251 |
def analyze_vocabulary_diversity(doc):
|
252 |
"""Análisis mejorado de la diversidad y calidad del vocabulario"""
|
253 |
try:
|
@@ -305,6 +308,7 @@ def analyze_vocabulary_diversity(doc):
|
|
305 |
logger.error(f"Error en analyze_vocabulary_diversity: {str(e)}")
|
306 |
return 0.0, {}
|
307 |
|
|
|
308 |
def analyze_cohesion(doc):
|
309 |
"""Analiza la cohesión textual"""
|
310 |
try:
|
@@ -386,6 +390,7 @@ def analyze_cohesion(doc):
|
|
386 |
logger.error(f"Error en analyze_cohesion: {str(e)}")
|
387 |
return 0.0
|
388 |
|
|
|
389 |
def analyze_structure(doc):
|
390 |
try:
|
391 |
if len(doc) == 0:
|
@@ -513,6 +518,8 @@ def get_dependency_depths(token, depth=0, analyzed_tokens=None):
|
|
513 |
|
514 |
return current_result
|
515 |
|
|
|
|
|
516 |
def normalize_score(value, metric_type,
|
517 |
min_threshold=0.0, target_threshold=1.0,
|
518 |
range_factor=2.0, optimal_length=None,
|
@@ -616,6 +623,9 @@ def normalize_score(value, metric_type,
|
|
616 |
return 0.0
|
617 |
|
618 |
|
|
|
|
|
|
|
619 |
# Funciones de generación de gráficos
|
620 |
def generate_sentence_graphs(doc):
|
621 |
"""Genera visualizaciones de estructura de oraciones"""
|
@@ -684,6 +694,7 @@ def create_vocabulary_network(doc):
|
|
684 |
plt.axis('off')
|
685 |
return fig
|
686 |
|
|
|
687 |
def create_syntax_complexity_graph(doc):
|
688 |
"""
|
689 |
Genera el diagrama de arco de complejidad sintáctica.
|
@@ -763,7 +774,7 @@ def create_syntax_complexity_graph(doc):
|
|
763 |
logger.error(f"Error en create_syntax_complexity_graph: {str(e)}")
|
764 |
return None
|
765 |
|
766 |
-
|
767 |
def create_cohesion_heatmap(doc):
|
768 |
"""Genera un mapa de calor que muestra la cohesión entre párrafos/oraciones."""
|
769 |
try:
|
@@ -808,3 +819,193 @@ def create_cohesion_heatmap(doc):
|
|
808 |
except Exception as e:
|
809 |
logger.error(f"Error en create_cohesion_heatmap: {str(e)}")
|
810 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
# 3. Obtener el logger específico para este módulo
|
24 |
logger = logging.getLogger(__name__)
|
25 |
|
26 |
+
# Importaciones locales
|
27 |
+
from translations.recommendations import RECOMMENDATIONS
|
28 |
+
|
29 |
#########################################################################
|
30 |
|
31 |
def correlate_metrics(scores):
|
|
|
250 |
logger.error(f"Error en analyze_clarity: {str(e)}")
|
251 |
return 0.0, {}
|
252 |
|
253 |
+
########################################################################################
|
254 |
def analyze_vocabulary_diversity(doc):
|
255 |
"""Análisis mejorado de la diversidad y calidad del vocabulario"""
|
256 |
try:
|
|
|
308 |
logger.error(f"Error en analyze_vocabulary_diversity: {str(e)}")
|
309 |
return 0.0, {}
|
310 |
|
311 |
+
#############################################################################################
|
312 |
def analyze_cohesion(doc):
|
313 |
"""Analiza la cohesión textual"""
|
314 |
try:
|
|
|
390 |
logger.error(f"Error en analyze_cohesion: {str(e)}")
|
391 |
return 0.0
|
392 |
|
393 |
+
#############################################################################################################
|
394 |
def analyze_structure(doc):
|
395 |
try:
|
396 |
if len(doc) == 0:
|
|
|
518 |
|
519 |
return current_result
|
520 |
|
521 |
+
|
522 |
+
#############################################################################################################
|
523 |
def normalize_score(value, metric_type,
|
524 |
min_threshold=0.0, target_threshold=1.0,
|
525 |
range_factor=2.0, optimal_length=None,
|
|
|
623 |
return 0.0
|
624 |
|
625 |
|
626 |
+
|
627 |
+
|
628 |
+
#####################################################################################
|
629 |
# Funciones de generación de gráficos
|
630 |
def generate_sentence_graphs(doc):
|
631 |
"""Genera visualizaciones de estructura de oraciones"""
|
|
|
694 |
plt.axis('off')
|
695 |
return fig
|
696 |
|
697 |
+
#############################################################################
|
698 |
def create_syntax_complexity_graph(doc):
|
699 |
"""
|
700 |
Genera el diagrama de arco de complejidad sintáctica.
|
|
|
774 |
logger.error(f"Error en create_syntax_complexity_graph: {str(e)}")
|
775 |
return None
|
776 |
|
777 |
+
#########################################################################################################
|
778 |
def create_cohesion_heatmap(doc):
|
779 |
"""Genera un mapa de calor que muestra la cohesión entre párrafos/oraciones."""
|
780 |
try:
|
|
|
819 |
except Exception as e:
|
820 |
logger.error(f"Error en create_cohesion_heatmap: {str(e)}")
|
821 |
return None
|
822 |
+
|
823 |
+
########################################################################################
|
824 |
+
def generate_recommendations(metrics, text_type, lang_code='es'):
|
825 |
+
"""
|
826 |
+
Genera recomendaciones personalizadas basadas en las métricas del texto y el tipo de texto.
|
827 |
+
|
828 |
+
Args:
|
829 |
+
metrics: Diccionario con las métricas analizadas
|
830 |
+
text_type: Tipo de texto ('academic_article', 'student_essay', 'general_communication')
|
831 |
+
lang_code: Código del idioma para las recomendaciones (es, en, fr, pt)
|
832 |
+
|
833 |
+
Returns:
|
834 |
+
dict: Recomendaciones organizadas por categoría en el idioma correspondiente
|
835 |
+
"""
|
836 |
+
try:
|
837 |
+
# Obtener umbrales según el tipo de texto
|
838 |
+
thresholds = TEXT_TYPES[text_type]['thresholds']
|
839 |
+
|
840 |
+
# Verificar que el idioma esté soportado, usar español como respaldo
|
841 |
+
if lang_code not in RECOMMENDATIONS:
|
842 |
+
logger.warning(f"Idioma {lang_code} no soportado para recomendaciones, usando español")
|
843 |
+
lang_code = 'es'
|
844 |
+
|
845 |
+
# Obtener traducciones para el idioma seleccionado
|
846 |
+
translations = RECOMMENDATIONS[lang_code]
|
847 |
+
|
848 |
+
# Inicializar diccionario de recomendaciones
|
849 |
+
recommendations = {
|
850 |
+
'vocabulary': [],
|
851 |
+
'structure': [],
|
852 |
+
'cohesion': [],
|
853 |
+
'clarity': [],
|
854 |
+
'specific': [],
|
855 |
+
'priority': {
|
856 |
+
'area': 'general',
|
857 |
+
'tips': []
|
858 |
+
},
|
859 |
+
'text_type_name': translations['text_types'][text_type],
|
860 |
+
'dimension_names': translations['dimension_names'],
|
861 |
+
'ui_text': {
|
862 |
+
'priority_intro': translations['priority_intro'],
|
863 |
+
'detailed_recommendations': translations['detailed_recommendations'],
|
864 |
+
'save_button': translations['save_button'],
|
865 |
+
'save_success': translations['save_success'],
|
866 |
+
'save_error': translations['save_error'],
|
867 |
+
'area_priority': translations['area_priority']
|
868 |
+
}
|
869 |
+
}
|
870 |
+
|
871 |
+
# Determinar nivel para cada dimensión y asignar recomendaciones
|
872 |
+
dimensions = ['vocabulary', 'structure', 'cohesion', 'clarity']
|
873 |
+
scores = {}
|
874 |
+
|
875 |
+
for dim in dimensions:
|
876 |
+
score = metrics[dim]['normalized_score']
|
877 |
+
scores[dim] = score
|
878 |
+
|
879 |
+
# Determinar nivel (bajo, medio, alto)
|
880 |
+
if score < thresholds[dim]['min']:
|
881 |
+
level = 'low'
|
882 |
+
elif score < thresholds[dim]['target']:
|
883 |
+
level = 'medium'
|
884 |
+
else:
|
885 |
+
level = 'high'
|
886 |
+
|
887 |
+
# Asignar recomendaciones para ese nivel
|
888 |
+
recommendations[dim] = translations[dim][level]
|
889 |
+
|
890 |
+
# Asignar recomendaciones específicas por tipo de texto
|
891 |
+
recommendations['specific'] = translations[text_type]
|
892 |
+
|
893 |
+
# Determinar área prioritaria (la que tiene menor puntuación)
|
894 |
+
priority_dimension = min(scores, key=scores.get)
|
895 |
+
recommendations['priority']['area'] = priority_dimension
|
896 |
+
recommendations['priority']['tips'] = recommendations[priority_dimension]
|
897 |
+
|
898 |
+
logger.info(f"Generadas recomendaciones en {lang_code} para texto tipo {text_type}")
|
899 |
+
return recommendations
|
900 |
+
|
901 |
+
except Exception as e:
|
902 |
+
logger.error(f"Error en generate_recommendations: {str(e)}")
|
903 |
+
# Retornar mensajes genéricos en caso de error
|
904 |
+
if lang_code == 'en':
|
905 |
+
return {
|
906 |
+
'vocabulary': ["Try enriching your vocabulary"],
|
907 |
+
'structure': ["Work on the structure of your sentences"],
|
908 |
+
'cohesion': ["Improve the connection between your ideas"],
|
909 |
+
'clarity': ["Try to express your ideas more clearly"],
|
910 |
+
'specific': ["Adapt your text according to its purpose"],
|
911 |
+
'priority': {
|
912 |
+
'area': 'general',
|
913 |
+
'tips': ["Seek specific feedback from a tutor or teacher"]
|
914 |
+
},
|
915 |
+
'dimension_names': {
|
916 |
+
'vocabulary': 'Vocabulary',
|
917 |
+
'structure': 'Structure',
|
918 |
+
'cohesion': 'Cohesion',
|
919 |
+
'clarity': 'Clarity',
|
920 |
+
'general': 'General'
|
921 |
+
},
|
922 |
+
'ui_text': {
|
923 |
+
'priority_intro': "This is where you should focus your efforts.",
|
924 |
+
'detailed_recommendations': "Detailed recommendations",
|
925 |
+
'save_button': "Save analysis",
|
926 |
+
'save_success': "Analysis saved successfully",
|
927 |
+
'save_error': "Error saving analysis",
|
928 |
+
'area_priority': "Priority area"
|
929 |
+
}
|
930 |
+
}
|
931 |
+
elif lang_code == 'fr':
|
932 |
+
return {
|
933 |
+
'vocabulary': ["Essayez d'enrichir votre vocabulaire"],
|
934 |
+
'structure': ["Travaillez sur la structure de vos phrases"],
|
935 |
+
'cohesion': ["Améliorez la connexion entre vos idées"],
|
936 |
+
'clarity': ["Essayez d'exprimer vos idées plus clairement"],
|
937 |
+
'specific': ["Adaptez votre texte en fonction de son objectif"],
|
938 |
+
'priority': {
|
939 |
+
'area': 'general',
|
940 |
+
'tips': ["Demandez des commentaires spécifiques à un tuteur ou un professeur"]
|
941 |
+
},
|
942 |
+
'dimension_names': {
|
943 |
+
'vocabulary': 'Vocabulaire',
|
944 |
+
'structure': 'Structure',
|
945 |
+
'cohesion': 'Cohésion',
|
946 |
+
'clarity': 'Clarté',
|
947 |
+
'general': 'Général'
|
948 |
+
},
|
949 |
+
'ui_text': {
|
950 |
+
'priority_intro': "C'est là que vous devriez concentrer vos efforts.",
|
951 |
+
'detailed_recommendations': "Recommandations détaillées",
|
952 |
+
'save_button': "Enregistrer l'analyse",
|
953 |
+
'save_success': "Analyse enregistrée avec succès",
|
954 |
+
'save_error': "Erreur lors de l'enregistrement de l'analyse",
|
955 |
+
'area_priority': "Domaine prioritaire"
|
956 |
+
}
|
957 |
+
}
|
958 |
+
elif lang_code == 'pt':
|
959 |
+
return {
|
960 |
+
'vocabulary': ["Tente enriquecer seu vocabulário"],
|
961 |
+
'structure': ["Trabalhe na estrutura de suas frases"],
|
962 |
+
'cohesion': ["Melhore a conexão entre suas ideias"],
|
963 |
+
'clarity': ["Tente expressar suas ideias com mais clareza"],
|
964 |
+
'specific': ["Adapte seu texto de acordo com seu propósito"],
|
965 |
+
'priority': {
|
966 |
+
'area': 'general',
|
967 |
+
'tips': ["Busque feedback específico de um tutor ou professor"]
|
968 |
+
},
|
969 |
+
'dimension_names': {
|
970 |
+
'vocabulary': 'Vocabulário',
|
971 |
+
'structure': 'Estrutura',
|
972 |
+
'cohesion': 'Coesão',
|
973 |
+
'clarity': 'Clareza',
|
974 |
+
'general': 'Geral'
|
975 |
+
},
|
976 |
+
'ui_text': {
|
977 |
+
'priority_intro': "É aqui que você deve concentrar seus esforços.",
|
978 |
+
'detailed_recommendations': "Recomendações detalhadas",
|
979 |
+
'save_button': "Salvar análise",
|
980 |
+
'save_success': "Análise salva com sucesso",
|
981 |
+
'save_error': "Erro ao salvar análise",
|
982 |
+
'area_priority': "Área prioritária"
|
983 |
+
}
|
984 |
+
}
|
985 |
+
else: # Español por defecto
|
986 |
+
return {
|
987 |
+
'vocabulary': ["Intenta enriquecer tu vocabulario"],
|
988 |
+
'structure': ["Trabaja en la estructura de tus oraciones"],
|
989 |
+
'cohesion': ["Mejora la conexión entre tus ideas"],
|
990 |
+
'clarity': ["Busca expresar tus ideas con mayor claridad"],
|
991 |
+
'specific': ["Adapta tu texto según su propósito"],
|
992 |
+
'priority': {
|
993 |
+
'area': 'general',
|
994 |
+
'tips': ["Busca retroalimentación específica de un tutor o profesor"]
|
995 |
+
},
|
996 |
+
'dimension_names': {
|
997 |
+
'vocabulary': 'Vocabulario',
|
998 |
+
'structure': 'Estructura',
|
999 |
+
'cohesion': 'Cohesión',
|
1000 |
+
'clarity': 'Claridad',
|
1001 |
+
'general': 'General'
|
1002 |
+
},
|
1003 |
+
'ui_text': {
|
1004 |
+
'priority_intro': "Esta es el área donde debes concentrar tus esfuerzos.",
|
1005 |
+
'detailed_recommendations': "Recomendaciones detalladas",
|
1006 |
+
'save_button': "Guardar análisis",
|
1007 |
+
'save_success': "Análisis guardado con éxito",
|
1008 |
+
'save_error': "Error al guardar el análisis",
|
1009 |
+
'area_priority': "Área prioritaria"
|
1010 |
+
}
|
1011 |
+
}
|