Spaces:
Sleeping
Sleeping
File size: 70,698 Bytes
459923e 53b5464 459923e 1f3ea22 459923e 34603ff 459923e 34603ff 459923e 1f3ea22 459923e 34603ff 1f3ea22 34603ff 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 34603ff 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e 1f3ea22 459923e |
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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 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 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 |
import logging
import os
import sys
import asyncio
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
logger.info("Starting Hugging Face Spaces application...")
logger.info(f"Python version: {sys.version}")
try:
logger.info("Importing FastAPI...")
from fastapi import FastAPI, File, UploadFile, Form, Request, HTTPException
logger.info("Importing CORSMiddleware...")
from fastapi.middleware.cors import CORSMiddleware
logger.info("Importing JSONResponse, FileResponse...")
from fastapi.responses import JSONResponse, FileResponse, HTMLResponse
logger.info("Importing StaticFiles...")
from fastapi.staticfiles import StaticFiles
logger.info("Importing json...")
import json
logger.info("Importing OCR...")
from OCR import OCR
logger.info("Importing Grader...")
from Feedback import Grader
logger.info("Importing PDFFeedbackGenerator...")
from PDFFeedbackGenerator import PDFFeedbackGenerator
logger.info("Importing pandas...")
import pandas as pd
logger.info("Importing BytesIO...")
from io import BytesIO
logger.info("Importing tempfile...")
import tempfile
logger.info("Importing shutil...")
import shutil
logger.info("Importing typing...")
from typing import List, Dict, Any
logger.info("Importing pdf2image...")
from pdf2image import convert_from_path
logger.info("Importing platform...")
import platform
logger.info("Importing cv2...")
import cv2
logger.info("All imports successful.")
except ImportError as e:
logger.error(f"Failed to import a required module: {e}")
logger.error("Please ensure all dependencies in 'requirements.txt' are installed.")
sys.exit(1) # Exit if imports fail
app = FastAPI(
title="CSS Essay Grader API - Hugging Face Spaces",
description="API for processing and grading essays with OCR and AI feedback - Deployed on Hugging Face Spaces",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# Enable CORS for all routes
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Constants
LOGO_PATH = "cslogo.png"
TEMP_DIR = "temp"
OUTPUT_DIR = "output"
# Create necessary directories
os.makedirs(TEMP_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Initialize instances
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
raise RuntimeError("OPENAI_API_KEY environment variable not set")
ocr = OCR()
# Initialize enhanced Grader with production configuration
grader_config = {
'enable_validation': True,
'enable_enhanced_logging': True,
'fallback_to_legacy': True,
'aggregate_scores': True,
'log_missing_categories': True
}
grader = Grader(api_key=api_key, config=grader_config)
pdf_generator = PDFFeedbackGenerator(output_path=os.path.join(OUTPUT_DIR, "feedback.pdf"), logo_path=LOGO_PATH)
# Create a thread pool executor for handling long-running tasks
executor = ThreadPoolExecutor(max_workers=4)
def preprocess_essay_text(text: str) -> str:
"""
Preprocess essay text to remove problematic characters and normalize formatting.
"""
import unicodedata
# Remove control characters except newlines and tabs
text = ''.join(char for char in text if unicodedata.category(char)[0] != 'C' or char in '\n\r\t')
# Normalize Unicode characters
text = unicodedata.normalize('NFKC', text)
# Replace problematic characters
text = text.replace('\u201c', '"').replace('\u201d', '"') # Smart quotes
text = text.replace('\u2018', "'").replace('\u2019', "'") # Smart single quotes
text = text.replace('\u2013', '-').replace('\u2014', '-') # En/em dashes
text = text.replace('\u2022', '•') # Bullet points
text = text.replace('\u00a0', ' ') # Non-breaking spaces
text = text.replace('\u2026', '...') # Ellipsis
text = text.replace('\u2014', '--') # Em dash
text = text.replace('\u2013', '-') # En dash
# Clean up multiple spaces and newlines
import re
text = re.sub(r'\s+', ' ', text) # Replace multiple whitespace with single space
text = re.sub(r'\n\s*\n', '\n\n', text) # Clean up multiple newlines
return text.strip()
def process_pdf_with_poppler(file_path: str) -> tuple:
"""Process PDF file with optimized Poppler configuration."""
try:
# Use system-installed Poppler (much faster and smaller)
# Convert PDF to images with optimized settings
images = convert_from_path(
file_path,
dpi=200, # Reduced from 300 for better performance
thread_count=1, # Reduced for container environments
grayscale=True, # Smaller file size
size=(1654, 2340) # A4 size at 200 DPI
)
# Save the first page as a temporary image
temp_image_path = os.path.join(TEMP_DIR, f"temp_{os.path.basename(file_path)}.png")
images[0].save(temp_image_path, "PNG", optimize=True, quality=85)
try:
# Process with OCR using the converted image
extracted_text, accuracy_metrics = ocr.process_image_with_vision(temp_image_path)
return extracted_text, accuracy_metrics
finally:
# Clean up temporary image
if os.path.exists(temp_image_path):
os.remove(temp_image_path)
except Exception as e:
logger.error(f"Error processing PDF {file_path}: {str(e)}")
raise Exception(f"Error processing PDF: {str(e)}")
@app.get("/", response_class=HTMLResponse)
def root():
"""Root endpoint with HTML welcome page for Hugging Face Spaces."""
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>CSS Essay Grader API - Hugging Face Spaces</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
.container { max-width: 800px; margin: 0 auto; background: rgba(255,255,255,0.1); padding: 30px; border-radius: 15px; backdrop-filter: blur(10px); }
h1 { text-align: center; margin-bottom: 30px; }
.endpoint { background: rgba(255,255,255,0.2); padding: 15px; margin: 10px 0; border-radius: 8px; }
.method { font-weight: bold; color: #4CAF50; }
.url { font-family: monospace; background: rgba(0,0,0,0.3); padding: 5px; border-radius: 4px; }
.docs-link { text-align: center; margin-top: 30px; }
.docs-link a { color: #FFD700; text-decoration: none; font-weight: bold; }
.docs-link a:hover { text-decoration: underline; }
.new-feature { background: rgba(255,215,0,0.2); border-left: 4px solid #FFD700; }
</style>
</head>
<body>
<div class="container">
<h1>🎓 CSS Essay Grader API</h1>
<p>Welcome to the CSS Essay Grader API deployed on Hugging Face Spaces! This API provides comprehensive essay analysis, OCR text extraction, and AI-powered feedback.</p>
<h2>Available Endpoints:</h2>
<div class="endpoint">
<div class="method">GET</div>
<div class="url">/health</div>
<div>Health check endpoint</div>
</div>
<div class="endpoint">
<div class="method">POST</div>
<div class="url">/api/upload</div>
<div>Upload and process a single file (image or PDF)</div>
</div>
<div class="endpoint">
<div class="method">POST</div>
<div class="url">/api/upload/bulk</div>
<div>Upload and process multiple files (images or PDFs)</div>
</div>
<div class="endpoint">
<div class="method">POST</div>
<div class="url">/api/essay-analysis</div>
<div>Generate comprehensive essay analysis with AI feedback</div>
</div>
<div class="endpoint">
<div class="method">POST</div>
<div class="url">/api/feedback</div>
<div>Generate feedback for essay text</div>
</div>
<div class="endpoint new-feature">
<div class="method">POST</div>
<div class="url">/api/grammar-analysis</div>
<div><strong>NEW:</strong> Generate grammar and punctuation analysis only (line-by-line processing)</div>
</div>
<div class="endpoint new-feature">
<div class="method">POST</div>
<div class="url">/api/essay-analysis-with-question</div>
<div><strong>NEW:</strong> Generate comprehensive essay analysis based on a specific question (essay_text + question)</div>
</div>
<div class="endpoint new-feature">
<div class="method">POST</div>
<div class="url">/api/feedback-with-question</div>
<div><strong>NEW:</strong> Generate feedback for essay text based on a specific question (essay_text + question)</div>
</div>
<div class="endpoint">
<div class="method">POST</div>
<div class="url">/api/verify</div>
<div>Verify and analyze text quality</div>
</div>
<div class="docs-link">
<a href="/docs">📚 View Interactive API Documentation</a>
</div>
<div style="margin-top: 30px; padding: 20px; background: rgba(255,255,255,0.1); border-radius: 8px;">
<h3>🚀 Enhanced Features Now Available:</h3>
<ul style="text-align: left;">
<li><strong>Automatic Chunking:</strong> Long essays are automatically split and processed in chunks</li>
<li><strong>Enhanced Validation:</strong> Post-processing validation ensures complete feedback</li>
<li><strong>Improved Error Handling:</strong> Better fallback mechanisms and error recovery</li>
<li><strong>Runtime Configuration:</strong> Adjust settings without restarting the API</li>
<li><strong>Enhanced Logging:</strong> Detailed processing information and monitoring</li>
<li><strong>Backward Compatibility:</strong> All existing API contracts remain unchanged</li>
</ul>
</div>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.get("/health")
def health_check():
"""Health check endpoint."""
try:
# Check if all components are working
status = {
"status": "healthy",
"service": "CSS Essay Grader API - Hugging Face Spaces",
"components": {
"ocr": "initialized",
"grader": "initialized",
"pdf_generator": "initialized"
},
"timestamp": str(datetime.now()),
"version": "1.0.0",
"deployment": "huggingface-spaces"
}
return status
except Exception as e:
return {
"status": "unhealthy",
"service": "CSS Essay Grader API - Hugging Face Spaces",
"error": str(e),
"timestamp": str(datetime.now())
}
@app.post('/api/upload')
async def upload_file(file: UploadFile = File(...)):
"""Upload and process a single file (image or PDF)."""
try:
# Save uploaded file to temp directory
file_path = os.path.join(TEMP_DIR, file.filename)
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
try:
# Process file based on type
if file.filename.lower().endswith(".pdf"):
extracted_text, accuracy_metrics = ocr.process_pdf_file_with_vision(file_path)
else:
extracted_text, accuracy_metrics = ocr.process_image_with_vision(file_path)
# Get accuracy status and analysis
status, message = ocr.accuracy_analyzer.get_accuracy_status(accuracy_metrics)
analysis_points = ocr.accuracy_analyzer.get_detailed_analysis(accuracy_metrics)
word_count = len(extracted_text.split())
response = {
"success": True,
"extracted_text": extracted_text,
"filename": file.filename,
"word_count": word_count,
"ocr_quality": {
"status": status,
"message": message,
"analysis_points": analysis_points,
"metrics": accuracy_metrics
}
}
return response
finally:
# Clean up temp file
if os.path.exists(file_path):
os.remove(file_path)
except Exception as e:
logger.error(f"Error processing file: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@app.post('/api/upload/bulk')
async def upload_bulk_files(
files: List[UploadFile] = File(...)
):
"""Upload and process multiple files (images or PDFs)."""
if len(files) > 10: # Reduced from 15 for better performance
raise HTTPException(status_code=400, detail="You can upload a maximum of 10 files at once.")
results = []
extracted_texts = []
for file in files:
try:
# Save uploaded file to temp directory
file_path = os.path.join(TEMP_DIR, file.filename)
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# Process file based on type
if file.filename.lower().endswith(".pdf"):
try:
extracted_text, accuracy_metrics = ocr.process_pdf_file_with_vision(file_path)
except Exception as pdf_error:
logger.error(f"Error processing PDF {file.filename}: {str(pdf_error)}")
results.append({
"filename": file.filename,
"error": str(pdf_error)
})
continue
else:
extracted_text, accuracy_metrics = ocr.process_image_with_vision(file_path)
# Check OCR accuracy - Updated threshold to 20%
if accuracy_metrics.get("overall_accuracy", 0.0) < 0.2:
results.append({
"filename": file.filename,
"error": "OCR accuracy is below 20%. Please upload a clearer image or higher quality file.",
"accuracy": accuracy_metrics.get("overall_accuracy", 0.0)
})
continue
if not extracted_text.strip():
results.append({
"filename": file.filename,
"error": "No text extracted from file",
"accuracy": accuracy_metrics.get("overall_accuracy", 0.0)
})
continue
# Get accuracy status and analysis
status, message = ocr.accuracy_analyzer.get_accuracy_status(accuracy_metrics)
analysis_points = ocr.accuracy_analyzer.get_detailed_analysis(accuracy_metrics)
word_count = len(extracted_text.split())
extracted_texts.append(extracted_text)
results.append({
"filename": file.filename,
"extracted_text": extracted_text,
"word_count": word_count,
"ocr_quality": {
"status": status,
"message": message,
"analysis_points": analysis_points,
"metrics": accuracy_metrics
}
})
# Clean up temp file
os.remove(file_path)
except Exception as e:
logger.error(f"Error processing file {file.filename}: {str(e)}")
results.append({
"filename": file.filename,
"error": str(e)
})
# Combine all extracted texts
combined_text = "\n\n".join(extracted_texts) if extracted_texts else ""
# Return only results and combined_text, no feedback
return {
"results": results,
"combined_text": combined_text
}
@app.post('/api/verify')
async def verify_text(text: str = Form(...)):
"""Verify and analyze text quality."""
try:
# Simple text analysis
word_count = len(text.split())
char_count = len(text)
return {
"word_count": word_count,
"char_count": char_count,
"text_length": "short" if word_count < 100 else "medium" if word_count < 500 else "long"
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post('/api/feedback')
async def get_feedback(
essay_text: str = Form(...),
question: str = Form(None)
):
"""Generate feedback for essay text. Optionally provide a question for question-specific feedback. Now also returns line-by-line feedback."""
try:
if not essay_text.strip():
raise HTTPException(status_code=400, detail="Essay text cannot be empty")
# Preprocess the essay text to clean problematic characters
essay_text = preprocess_essay_text(essay_text)
# Enhanced logging: Check essay length and processing method
essay_length = len(essay_text)
word_count = len(essay_text.split())
token_count = grader.count_tokens(essay_text)
logger.info(f"Processing feedback request: {word_count} words, {token_count} tokens, {essay_length} characters - FULL TEXT")
# Always process full text without any chunking or truncation
# Check if question is provided for question-specific feedback
if question and question.strip():
# Generate question-specific feedback
feedback = grader.grade_answer_with_question(
essay_text,
question.strip()
)
feedback_type = "question_specific"
else:
# Generate general feedback
feedback = grader.grade_answer_with_gpt(
essay_text,
"Provide comprehensive feedback on this essay including grammar, structure, and content analysis."
)
feedback_type = "general"
# Enhanced logging: Full text processing
logger.info("Essay processed using full text method - NO TRUNCATION")
# --- NEW: Add line-by-line feedback ---
# Remove all unlimited_analysis and line_feedback logic from feedback endpoints
# Only return overall_feedback in /api/feedback
overall_feedback = feedback
# Return both overall and line-by-line feedback
return {
"feedback_type": feedback_type,
"overall_feedback": overall_feedback,
"evaluationAndScoring": overall_feedback.get("evaluationAndScoring", []),
"essayStructure": overall_feedback.get("essayStructure", []),
"issues_summary": {
"total_issues": overall_feedback.get("total_issues_found", 0),
"vocabulary_issues": overall_feedback.get("vocabulary_issues", []),
"grammar_issues": overall_feedback.get("grammar_issues", []),
"issues_by_category": {
section["label"]: {
"count": section.get("issuesCount", 0),
"issues": section.get("issuesList", [])
} for section in overall_feedback.get("evaluationAndScoring", [])
}
},
"processing_info": {
"word_count": word_count,
"token_count": token_count,
"chunked_processing": False, # No chunking in this endpoint
"chunks_used": 1 # Always 1 chunk for full text
}
}
except Exception as e:
logger.error(f"Error in get_feedback: {str(e)}")
raise HTTPException(status_code=500, detail=f"Failed to generate feedback: {str(e)}")
@app.post('/api/grammar-analysis')
async def get_grammar_analysis(
essay_text: str = Form(...)
):
"""Generate grammar and punctuation analysis only for essay text. Returns a single section with all issues aggregated."""
try:
if not essay_text.strip():
raise HTTPException(status_code=400, detail="Essay text cannot be empty")
essay_text = preprocess_essay_text(essay_text)
essay_length = len(essay_text)
word_count = len(essay_text.split())
token_count = grader.count_tokens(essay_text)
logger.info(f"Processing grammar analysis request: {word_count} words, {token_count} tokens, {essay_length} characters - FULL TEXT")
text_length = len(essay_text)
logger.info(f"Processing full essay text: {text_length} characters - NO TRUNCATION")
grammar_analysis = grader.analyze_grammar_only(essay_text)
line_by_line_grammar = grammar_analysis.get('line_by_line_grammar', [])
# Aggregate issues and positive points
all_issues = []
all_positive_points = []
all_scores = []
for line in line_by_line_grammar:
all_issues.extend(line.get('grammar_issues', []))
all_positive_points.extend(line.get('positive_points', []))
score = line.get('grammar_score')
if isinstance(score, (int, float)):
all_scores.append(score)
overall_score = int(sum(all_scores) / len(all_scores)) if all_scores else 0
analysis = grammar_analysis.get('overall_grammar_summary', {}).get('analysis', 'Grammar & Punctuation analysis completed.')
section = {
"name": "Grammar & Punctuation",
"score": overall_score,
"analysis": analysis,
"issues": all_issues,
"positive_points": list(set(all_positive_points)),
"issues_count": len(all_issues)
}
return {"feedback": {"sections": [section]}}
except Exception as e:
logger.error(f"Error in grammar analysis: {str(e)}")
raise HTTPException(status_code=500, detail=f"Failed to generate grammar analysis: {str(e)}")
@app.post('/api/essay-analysis')
async def get_essay_analysis(
essay_text: str = Form(...),
question: str = Form(None)
):
"""Generate comprehensive essay analysis with enhanced mandatory feedback for each topic/question. Optionally provide a question for question-specific analysis."""
try:
if not essay_text.strip():
raise HTTPException(status_code=400, detail="Essay text cannot be empty")
# Preprocess the essay text to clean problematic characters
essay_text = preprocess_essay_text(essay_text)
# Enhanced logging: Check essay length and processing method
essay_length = len(essay_text)
word_count = len(essay_text.split())
token_count = grader.count_tokens(essay_text)
logger.info(f"Processing essay analysis request: {word_count} words, {token_count} tokens, {essay_length} characters - FULL TEXT")
# Always process full text without any chunking or truncation
text_length = len(essay_text)
logger.info(f"Processing full essay text: {text_length} characters - NO TRUNCATION")
# Get original essay word count
original_essay_word_count = len(essay_text.split())
# Use thread pool executor for long-running tasks with timeout
loop = asyncio.get_event_loop()
# Generate rewritten essay with better error handling and timeout
try:
rephrased_analysis = await loop.run_in_executor(
executor,
lambda: grader.rephrase_text_with_gpt(essay_text)
)
rewritten_essay = rephrased_analysis.get('rephrased_text', essay_text)
except Exception as rephrase_error:
logger.error(f"Error in rephrasing: {str(rephrase_error)}")
# Fallback to original text if rephrasing fails
rewritten_essay = essay_text
rewritten_essay_word_count = len(rewritten_essay.split())
# Check if question is provided for question-specific analysis
if question and question.strip():
# Generate enhanced evaluation feedback with mandatory question-specific analysis
try:
feedback = await loop.run_in_executor(
executor,
lambda: grader.grade_answer_with_question(
essay_text,
question.strip()
)
)
analysis_type = "question_specific"
except Exception as feedback_error:
logger.error(f"Error in generating question-specific feedback: {str(feedback_error)}")
# Create a comprehensive fallback feedback structure
feedback = {
"sections": [
{
"name": "Grammar & Punctuation",
"score": 70,
"analysis": "Basic grammar analysis completed",
"issues": [],
"positive_points": ["Essay demonstrates basic grammar understanding"],
"issues_count": 0
},
{
"name": "Vocabulary Usage",
"score": 75,
"analysis": "Vocabulary analysis completed",
"issues": [],
"positive_points": ["Appropriate vocabulary usage"],
"issues_count": 0
},
{
"name": "Sentence Structure",
"score": 80,
"analysis": "Sentence structure analysis completed",
"issues": [],
"positive_points": ["Good sentence variety"],
"issues_count": 0
},
{
"name": "Content Relevance & Depth",
"score": 75,
"analysis": "Content relevance analysis completed",
"issues": [],
"positive_points": ["Content addresses the topic"],
"issues_count": 0
},
{
"name": "Argument Development",
"score": 70,
"analysis": "Argument development analysis completed",
"issues": [],
"positive_points": ["Arguments are presented"],
"issues_count": 0
},
{
"name": "Evidence & Citations",
"score": 65,
"analysis": "Evidence and citations analysis completed",
"issues": [],
"positive_points": ["Some evidence provided"],
"issues_count": 0
},
{
"name": "Structure & Organization",
"score": 75,
"analysis": "Structure and organization analysis completed",
"issues": [],
"positive_points": ["Essay has clear structure"],
"issues_count": 0
},
{
"name": "Conclusion Quality",
"score": 70,
"analysis": "Conclusion quality analysis completed",
"issues": [],
"positive_points": ["Conclusion is present"],
"issues_count": 0
}
],
"overall_score": 72,
"essay_structure": {
"Introduction & Thesis": {
"Clear Thesis Statement": {"value": True, "explanation": "Thesis statement analysis completed", "suggestions": "Consider strengthening the thesis"},
"Engaging Introduction": {"value": True, "explanation": "Introduction analysis completed", "suggestions": "Make introduction more engaging"},
"Background Context": {"value": True, "explanation": "Background context analysis completed", "suggestions": "Provide more background context"}
},
"Body Development": {
"Topic Sentences": {"value": True, "explanation": "Topic sentences analysis completed", "suggestions": "Strengthen topic sentences"},
"Supporting Evidence": {"value": True, "explanation": "Supporting evidence analysis completed", "suggestions": "Add more supporting evidence"},
"Logical Flow": {"value": True, "explanation": "Logical flow analysis completed", "suggestions": "Improve logical flow"},
"Paragraph Coherence": {"value": True, "explanation": "Paragraph coherence analysis completed", "suggestions": "Enhance paragraph coherence"}
},
"Content Quality": {
"Relevance to Topic": {"value": True, "explanation": "Topic relevance analysis completed", "suggestions": "Ensure all content is relevant"},
"Depth of Analysis": {"value": True, "explanation": "Analysis depth completed", "suggestions": "Deepen the analysis"},
"Use of Examples": {"value": True, "explanation": "Examples analysis completed", "suggestions": "Include more specific examples"},
"Critical Thinking": {"value": True, "explanation": "Critical thinking analysis completed", "suggestions": "Demonstrate more critical thinking"}
},
"Evidence & Citations": {
"Factual Accuracy": {"value": True, "explanation": "Factual accuracy analysis completed", "suggestions": "Verify all facts"},
"Source Credibility": {"value": True, "explanation": "Source credibility analysis completed", "suggestions": "Use more credible sources"},
"Proper Citations": {"value": True, "explanation": "Citations analysis completed", "suggestions": "Improve citation format"},
"Statistical Data": {"value": True, "explanation": "Statistical data analysis completed", "suggestions": "Include more statistical data"}
},
"Conclusion": {
"Summary of Arguments": {"value": True, "explanation": "Argument summary analysis completed", "suggestions": "Strengthen argument summary"},
"Policy Recommendations": {"value": True, "explanation": "Policy recommendations analysis completed", "suggestions": "Provide specific policy recommendations"},
"Future Implications": {"value": True, "explanation": "Future implications analysis completed", "suggestions": "Discuss future implications"},
"Strong Closing": {"value": True, "explanation": "Closing analysis completed", "suggestions": "Create a stronger closing"}
}
},
"question_specific_feedback": {
"question": question.strip(),
"question_relevance_score": 70,
"question_coverage": "Question coverage analysis completed",
"covered_aspects": ["Essay addresses the main question"],
"missing_aspects": ["Consider addressing additional aspects of the question"],
"strengths": ["Essay addresses the main question"],
"improvement_suggestions": ["Provide more comprehensive question coverage"]
}
}
else:
# Generate enhanced evaluation feedback with mandatory topic-specific analysis
try:
feedback = await loop.run_in_executor(
executor,
lambda: grader.grade_answer_with_gpt(
essay_text,
"Provide comprehensive mandatory feedback on this essay including grammar, structure, content analysis, and topic-specific evaluation."
)
)
analysis_type = "general"
except Exception as feedback_error:
logger.error(f"Error in generating feedback: {str(feedback_error)}")
# Create a comprehensive fallback feedback structure
feedback = {
"sections": [
{
"name": "Grammar & Punctuation",
"score": 70,
"analysis": "Basic grammar analysis completed",
"issues": [],
"positive_points": ["Essay demonstrates basic grammar understanding"],
"issues_count": 0
},
{
"name": "Vocabulary Usage",
"score": 75,
"analysis": "Vocabulary analysis completed",
"issues": [],
"positive_points": ["Appropriate vocabulary usage"],
"issues_count": 0
},
{
"name": "Sentence Structure",
"score": 80,
"analysis": "Sentence structure analysis completed",
"issues": [],
"positive_points": ["Good sentence variety"],
"issues_count": 0
},
{
"name": "Content Relevance & Depth",
"score": 75,
"analysis": "Content relevance analysis completed",
"issues": [],
"positive_points": ["Content addresses the topic"],
"issues_count": 0
},
{
"name": "Argument Development",
"score": 70,
"analysis": "Argument development analysis completed",
"issues": [],
"positive_points": ["Arguments are presented"],
"issues_count": 0
},
{
"name": "Evidence & Citations",
"score": 65,
"analysis": "Evidence and citations analysis completed",
"issues": [],
"positive_points": ["Some evidence provided"],
"issues_count": 0
},
{
"name": "Structure & Organization",
"score": 75,
"analysis": "Structure and organization analysis completed",
"issues": [],
"positive_points": ["Essay has clear structure"],
"issues_count": 0
},
{
"name": "Conclusion Quality",
"score": 70,
"analysis": "Conclusion quality analysis completed",
"issues": [],
"positive_points": ["Conclusion is present"],
"issues_count": 0
}
],
"overall_score": 72,
"essay_structure": {
"Introduction & Thesis": {
"Clear Thesis Statement": {"value": True, "explanation": "Thesis statement analysis completed", "suggestions": "Consider strengthening the thesis"},
"Engaging Introduction": {"value": True, "explanation": "Introduction analysis completed", "suggestions": "Make introduction more engaging"},
"Background Context": {"value": True, "explanation": "Background context analysis completed", "suggestions": "Provide more background context"}
},
"Body Development": {
"Topic Sentences": {"value": True, "explanation": "Topic sentences analysis completed", "suggestions": "Strengthen topic sentences"},
"Supporting Evidence": {"value": True, "explanation": "Supporting evidence analysis completed", "suggestions": "Add more supporting evidence"},
"Logical Flow": {"value": True, "explanation": "Logical flow analysis completed", "suggestions": "Improve logical flow"},
"Paragraph Coherence": {"value": True, "explanation": "Paragraph coherence analysis completed", "suggestions": "Enhance paragraph coherence"}
},
"Content Quality": {
"Relevance to Topic": {"value": True, "explanation": "Topic relevance analysis completed", "suggestions": "Ensure all content is relevant"},
"Depth of Analysis": {"value": True, "explanation": "Analysis depth completed", "suggestions": "Deepen the analysis"},
"Use of Examples": {"value": True, "explanation": "Examples analysis completed", "suggestions": "Include more specific examples"},
"Critical Thinking": {"value": True, "explanation": "Critical thinking analysis completed", "suggestions": "Demonstrate more critical thinking"}
},
"Evidence & Citations": {
"Factual Accuracy": {"value": True, "explanation": "Factual accuracy analysis completed", "suggestions": "Verify all facts"},
"Source Credibility": {"value": True, "explanation": "Source credibility analysis completed", "suggestions": "Use more credible sources"},
"Proper Citations": {"value": True, "explanation": "Citations analysis completed", "suggestions": "Improve citation format"},
"Statistical Data": {"value": True, "explanation": "Statistical data analysis completed", "suggestions": "Include more statistical data"}
},
"Conclusion": {
"Summary of Arguments": {"value": True, "explanation": "Argument summary analysis completed", "suggestions": "Strengthen argument summary"},
"Policy Recommendations": {"value": True, "explanation": "Policy recommendations analysis completed", "suggestions": "Provide specific policy recommendations"},
"Future Implications": {"value": True, "explanation": "Future implications analysis completed", "suggestions": "Discuss future implications"},
"Strong Closing": {"value": True, "explanation": "Closing analysis completed", "suggestions": "Create a stronger closing"}
}
},
"topic_specific_feedback": {
"topic_coverage": "Topic coverage analysis completed",
"missing_aspects": ["Consider addressing additional aspects of the topic"],
"strengths": ["Essay addresses the main topic"],
"improvement_suggestions": ["Provide more comprehensive topic coverage"]
}
}
# Enhanced logging: Check if chunking was used
# No chunking in this endpoint
# Extract overall score
overall_score = feedback.get("overall_score", 0)
# Transform enhanced evaluation sections to match required format
evaluation_and_scoring = []
for section in feedback.get("sections", []):
section_name = section.get("name", "")
score = section.get("score", 0)
analysis = section.get("analysis", "")
issues = section.get("issues", [])
positive_points = section.get("positive_points", [])
issues_count = section.get("issues_count", 0)
# Transform issues to match required format
issues_list = []
for issue in issues:
issues_list.append({
"before": issue.get("before", ""),
"after": issue.get("after", ""),
"explanation": issue.get("explanation", "")
})
evaluation_and_scoring.append({
"label": section_name,
"score": score,
"analysis": analysis,
"issuesCount": issues_count,
"issuesList": issues_list,
"positivePoints": positive_points
})
# Transform enhanced essay structure to match required format
essay_structure = []
original_essay_structure = feedback.get('essay_structure', {})
# Introduction & Thesis section
intro_features = []
if 'Introduction & Thesis' in original_essay_structure:
intro_data = original_essay_structure['Introduction & Thesis']
for key, value in intro_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
intro_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Introduction & Thesis",
"features": intro_features
})
# Body Development section
body_features = []
if 'Body Development' in original_essay_structure:
body_data = original_essay_structure['Body Development']
for key, value in body_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
body_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Body Development",
"features": body_features
})
# Content Quality section
content_features = []
if 'Content Quality' in original_essay_structure:
content_data = original_essay_structure['Content Quality']
for key, value in content_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
content_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Content Quality",
"features": content_features
})
# Evidence & Citations section
evidence_features = []
if 'Evidence & Citations' in original_essay_structure:
evidence_data = original_essay_structure['Evidence & Citations']
for key, value in evidence_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
evidence_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Evidence & Citations",
"features": evidence_features
})
# Conclusion section
conclusion_features = []
if 'Conclusion' in original_essay_structure:
conclusion_data = original_essay_structure['Conclusion']
for key, value in conclusion_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
conclusion_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Conclusion",
"features": conclusion_features
})
# Get question-specific feedback or topic-specific feedback
if question and question.strip():
question_feedback = feedback.get('question_specific_feedback', {})
response_data = {
"originalEssayWordCount": original_essay_word_count,
"reWrittenEssayWordCount": rewritten_essay_word_count,
"originalEssay": essay_text,
"reWrittenEssay": rewritten_essay,
"evaluationAndScoring": feedback.get("evaluationAndScoring", evaluation_and_scoring),
"essayStructure": feedback.get("essayStructure", essay_structure),
"question": question.strip(),
"questionSpecificFeedback": question_feedback,
"analysisType": analysis_type,
"issuesSummary": {
"totalIssues": feedback.get("total_issues_found", 0),
"vocabularyIssues": feedback.get("vocabulary_issues", []),
"grammarIssues": feedback.get("grammar_issues", []),
"issuesByCategory": {
section["label"]: {
"count": section.get("issuesCount", 0),
"issues": section.get("issuesList", [])
} for section in feedback.get("evaluationAndScoring", [])
}
}
}
else:
topic_feedback = feedback.get('topic_specific_feedback', {})
response_data = {
"originalEssayWordCount": original_essay_word_count,
"reWrittenEssayWordCount": rewritten_essay_word_count,
"originalEssay": essay_text,
"reWrittenEssay": rewritten_essay,
"evaluationAndScoring": feedback.get("evaluationAndScoring", evaluation_and_scoring),
"essayStructure": feedback.get("essayStructure", essay_structure),
"topicSpecificFeedback": {
"topicCoverage": topic_feedback.get('topic_coverage', 'Topic coverage analysis completed'),
"missingAspects": topic_feedback.get('missing_aspects', ['Consider additional aspects']),
"strengths": topic_feedback.get('strengths', ['Essay addresses the topic']),
"improvementSuggestions": topic_feedback.get('improvement_suggestions', ['Provide more comprehensive coverage'])
},
"analysisType": analysis_type,
"issuesSummary": {
"totalIssues": feedback.get("total_issues_found", 0),
"vocabularyIssues": feedback.get("vocabulary_issues", []),
"grammarIssues": feedback.get("grammar_issues", []),
"issuesByCategory": {
section["label"]: {
"count": section.get("issuesCount", 0),
"issues": section.get("issuesList", [])
} for section in feedback.get("evaluationAndScoring", [])
}
}
}
return response_data
except asyncio.TimeoutError:
logger.error("Essay analysis timed out")
raise HTTPException(status_code=408, detail="Analysis timed out. Please try with a shorter essay.")
except Exception as e:
logger.error(f"Error generating essay analysis: {str(e)}")
# Provide a more informative error message
error_detail = str(e)
if "Invalid control character" in error_detail:
error_detail = "The essay text contains invalid characters that cannot be processed. Please check for special characters or formatting issues."
elif "JSON" in error_detail:
error_detail = "There was an issue processing the essay analysis. Please try with a shorter or simpler text."
elif "timeout" in error_detail.lower():
error_detail = "The analysis took too long to complete. Please try with a shorter essay."
raise HTTPException(status_code=500, detail=error_detail)
@app.get('/api/download-pdf/{pdf_path:path}')
async def download_pdf(pdf_path: str):
"""Download generated PDF file."""
try:
full_path = os.path.join(OUTPUT_DIR, pdf_path)
if not os.path.exists(full_path):
raise HTTPException(status_code=404, detail="PDF file not found")
return FileResponse(
full_path,
media_type='application/pdf',
filename=os.path.basename(pdf_path)
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Hugging Face Spaces specific endpoint
@app.get("/spaces-info")
def spaces_info():
"""Information about the Hugging Face Spaces deployment."""
return {
"space_name": "CSS Essay Grader API",
"deployment": "huggingface-spaces",
"port": 7860,
"framework": "fastapi",
"features": [
"OCR Text Extraction",
"Essay Analysis",
"AI-Powered Feedback",
"PDF Processing",
"Bulk File Upload"
],
"documentation": "/docs",
"health_check": "/health"
}
@app.post('/api/feedback-with-question')
async def get_feedback_with_question(
essay_text: str = Form(...),
question: str = Form(...)
):
"""Generate feedback for essay text based on a specific question."""
try:
if not essay_text.strip():
raise HTTPException(status_code=400, detail="Essay text cannot be empty")
if not question.strip():
raise HTTPException(status_code=400, detail="Question cannot be empty")
# Preprocess the essay text to clean problematic characters
essay_text = preprocess_essay_text(essay_text)
# Generate question-specific feedback
feedback = grader.grade_answer_with_question(
essay_text,
question
)
# Generate PDF if requested
try:
pdf_path = pdf_generator.create_feedback_pdf(
"Student",
f"Essay Analysis - Question: {question}",
feedback
)
return {
"feedback": feedback,
"question": question,
"pdf_path": pdf_path
}
except Exception as pdf_error:
logger.error(f"PDF generation failed: {str(pdf_error)}")
return {
"feedback": feedback,
"question": question,
"pdf_error": str(pdf_error)
}
except Exception as e:
logger.error(f"Error generating feedback with question: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@app.post('/api/essay-analysis-with-question')
async def get_essay_analysis_with_question(
essay_text: str = Form(...),
question: str = Form(...)
):
"""Generate comprehensive essay analysis with enhanced mandatory feedback for a specific question."""
try:
if not essay_text.strip():
raise HTTPException(status_code=400, detail="Essay text cannot be empty")
if not question.strip():
raise HTTPException(status_code=400, detail="Question cannot be empty")
# Preprocess the essay text to clean problematic characters
essay_text = preprocess_essay_text(essay_text)
# Process full text without any truncation
text_length = len(essay_text)
logger.info(f"Processing full essay text: {text_length} characters - NO TRUNCATION")
# Get original essay word count
original_essay_word_count = len(essay_text.split())
# Use thread pool executor for long-running tasks with timeout
loop = asyncio.get_event_loop()
# Generate rewritten essay with better error handling and timeout
try:
rephrased_analysis = await loop.run_in_executor(
executor,
lambda: grader.rephrase_text_with_gpt(essay_text)
)
rewritten_essay = rephrased_analysis.get('rephrased_text', essay_text)
except Exception as rephrase_error:
logger.error(f"Error in rephrasing: {str(rephrase_error)}")
# Fallback to original text if rephrasing fails
rewritten_essay = essay_text
rewritten_essay_word_count = len(rewritten_essay.split())
# Generate enhanced evaluation feedback with mandatory question-specific analysis
try:
feedback = await loop.run_in_executor(
executor,
lambda: grader.grade_answer_with_question(
essay_text,
question
)
)
except Exception as feedback_error:
logger.error(f"Error in generating feedback: {str(feedback_error)}")
# Create a comprehensive fallback feedback structure
feedback = {
"sections": [
{
"name": "Grammar & Punctuation",
"score": 70,
"analysis": "Basic grammar analysis completed",
"issues": [],
"positive_points": ["Essay demonstrates basic grammar understanding"],
"issues_count": 0
},
{
"name": "Vocabulary Usage",
"score": 75,
"analysis": "Vocabulary analysis completed",
"issues": [],
"positive_points": ["Appropriate vocabulary usage"],
"issues_count": 0
},
{
"name": "Sentence Structure",
"score": 80,
"analysis": "Sentence structure analysis completed",
"issues": [],
"positive_points": ["Good sentence variety"],
"issues_count": 0
},
{
"name": "Content Relevance & Depth",
"score": 75,
"analysis": "Content relevance analysis completed",
"issues": [],
"positive_points": ["Content addresses the topic"],
"issues_count": 0
},
{
"name": "Argument Development",
"score": 70,
"analysis": "Argument development analysis completed",
"issues": [],
"positive_points": ["Arguments are presented"],
"issues_count": 0
},
{
"name": "Evidence & Citations",
"score": 65,
"analysis": "Evidence and citations analysis completed",
"issues": [],
"positive_points": ["Some evidence provided"],
"issues_count": 0
},
{
"name": "Structure & Organization",
"score": 75,
"analysis": "Structure and organization analysis completed",
"issues": [],
"positive_points": ["Essay has clear structure"],
"issues_count": 0
},
{
"name": "Conclusion Quality",
"score": 70,
"analysis": "Conclusion quality analysis completed",
"issues": [],
"positive_points": ["Conclusion is present"],
"issues_count": 0
}
],
"overall_score": 72,
"essay_structure": {
"Introduction & Thesis": {
"Clear Thesis Statement": {"value": True, "explanation": "Thesis statement analysis completed", "suggestions": "Consider strengthening the thesis"},
"Engaging Introduction": {"value": True, "explanation": "Introduction analysis completed", "suggestions": "Make introduction more engaging"},
"Background Context": {"value": True, "explanation": "Background context analysis completed", "suggestions": "Provide more background context"}
},
"Body Development": {
"Topic Sentences": {"value": True, "explanation": "Topic sentences analysis completed", "suggestions": "Strengthen topic sentences"},
"Supporting Evidence": {"value": True, "explanation": "Supporting evidence analysis completed", "suggestions": "Add more supporting evidence"},
"Logical Flow": {"value": True, "explanation": "Logical flow analysis completed", "suggestions": "Improve logical flow"},
"Paragraph Coherence": {"value": True, "explanation": "Paragraph coherence analysis completed", "suggestions": "Enhance paragraph coherence"}
},
"Content Quality": {
"Relevance to Topic": {"value": True, "explanation": "Topic relevance analysis completed", "suggestions": "Ensure all content is relevant"},
"Depth of Analysis": {"value": True, "explanation": "Analysis depth completed", "suggestions": "Deepen the analysis"},
"Use of Examples": {"value": True, "explanation": "Examples analysis completed", "suggestions": "Include more specific examples"},
"Critical Thinking": {"value": True, "explanation": "Critical thinking analysis completed", "suggestions": "Demonstrate more critical thinking"}
},
"Evidence & Citations": {
"Factual Accuracy": {"value": True, "explanation": "Factual accuracy analysis completed", "suggestions": "Verify all facts"},
"Source Credibility": {"value": True, "explanation": "Source credibility analysis completed", "suggestions": "Use more credible sources"},
"Proper Citations": {"value": True, "explanation": "Citations analysis completed", "suggestions": "Improve citation format"},
"Statistical Data": {"value": True, "explanation": "Statistical data analysis completed", "suggestions": "Include more statistical data"}
},
"Conclusion": {
"Summary of Arguments": {"value": True, "explanation": "Argument summary analysis completed", "suggestions": "Strengthen argument summary"},
"Policy Recommendations": {"value": True, "explanation": "Policy recommendations analysis completed", "suggestions": "Provide specific policy recommendations"},
"Future Implications": {"value": True, "explanation": "Future implications analysis completed", "suggestions": "Discuss future implications"},
"Strong Closing": {"value": True, "explanation": "Closing analysis completed", "suggestions": "Create a stronger closing"}
}
},
"question_specific_feedback": {
"question": question,
"question_relevance_score": 70,
"question_coverage": "Question coverage analysis completed",
"covered_aspects": ["Essay addresses the main question"],
"missing_aspects": ["Consider addressing additional aspects of the question"],
"strengths": ["Essay addresses the main question"],
"improvement_suggestions": ["Provide more comprehensive question coverage"]
}
}
# Extract overall score
overall_score = feedback.get("overall_score", 0)
# Transform enhanced evaluation sections to match required format
evaluation_and_scoring = []
for section in feedback.get("sections", []):
section_name = section.get("name", "")
score = section.get("score", 0)
analysis = section.get("analysis", "")
issues = section.get("issues", [])
positive_points = section.get("positive_points", [])
issues_count = section.get("issues_count", 0)
# Transform issues to match required format
issues_list = []
for issue in issues:
issues_list.append({
"before": issue.get("before", ""),
"after": issue.get("after", ""),
"explanation": issue.get("explanation", "")
})
evaluation_and_scoring.append({
"label": section_name,
"score": score,
"analysis": analysis,
"issuesCount": issues_count,
"issuesList": issues_list,
"positivePoints": positive_points
})
# Transform enhanced essay structure to match required format
essay_structure = []
original_essay_structure = feedback.get('essay_structure', {})
# Introduction & Thesis section
intro_features = []
if 'Introduction & Thesis' in original_essay_structure:
intro_data = original_essay_structure['Introduction & Thesis']
for key, value in intro_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
intro_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Introduction & Thesis",
"features": intro_features
})
# Body Development section
body_features = []
if 'Body Development' in original_essay_structure:
body_data = original_essay_structure['Body Development']
for key, value in body_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
body_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Body Development",
"features": body_features
})
# Content Quality section
content_features = []
if 'Content Quality' in original_essay_structure:
content_data = original_essay_structure['Content Quality']
for key, value in content_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
content_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Content Quality",
"features": content_features
})
# Evidence & Citations section
evidence_features = []
if 'Evidence & Citations' in original_essay_structure:
evidence_data = original_essay_structure['Evidence & Citations']
for key, value in evidence_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
evidence_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Evidence & Citations",
"features": evidence_features
})
# Conclusion section
conclusion_features = []
if 'Conclusion' in original_essay_structure:
conclusion_data = original_essay_structure['Conclusion']
for key, value in conclusion_data.items():
is_correct = value.get('value', True)
explanation = value.get('explanation', '')
suggestions = value.get('suggestions', '')
error_message = f"{explanation} {suggestions}".strip() if not is_correct else ""
conclusion_features.append({
"label": key,
"isCorrect": is_correct,
"errorMessage": error_message if not is_correct else None
})
essay_structure.append({
"label": "Conclusion",
"features": conclusion_features
})
# Get question-specific feedback
question_feedback = feedback.get('question_specific_feedback', {})
# Return the response in the exact format required by the API documentation
response_data = {
"originalEssayWordCount": original_essay_word_count,
"reWrittenEssayWordCount": rewritten_essay_word_count,
"originalEssay": essay_text,
"reWrittenEssay": rewritten_essay,
"evaluationAndScoring": feedback.get("evaluationAndScoring", evaluation_and_scoring),
"essayStructure": feedback.get("essayStructure", essay_structure),
"question": question,
"questionSpecificFeedback": question_feedback
}
return response_data
except Exception as e:
logger.error(f"Error in essay analysis with question: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
# For Hugging Face Spaces, we need to use port 7860
uvicorn.run(app, host="0.0.0.0", port=7860) |