File size: 7,536 Bytes
af25a2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""

Utility functions for the AI Study Assistant

"""

import re
import os
from typing import List, Dict, Tuple
import json
from datetime import datetime


def create_directory(path: str) -> None:
    """Create a directory if it doesn't exist."""
    if not os.path.exists(path):
        os.makedirs(path)
        print(f"✓ Created directory: {path}")


def read_file(filepath: str) -> str:
    """Read and return file contents."""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        raise FileNotFoundError(f"File not found: {filepath}")
    except Exception as e:
        raise Exception(f"Error reading file {filepath}: {str(e)}")


def write_file(filepath: str, content: str) -> None:
    """Write content to a file."""
    try:
        os.makedirs(os.path.dirname(filepath) or '.', exist_ok=True)
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(content)
    except Exception as e:
        raise Exception(f"Error writing to file {filepath}: {str(e)}")


def load_prompt_template(prompt_name: str, mode: str = "normal") -> str:
    """

    Load a prompt template from file.

    

    Args:

        prompt_name: Name of the prompt (e.g., 'summary', 'quiz')

        mode: Mode for the prompt (e.g., 'normal', 'detailed')

    

    Returns:

        The prompt template content

    """
    from config import PROMPTS_DIR, MODES_DIR
    
    # Try mode-specific prompt first
    mode_path = os.path.join(MODES_DIR, f"{mode}.txt")
    base_path = os.path.join(PROMPTS_DIR, f"{prompt_name}_prompt.txt")
    
    try:
        return read_file(base_path)
    except FileNotFoundError:
        raise FileNotFoundError(
            f"Prompt template not found: {prompt_name}_prompt.txt\n"
            f"Expected at: {base_path}"
        )


def extract_text_from_pdf(pdf_path: str) -> str:
    """

    Extract text from a PDF file.

    

    Args:

        pdf_path: Path to the PDF file

    

    Returns:

        Extracted text content

    """
    try:
        from PyPDF2 import PdfReader
        
        text = []
        with open(pdf_path, 'rb') as file:
            pdf_reader = PdfReader(file)
            for page_num, page in enumerate(pdf_reader.pages):
                page_text = page.extract_text()
                if page_text:
                    text.append(page_text)
        
        return '\n'.join(text)
    
    except ImportError:
        raise ImportError("PyPDF2 not installed. Install with: pip install PyPDF2")
    except Exception as e:
        raise Exception(f"Error extracting PDF: {str(e)}")


def extract_text_from_file(file_path: str) -> str:
    """

    Extract text from various file types.

    

    Args:

        file_path: Path to the file

    

    Returns:

        Extracted text content

    """
    file_ext = os.path.splitext(file_path)[1].lower()
    
    if file_ext == '.pdf':
        return extract_text_from_pdf(file_path)
    elif file_ext in ['.txt', '.md']:
        return read_file(file_path)
    else:
        raise ValueError(f"Unsupported file type: {file_ext}")


def truncate_text(text: str, max_length: int) -> str:
    """

    Truncate text to maximum length while preserving words.

    

    Args:

        text: The text to truncate

        max_length: Maximum number of characters

    

    Returns:

        Truncated text

    """
    if len(text) <= max_length:
        return text
    
    # Truncate at word boundary
    truncated = text[:max_length].rsplit(' ', 1)[0]
    return truncated + "..."


def clean_text(text: str) -> str:
    """

    Clean and normalize text.

    

    Args:

        text: Text to clean

    

    Returns:

        Cleaned text

    """
    # Remove excess whitespace
    text = re.sub(r'\s+', ' ', text)
    # Remove special characters but keep punctuation
    text = re.sub(r'[^\w\s.,!?;:\-\'"()]', '', text)
    return text.strip()


def extract_json_from_text(text: str) -> Dict:
    """

    Extract JSON object from text response.

    

    Args:

        text: Text potentially containing JSON

    

    Returns:

        Parsed JSON object or empty dict if not found

    """
    try:
        # Look for JSON-like patterns
        json_match = re.search(r'\{.*\}', text, re.DOTALL)
        if json_match:
            json_str = json_match.group(0)
            return json.loads(json_str)
    except json.JSONDecodeError:
        pass
    
    return {}


def format_quiz_response(quiz_text: str) -> List[Dict]:
    """

    Parse and format quiz response into structured questions.

    

    Args:

        quiz_text: Raw quiz text from LLM

    

    Returns:

        List of question dictionaries

    """
    questions = []
    
    # Split by question markers
    q_pattern = r'(?:Q\d+\.|Question \d+:|^\d+\.)'
    
    raw_questions = re.split(q_pattern, quiz_text)[1:]  # Skip first empty part
    
    for idx, q_text in enumerate(raw_questions, 1):
        questions.append({
            'id': idx,
            'question': q_text.strip()[:200],  # First 200 chars
            'raw_text': q_text.strip()
        })
    
    return questions[:5]  # Return max 5 questions


def format_summary(text: str) -> str:
    """

    Format summary response for better readability.

    

    Args:

        text: Raw summary text

    

    Returns:

        Formatted summary

    """
    # Add line breaks between paragraphs
    paragraphs = text.split('\n\n')
    formatted = '\n\n'.join(p.strip() for p in paragraphs if p.strip())
    return formatted


def log_event(event_type: str, details: str) -> None:
    """

    Log events for debugging and monitoring.

    

    Args:

        event_type: Type of event (e.g., 'API_CALL', 'ERROR', 'VALIDATION')

        details: Event details

    """
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_message = f"[{timestamp}] {event_type}: {details}"
    print(log_message)
    
    # Optionally save to log file
    try:
        with open("app.log", "a", encoding='utf-8') as log_file:
            log_file.write(log_message + "\n")
    except:
        pass


def validate_api_response(response: str, min_length: int = 10) -> Tuple[bool, str]:
    """

    Validate API response quality.

    

    Args:

        response: The response to validate

        min_length: Minimum acceptable length

    

    Returns:

        Tuple of (is_valid, message)

    """
    if not response:
        return False, "Empty response from API"
    
    if len(response.strip()) < min_length:
        return False, f"Response too short (minimum {min_length} characters)"
    
    if response.lower().startswith("error"):
        return False, "API returned an error"
    
    return True, "Valid response"


def format_error_message(error: Exception) -> str:
    """

    Format error messages for display to user.

    

    Args:

        error: The exception

    

    Returns:

        User-friendly error message

    """
    error_str = str(error)
    
    if "API" in error_str:
        return f"🔴 API Error: {error_str}\n\nPlease check your API key in config.py"
    elif "file" in error_str.lower():
        return f"🔴 File Error: {error_str}\n\nEnsure the file exists and is readable"
    else:
        return f"🔴 Error: {error_str}"