File size: 5,742 Bytes
4cc1fd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import json
import os
from parser import get_fallback_courses

def load_courses():
    """Загружает курсы из JSON файла или возвращает fallback"""
    try:
        courses_file = 'data/processed/courses.json'
        if os.path.exists(courses_file):
            with open(courses_file, 'r', encoding='utf-8') as f:
                courses = json.load(f)
            return courses
        else:
            # Если файла нет, возвращаем fallback
            return get_fallback_courses()
    except Exception as e:
        print(f'Ошибка загрузки курсов: {e}')
        return get_fallback_courses()

def filter_courses(query, program_id=None, semester=None):
    """Фильтрация курсов по запросу и параметрам"""
    courses = load_courses()
    query_lower = query.lower()
    
    filtered = []
    
    for course in courses:
        # Фильтр по программе
        if program_id and course.get('program_id') != program_id:
            continue
            
        # Фильтр по семестру
        if semester and course.get('semester') != semester:
            continue
            
        # Поиск по ключевым словам
        course_text = f"{course.get('name', '')} {course.get('short_desc', '')} {' '.join(course.get('tags', []))}".lower()
        
        if any(word in course_text for word in query_lower.split()):
            filtered.append(course)
    
    return filtered[:8]  # Ограничиваем до 8 курсов

def recommend_courses(profile):
    """Рекомендации курсов на основе профиля студента"""
    courses = load_courses()
    
    programming_exp = profile.get('programming_experience', 2)
    math_level = profile.get('math_level', 2)
    interests = profile.get('interests', [])
    semester = profile.get('semester')
    
    # Фильтруем по семестру если указан
    if semester:
        courses = [c for c in courses if c.get('semester') == semester]
    
    # Сортируем по релевантности
    scored_courses = []
    
    for course in courses:
        score = 0
        
        # Оценка по сложности программирования
        if programming_exp <= 2 and 'python' in course.get('tags', []):
            score += 2
        elif 2 <= programming_exp <= 4 and 'ml' in course.get('tags', []):
            score += 2
        elif programming_exp >= 4 and 'dl' in course.get('tags', []):
            score += 2
        
        # Оценка по математике
        if math_level >= 2 and 'math' in course.get('tags', []):
            score += 2
        if math_level >= 3 and 'stats' in course.get('tags', []):
            score += 1
        
        # Оценка по интересам
        matching_tags = [tag for tag in interests if tag in course.get('tags', [])]
        score += len(matching_tags) * 3
        
        # Бонус за product/business интересы для AI Product программы
        if 'product' in interests or 'business' in interests:
            if course.get('program_id') == 'ai_product':
                score += 2
        
        if score > 0:
            scored_courses.append((course, score))
    
    # Сортируем по score и возвращаем топ-7
    scored_courses.sort(key=lambda x: x[1], reverse=True)
    return [course for course, score in scored_courses[:7]]

def is_relevant(message):
    """Проверяет релевантность вопроса"""
    itmo_keywords = [
        'итмо', 'магистратура', 'учебный план', 'дисциплина', 'курс',
        'ии', 'ai', 'ai product', 'институт ии', 'программа',
        'машинное обучение', 'глубокое обучение', 'nlp', 'компьютерное зрение',
        'продукт', 'аналитика', 'управление', 'обучение', 'учеба'
    ]
    
    message_lower = message.lower()
    
    # Проверяем ключевые слова
    if any(keyword in message_lower for keyword in itmo_keywords):
        return True
    
    # Проверяем совпадение с названиями курсов
    courses = load_courses()
    for course in courses:
        if course.get('name', '').lower() in message_lower:
            return True
    
    return False

def get_program_info(program_id):
    """Получает информацию о программе"""
    programs = {
        'ai': {
            'name': 'Искусственный интеллект',
            'description': 'Программа готовит специалистов в области машинного обучения, глубокого обучения, обработки естественного языка и компьютерного зрения.',
            'duration': '2 года (4 семестра)',
            'credits_total': 120,
            'career': 'ML Engineer, Data Scientist, Research Scientist, AI Developer'
        },
        'ai_product': {
            'name': 'AI Product Management',
            'description': 'Программа готовит продуктовых менеджеров, способных создавать и развивать ИИ-продукты.',
            'duration': '2 года (4 семестра)',
            'credits_total': 120,
            'career': 'Product Manager, AI Product Manager, Business Analyst, Product Owner'
        }
    }
    
    return programs.get(program_id)