Spaces:
Running
Running
Update components/student_flow.py
Browse files- components/student_flow.py +232 -73
components/student_flow.py
CHANGED
|
@@ -4,6 +4,10 @@ from generator import model_manager
|
|
| 4 |
from components.file_processor import get_student_content_input
|
| 5 |
from components.export_handler import generate_pdf
|
| 6 |
from components.session_manager import update_session_state
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
def render_student_flow():
|
| 9 |
"""Render the student content generation flow"""
|
|
@@ -288,86 +292,241 @@ def generate_chunked_content(content_text, student_level, specific_help, filenam
|
|
| 288 |
st.info("🔄 Trying alternative processing method...")
|
| 289 |
generate_single_large_content(content_text, student_level, specific_help, filename)
|
| 290 |
|
| 291 |
-
def
|
| 292 |
-
"""
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
if current_chunk:
|
| 328 |
chunks.append(current_chunk.strip())
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
else:
|
| 334 |
if current_chunk:
|
| 335 |
chunks.append(current_chunk.strip())
|
| 336 |
-
current_chunk =
|
| 337 |
-
|
| 338 |
-
#
|
| 339 |
-
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
|
| 342 |
-
for sentence in sentences:
|
| 343 |
-
if len(current_chunk) + len(sentence) < max_chunk_size:
|
| 344 |
-
current_chunk += sentence + ". "
|
| 345 |
-
else:
|
| 346 |
-
if current_chunk:
|
| 347 |
-
chunks.append(current_chunk.strip())
|
| 348 |
-
current_chunk = sentence + ". "
|
| 349 |
-
|
| 350 |
-
# Add the last chunk if it exists
|
| 351 |
-
if current_chunk.strip():
|
| 352 |
-
chunks.append(current_chunk.strip())
|
| 353 |
-
|
| 354 |
-
# Final validation - ensure no chunk is too large
|
| 355 |
-
validated_chunks = []
|
| 356 |
-
for chunk in chunks:
|
| 357 |
-
if len(chunk) < min_chunk_size and validated_chunks: # Now min_chunk_size is defined
|
| 358 |
-
# Merge with previous chunk if too small (unless it's the first chunk)
|
| 359 |
-
validated_chunks[-1] = validated_chunks[-1] + "\n\n" + chunk
|
| 360 |
-
elif len(chunk) > max_chunk_size * 1.2: # Allow 20% overflow
|
| 361 |
-
# Emergency split by fixed size
|
| 362 |
-
for i in range(0, len(chunk), max_chunk_size):
|
| 363 |
-
sub_chunk = chunk[i:i + max_chunk_size]
|
| 364 |
-
if sub_chunk.strip():
|
| 365 |
-
validated_chunks.append(sub_chunk.strip())
|
| 366 |
-
else:
|
| 367 |
-
validated_chunks.append(chunk)
|
| 368 |
-
|
| 369 |
-
return validated_chunks
|
| 370 |
-
|
| 371 |
def build_phi3_chunk_prompt(chunk, student_level, specific_help, chunk_num, total_chunks):
|
| 372 |
"""Build Phi-3 specific prompt for a single chunk - STRICTER VERSION"""
|
| 373 |
prompt = f"""TASK: Write the actual simplified explanation for this content section.
|
|
|
|
| 4 |
from components.file_processor import get_student_content_input
|
| 5 |
from components.export_handler import generate_pdf
|
| 6 |
from components.session_manager import update_session_state
|
| 7 |
+
import re
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
def render_student_flow():
|
| 13 |
"""Render the student content generation flow"""
|
|
|
|
| 292 |
st.info("🔄 Trying alternative processing method...")
|
| 293 |
generate_single_large_content(content_text, student_level, specific_help, filename)
|
| 294 |
|
| 295 |
+
def is_academic_section_start(line):
|
| 296 |
+
"""Detect common research paper section headers with error handling"""
|
| 297 |
+
try:
|
| 298 |
+
if not line or not isinstance(line, str):
|
| 299 |
+
return False
|
| 300 |
+
|
| 301 |
+
academic_headers = [
|
| 302 |
+
'abstract', 'introduction', 'methods', 'methodology', 'materials and methods',
|
| 303 |
+
'results', 'findings', 'discussion', 'conclusion', 'conclusions',
|
| 304 |
+
'references', 'bibliography', 'acknowledgments', 'acknowledgements',
|
| 305 |
+
'background', 'literature review', 'theoretical framework',
|
| 306 |
+
'data analysis', 'statistical analysis', 'limitations', 'future work',
|
| 307 |
+
'implications', 'key findings', 'summary', 'objectives'
|
| 308 |
+
]
|
| 309 |
+
|
| 310 |
+
line_lower = line.lower().strip()
|
| 311 |
+
|
| 312 |
+
# Return False for very short lines that are likely not section headers
|
| 313 |
+
if len(line_lower) < 3 or len(line_lower) > 200:
|
| 314 |
+
return False
|
| 315 |
+
|
| 316 |
+
# Remove common numbering patterns: "1. Introduction" -> "Introduction"
|
| 317 |
+
line_clean = re.sub(r'^\d+[\.\)]\s*', '', line_lower) # "1. Introduction"
|
| 318 |
+
line_clean = re.sub(r'^[IVX]+[\.\)]\s*', '', line_clean) # "I. Introduction"
|
| 319 |
+
line_clean = re.sub(r'^[A-Z]\)\s*', '', line_clean) # "A) Introduction"
|
| 320 |
+
|
| 321 |
+
# Clean up extra whitespace
|
| 322 |
+
line_clean = re.sub(r'\s+', ' ', line_clean).strip()
|
| 323 |
+
|
| 324 |
+
# Check if line starts with or contains academic headers
|
| 325 |
+
for header in academic_headers:
|
| 326 |
+
try:
|
| 327 |
+
if (line_clean.startswith(header) or
|
| 328 |
+
f"\n{header}" in f"\n{line_clean}" or
|
| 329 |
+
re.match(rf'^{header}[\s:]', line_clean) or
|
| 330 |
+
line_clean == header):
|
| 331 |
+
logger.debug(f"Detected academic section: '{line_clean}' matches '{header}'")
|
| 332 |
+
return True
|
| 333 |
+
except re.error as e:
|
| 334 |
+
logger.warning(f"Regex error for header '{header}': {e}")
|
| 335 |
+
continue
|
| 336 |
|
| 337 |
+
return False
|
| 338 |
+
|
| 339 |
+
except Exception as e:
|
| 340 |
+
logger.error(f"Error in is_academic_section_start: {e}")
|
| 341 |
+
return False
|
| 342 |
+
|
| 343 |
+
def chunk_content(content, max_chunk_size=8000, min_chunk_size=500):
|
| 344 |
+
"""Split content into manageable chunks with robust error handling"""
|
| 345 |
+
try:
|
| 346 |
+
# Input validation
|
| 347 |
+
if not content or not isinstance(content, str):
|
| 348 |
+
logger.warning("Invalid content provided to chunk_content")
|
| 349 |
+
return []
|
| 350 |
+
|
| 351 |
+
content = content.strip()
|
| 352 |
+
if not content:
|
| 353 |
+
return []
|
| 354 |
+
|
| 355 |
+
# Parameter validation
|
| 356 |
+
if not isinstance(max_chunk_size, int) or max_chunk_size <= 0:
|
| 357 |
+
logger.warning(f"Invalid max_chunk_size: {max_chunk_size}, using default 8000")
|
| 358 |
+
max_chunk_size = 8000
|
| 359 |
+
|
| 360 |
+
if not isinstance(min_chunk_size, int) or min_chunk_size <= 0:
|
| 361 |
+
logger.warning(f"Invalid min_chunk_size: {min_chunk_size}, using default 500")
|
| 362 |
+
min_chunk_size = 500
|
| 363 |
+
|
| 364 |
+
if min_chunk_size >= max_chunk_size:
|
| 365 |
+
logger.warning(f"min_chunk_size ({min_chunk_size}) >= max_chunk_size ({max_chunk_size}), adjusting")
|
| 366 |
+
min_chunk_size = max(max_chunk_size // 4, 100)
|
| 367 |
+
|
| 368 |
+
# If content is already smaller than max chunk size, return it as a single chunk
|
| 369 |
+
if len(content) <= max_chunk_size:
|
| 370 |
+
logger.debug(f"Content fits in single chunk: {len(content)} chars")
|
| 371 |
+
return [content]
|
| 372 |
+
|
| 373 |
+
logger.info(f"Chunking content: {len(content)} chars, max_chunk_size: {max_chunk_size}")
|
| 374 |
+
|
| 375 |
+
# First try: split by paragraphs
|
| 376 |
+
paragraphs = []
|
| 377 |
+
try:
|
| 378 |
+
paragraphs = re.split(r'\n\s*\n', content)
|
| 379 |
+
paragraphs = [p.strip() for p in paragraphs if p.strip()]
|
| 380 |
+
except Exception as e:
|
| 381 |
+
logger.error(f"Error splitting paragraphs: {e}")
|
| 382 |
+
# Fallback: split by double newlines
|
| 383 |
+
paragraphs = [p.strip() for p in content.split('\n\n') if p.strip()]
|
| 384 |
+
|
| 385 |
+
chunks = []
|
| 386 |
+
current_chunk = ""
|
| 387 |
+
|
| 388 |
+
if paragraphs:
|
| 389 |
+
logger.debug(f"Processing {len(paragraphs)} paragraphs")
|
| 390 |
+
|
| 391 |
+
for i, paragraph in enumerate(paragraphs):
|
| 392 |
+
try:
|
| 393 |
+
# Skip empty paragraphs
|
| 394 |
+
if not paragraph or len(paragraph.strip()) == 0:
|
| 395 |
+
continue
|
| 396 |
+
|
| 397 |
+
# Check if this paragraph starts a new academic section
|
| 398 |
+
is_new_section = False
|
| 399 |
+
try:
|
| 400 |
+
first_line = paragraph.split('\n')[0] if '\n' in paragraph else paragraph
|
| 401 |
+
is_new_section = is_academic_section_start(first_line)
|
| 402 |
+
except Exception as e:
|
| 403 |
+
logger.warning(f"Error detecting academic section: {e}")
|
| 404 |
+
|
| 405 |
+
# If we detect a new academic section and have existing content, consider starting new chunk
|
| 406 |
+
if (is_new_section and current_chunk and
|
| 407 |
+
len(current_chunk) > min_chunk_size):
|
| 408 |
+
# Only start new chunk if current chunk is substantial
|
| 409 |
+
chunks.append(current_chunk.strip())
|
| 410 |
+
current_chunk = ""
|
| 411 |
+
logger.debug(f"Started new chunk at academic section: {first_line[:50]}...")
|
| 412 |
+
|
| 413 |
+
# If a single paragraph is too large, split it by sentences
|
| 414 |
+
if len(paragraph) > max_chunk_size:
|
| 415 |
+
logger.debug(f"Splitting large paragraph: {len(paragraph)} chars")
|
| 416 |
+
|
| 417 |
+
# If we have accumulated content, save it first
|
| 418 |
if current_chunk:
|
| 419 |
chunks.append(current_chunk.strip())
|
| 420 |
+
current_chunk = ""
|
| 421 |
+
|
| 422 |
+
# Split the large paragraph by sentences
|
| 423 |
+
sentences = []
|
| 424 |
+
try:
|
| 425 |
+
sentences = re.split(r'[.!?]+', paragraph)
|
| 426 |
+
sentences = [s.strip() for s in sentences if s.strip()]
|
| 427 |
+
except Exception as e:
|
| 428 |
+
logger.error(f"Error splitting sentences: {e}")
|
| 429 |
+
# Emergency fallback: split by fixed size
|
| 430 |
+
sentences = [paragraph[j:j+500] for j in range(0, len(paragraph), 500)]
|
| 431 |
+
|
| 432 |
+
for sentence in sentences:
|
| 433 |
+
if not sentence:
|
| 434 |
+
continue
|
| 435 |
+
|
| 436 |
+
if len(current_chunk) + len(sentence) < max_chunk_size:
|
| 437 |
+
current_chunk += sentence + ". "
|
| 438 |
+
else:
|
| 439 |
+
if current_chunk:
|
| 440 |
+
chunks.append(current_chunk.strip())
|
| 441 |
+
current_chunk = sentence + ". "
|
| 442 |
+
else:
|
| 443 |
+
# Normal paragraph processing
|
| 444 |
+
if len(current_chunk) + len(paragraph) < max_chunk_size:
|
| 445 |
+
current_chunk += paragraph + "\n\n"
|
| 446 |
+
else:
|
| 447 |
+
if current_chunk:
|
| 448 |
+
chunks.append(current_chunk.strip())
|
| 449 |
+
current_chunk = paragraph + "\n\n"
|
| 450 |
+
|
| 451 |
+
except Exception as e:
|
| 452 |
+
logger.error(f"Error processing paragraph {i}: {e}")
|
| 453 |
+
# Continue with next paragraph instead of failing completely
|
| 454 |
+
continue
|
| 455 |
+
|
| 456 |
+
else:
|
| 457 |
+
# Fallback: split by sentences if no paragraphs found
|
| 458 |
+
logger.debug("No paragraphs found, falling back to sentence splitting")
|
| 459 |
+
sentences = []
|
| 460 |
+
try:
|
| 461 |
+
sentences = re.split(r'[.!?]+', content)
|
| 462 |
+
sentences = [s.strip() for s in sentences if s.strip()]
|
| 463 |
+
except Exception as e:
|
| 464 |
+
logger.error(f"Error in sentence splitting fallback: {e}")
|
| 465 |
+
# Last resort: fixed-size chunks
|
| 466 |
+
return [content[i:i+max_chunk_size] for i in range(0, len(content), max_chunk_size)]
|
| 467 |
+
|
| 468 |
+
for sentence in sentences:
|
| 469 |
+
if not sentence:
|
| 470 |
+
continue
|
| 471 |
+
|
| 472 |
+
if len(current_chunk) + len(sentence) < max_chunk_size:
|
| 473 |
+
current_chunk += sentence + ". "
|
| 474 |
else:
|
| 475 |
if current_chunk:
|
| 476 |
chunks.append(current_chunk.strip())
|
| 477 |
+
current_chunk = sentence + ". "
|
| 478 |
+
|
| 479 |
+
# Add the last chunk if it exists
|
| 480 |
+
if current_chunk.strip():
|
| 481 |
+
chunks.append(current_chunk.strip())
|
| 482 |
+
|
| 483 |
+
# Final validation and cleanup
|
| 484 |
+
validated_chunks = []
|
| 485 |
+
for i, chunk in enumerate(chunks):
|
| 486 |
+
try:
|
| 487 |
+
chunk = chunk.strip()
|
| 488 |
+
if not chunk:
|
| 489 |
+
continue
|
| 490 |
+
|
| 491 |
+
# Merge very small chunks with previous chunk (if exists and not too large)
|
| 492 |
+
if (len(chunk) < min_chunk_size and validated_chunks and
|
| 493 |
+
len(validated_chunks[-1]) + len(chunk) < max_chunk_size * 1.5):
|
| 494 |
+
validated_chunks[-1] = validated_chunks[-1] + "\n\n" + chunk
|
| 495 |
+
logger.debug(f"Merged small chunk {i} with previous chunk")
|
| 496 |
+
|
| 497 |
+
# Split chunks that are way too large (emergency fallback)
|
| 498 |
+
elif len(chunk) > max_chunk_size * 1.5:
|
| 499 |
+
logger.warning(f"Chunk {i} too large ({len(chunk)} chars), emergency splitting")
|
| 500 |
+
# Split by fixed size as last resort
|
| 501 |
+
for j in range(0, len(chunk), max_chunk_size):
|
| 502 |
+
sub_chunk = chunk[j:j + max_chunk_size]
|
| 503 |
+
if sub_chunk.strip():
|
| 504 |
+
validated_chunks.append(sub_chunk.strip())
|
| 505 |
+
|
| 506 |
+
else:
|
| 507 |
+
validated_chunks.append(chunk)
|
| 508 |
+
|
| 509 |
+
except Exception as e:
|
| 510 |
+
logger.error(f"Error validating chunk {i}: {e}")
|
| 511 |
+
# Include the chunk anyway to avoid data loss
|
| 512 |
+
if chunk:
|
| 513 |
+
validated_chunks.append(chunk)
|
| 514 |
+
|
| 515 |
+
# Final check - ensure we have chunks
|
| 516 |
+
if not validated_chunks:
|
| 517 |
+
logger.warning("No chunks created, returning original content as single chunk")
|
| 518 |
+
return [content[:max_chunk_size]]
|
| 519 |
+
|
| 520 |
+
logger.info(f"Successfully created {len(validated_chunks)} chunks from {len(content)} chars")
|
| 521 |
+
return validated_chunks
|
| 522 |
+
|
| 523 |
+
except Exception as e:
|
| 524 |
+
logger.error(f"Critical error in chunk_content: {e}")
|
| 525 |
+
# Last resort fallback - return content as single chunk
|
| 526 |
+
if content and isinstance(content, str):
|
| 527 |
+
return [content[:max_chunk_size]]
|
| 528 |
+
return []
|
| 529 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
def build_phi3_chunk_prompt(chunk, student_level, specific_help, chunk_num, total_chunks):
|
| 531 |
"""Build Phi-3 specific prompt for a single chunk - STRICTER VERSION"""
|
| 532 |
prompt = f"""TASK: Write the actual simplified explanation for this content section.
|