File size: 18,435 Bytes
a561338 |
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 |
from fastapi import APIRouter, UploadFile, File, HTTPException, Depends
from typing import List
from datetime import datetime
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from motor.motor_asyncio import AsyncIOMotorClient
import logging
import asyncio
import threading
from app.config import MONGODB_URI, ALGORITHM, SECRET_KEY
from app.schemas.teacher_schemas import (
TeacherLexicalBatchReport, TeacherLexicalSummary,
LexicalDocResult, LexicalMatch
)
from app.utils.file_utils import extract_text_from_file, allowed_file
from app.utils.lexical_utils import (
get_meaningful_sentences, extract_keywords,
find_exact_matches, find_partial_phrase_match,
)
from app.utils.web_utils import fetch_sources_multi_query
router = APIRouter(prefix="/teacher", tags=["teacher-lexical"])
LEXICAL_DOC_THRESHOLD = 0.85 # 85%
# β
HARD TIMEOUT: 3 minutes (180 seconds) for all queries combined
SCRAPING_TIMEOUT = 180
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("lexical_analysis")
def verify_token(token: str = Depends(oauth2_scheme)):
try:
return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except JWTError:
raise HTTPException(status_code=401, detail="Invalid or expired token")
async def get_mongo_client():
return AsyncIOMotorClient(MONGODB_URI)
def generate_five_queries(text: str) -> List[str]:
"""
Generate 5 high-quality search queries from document.
Covers: beginning, 1/4, middle, 3/4, end
"""
from app.utils.lexical_utils import get_meaningful_sentences
logger.info(" π Generating 5 lexical queries from content...")
sentences = get_meaningful_sentences(text)
if len(sentences) < 5:
logger.warning(" β οΈ Not enough sentences, using fewer queries")
# Fallback for short documents
words = text.split()
return [
' '.join(words[:30]) if len(words) > 0 else text,
' '.join(words[max(0, len(words)//4):max(0, len(words)//4)+30]) if len(words) > 30 else text,
' '.join(words[max(0, len(words)//2):max(0, len(words)//2)+30]) if len(words) > 30 else text,
]
queries = []
# β
Query 1: BEGINNING - First 3-4 sentences
beginning_end = min(4, len(sentences))
query1 = ' '.join(sentences[:beginning_end])
queries.append(query1)
logger.debug(f" Query 1 length: {len(query1.split())} words")
# β
Query 2: QUARTER-POINT - Around 25% of document
quarter_start = max(beginning_end, len(sentences) // 4)
quarter_end = min(quarter_start + 4, len(sentences))
query2 = ' '.join(sentences[quarter_start:quarter_end])
queries.append(query2)
logger.debug(f" Query 2 length: {len(query2.split())} words")
# β
Query 3: MIDDLE - Around 50% of document
mid_start = max(quarter_end, len(sentences) // 2)
mid_end = min(mid_start + 4, len(sentences))
query3 = ' '.join(sentences[mid_start:mid_end])
queries.append(query3)
logger.debug(f" Query 3 length: {len(query3.split())} words")
# β
Query 4: THREE-QUARTER-POINT - Around 75% of document
three_quarter_start = max(mid_end, int(len(sentences) * 0.75))
three_quarter_end = min(three_quarter_start + 4, len(sentences))
query4 = ' '.join(sentences[three_quarter_start:three_quarter_end])
queries.append(query4)
logger.debug(f" Query 4 length: {len(query4.split())} words")
# β
Query 5: END - Last 3-4 sentences
end_start = max(three_quarter_end, len(sentences) - 4)
query5 = ' '.join(sentences[end_start:])
queries.append(query5)
logger.debug(f" Query 5 length: {len(query5.split())} words")
# β
Validate queries
final_queries = []
for q in queries:
q = q.strip()
if len(q.split()) >= 15: # Minimum 15 words for good search
final_queries.append(q)
logger.info(f" β
Generated {len(final_queries)} queries:")
for i, q in enumerate(final_queries, 1):
word_count = len(q.split())
preview = q[:80] + "..." if len(q) > 80 else q
logger.info(f" Query {i} ({word_count} words): {preview}")
return final_queries
class ScrapingTimeoutManager:
"""Manages web scraping with hard 3-minute overall timeout"""
def __init__(self, timeout_seconds: int = 180):
self.timeout = timeout_seconds
self.start_time = None
self.sources = []
self.lock = threading.Lock()
self.cancelled = False
def elapsed(self) -> float:
"""Get elapsed time in seconds"""
if self.start_time is None:
return 0.0
return (datetime.utcnow() - self.start_time).total_seconds()
def is_timeout(self) -> bool:
"""Check if 3-minute timeout exceeded"""
return self.elapsed() >= self.timeout
async def fetch_all_sources(self, queries: List[str], num_results: int = 10) -> List:
"""
Fetch sources for all 5 queries with hard 180-second overall timeout.
Immediately stops and starts matching when timeout reached.
"""
self.start_time = datetime.utcnow()
self.sources = []
logger.info(f"\nπ WEB SCRAPING PHASE")
logger.info(f" Max Duration: {self.timeout}s (3 minutes)")
logger.info(f" Queries: {len(queries)}")
logger.info(f" Starting: {self.start_time.strftime('%H:%M:%S')}")
# Process all queries in parallel with timeout
tasks = []
for query_idx, query in enumerate(queries, 1):
logger.info(f"\n Query {query_idx}/{len(queries)}: {query[:60]}...")
tasks.append(self._fetch_query(query, num_results))
try:
# Wait for all tasks with overall timeout
await asyncio.wait_for(
asyncio.gather(*tasks, return_exceptions=True),
timeout=self.timeout
)
except asyncio.TimeoutError:
logger.warning(f"\nπ HARD TIMEOUT REACHED after {self.elapsed():.1f}s")
logger.warning(f" Cancelling all pending queries")
self.cancelled = True
# Cancel remaining tasks
for task in tasks:
if isinstance(task, asyncio.Task):
task.cancel()
# Remove duplicates
seen_urls = set()
unique_sources = []
for source in self.sources:
url = source.get('url', '')
if url and url not in seen_urls:
seen_urls.add(url)
unique_sources.append(source)
elapsed = self.elapsed()
logger.info(f"\nβ
SCRAPING PHASE STOPPED")
logger.info(f" Total Duration: {elapsed:.1f}s ({int(elapsed)//60}m {int(elapsed)%60}s)")
logger.info(f" Unique Sources: {len(unique_sources)}")
logger.info(f" Status: {'π TIMEOUT' if self.is_timeout() else 'β
COMPLETED'}")
return unique_sources
async def _fetch_query(self, query: str, num_results: int = 10):
"""Fetch sources for a single query"""
try:
sources = await asyncio.to_thread(
fetch_sources_multi_query,
query,
num_results
)
with self.lock:
self.sources.extend(sources)
logger.info(f" β
Found {len(sources)} sources")
except asyncio.CancelledError:
logger.warning(f" βοΈ Query cancelled (timeout)")
except Exception as e:
logger.error(f" β Error: {e}")
@router.post("/lexical-analysis", response_model=TeacherLexicalBatchReport)
async def teacher_lexical_analysis(
files: List[UploadFile] = File(...),
current_user=Depends(verify_token),
):
if not files:
raise HTTPException(status_code=400, detail="No files uploaded")
t0 = datetime.utcnow()
doc_results: List[LexicalDocResult] = []
total_matches = 0
logger.info(f"\n{'='*80}")
logger.info(f"π LEXICAL ANALYSIS - {len(files)} file(s)")
logger.info(f"{'='*80}")
for idx, f in enumerate(files, start=1):
if not allowed_file(f.filename):
raise HTTPException(status_code=400, detail=f"Invalid file type: {f.filename}")
raw = await f.read()
try:
text = extract_text_from_file(raw, f.filename) or ""
except ValueError as ve:
# Catch over-word files
raise HTTPException(status_code=400, detail=str(ve))
sentences = get_meaningful_sentences(text)
logger.info(f"\nπ File {idx}: {f.filename}")
logger.info(f" Sentences: {len(sentences)}")
logger.info(f" Words: {len(text.split())}")
# β
Generate 5 lexical queries
queries = generate_five_queries(text)
# β
WEB SCRAPING WITH 3-MINUTE HARD TIMEOUT (OVERALL)
scraper = ScrapingTimeoutManager(timeout_seconds=SCRAPING_TIMEOUT)
sources = await scraper.fetch_all_sources(queries, num_results=5)
# β
RESET TIMEOUT - Scraping phase is done, matching has no time limit
from app.utils import web_utils
web_utils._scraping_deadline = None
web_utils._scraping_start_time = None
logger.info(f" Total unique sources: {len(sources)}")
if not sources:
logger.warning(f" β οΈ No sources found, skipping lexical matching")
doc_results.append(LexicalDocResult(
id=idx,
name=f.filename,
author=None,
similarity=0.0,
flagged=False,
wordCount=len(text.split()),
matches=[],
content=text
))
continue
matches: List[LexicalMatch] = []
highest = 0.0
source_matches_count = {}
# β
MATCHING PHASE (starts immediately after timeout)
logger.info(f"\nπ LEXICAL MATCHING PHASE")
logger.info(f" Comparing {len(sentences)} sentences against {len(sources)} sources...")
externals = [
{
"title": s.get("url", "Unknown"),
"text": s.get("content", ""),
"source_url": s.get("url", ""),
"type": "web",
}
for s in sources if s.get("content")
]
for ext in externals:
logger.info(f" π Source: {ext['source_url'][:60]}...")
source_matches_count[ext['source_url']] = 0
# Compare each sentence against ALL sources
for s in sentences:
best_overall_score = 0.0
best_overall_match = None
best_overall_src = None
for ext in externals:
# Try exact match first
sim = find_exact_matches(s, ext["text"])
if sim is not None and sim > best_overall_score:
best_overall_score = sim
best_overall_match = s
best_overall_src = ext
continue
# Try partial phrase match
pp = find_partial_phrase_match(s, ext["text"])
if pp:
phrase, score = pp
if score > best_overall_score:
best_overall_score = score
best_overall_match = phrase
best_overall_src = ext
# Add match if found and above threshold (50%)
if best_overall_match and best_overall_score > 0.0:
pct = round(best_overall_score * 100.0, 1)
if pct >= 50:
matches.append(LexicalMatch(
matched_text=best_overall_match,
similarity=pct,
source_type=best_overall_src["type"],
source_title=best_overall_src["title"],
source_url=best_overall_src["source_url"],
section=None,
context="Potential plagiarism detected",
))
source_matches_count[best_overall_src['source_url']] += 1
highest = max(highest, pct)
total_matches += 1
logger.debug(f" β
Match ({pct}%) with {best_overall_src['source_url'][:50]}")
# Better flagging logic considering multiple sources
num_sources_with_matches = sum(1 for c in source_matches_count.values() if c > 0)
avg_match_score = (sum(m.similarity for m in matches) / len(matches)) if matches else 0.0
# Flag if any of these conditions are met:
# 1. Single source with high similarity (>85%)
# 2. Content plagiarized from 2+ different sources
# 3. 3+ matches with average >70%
flagged = (
highest >= 85 or
num_sources_with_matches >= 2 or
(len(matches) >= 3 and avg_match_score >= 70)
)
logger.info(f" π Results:")
logger.info(f" Highest similarity: {highest:.1f}%")
logger.info(f" Total matches: {len(matches)}")
logger.info(f" Sources with matches: {num_sources_with_matches}")
logger.info(f" Average match score: {avg_match_score:.1f}%")
logger.info(f" Flagged: {flagged}")
doc_results.append(LexicalDocResult(
id=idx,
name=f.filename,
author=None,
similarity=round(highest, 1),
flagged=flagged,
wordCount=len(text.split()),
matches=matches,
content=text # Include full document for frontend
))
highest_any = max((d.similarity for d in doc_results), default=0.0)
avg = round(sum(d.similarity for d in doc_results) / len(doc_results), 1) if doc_results else 0.0
flagged_count = sum(1 for d in doc_results if d.flagged)
elapsed = (datetime.utcnow() - t0).total_seconds()
mm = int(elapsed // 60)
ss = int(elapsed % 60)
processing = f"{mm}m {ss:02d}s"
logger.info(f"\n{'='*80}")
logger.info(f"β
ANALYSIS COMPLETE")
logger.info(f"{'='*80}")
logger.info(f" Documents: {len(doc_results)}")
logger.info(f" Flagged: {flagged_count}")
logger.info(f" Highest: {highest_any}%")
logger.info(f" Average: {avg}%")
logger.info(f" Total Matches: {total_matches}")
logger.info(f" Total Time: {processing}\n")
result = TeacherLexicalBatchReport(
id="teacher_lexical_batch",
name="Teacher Lexical Analysis",
uploadDate=datetime.utcnow(),
processingTime=processing,
documents=doc_results,
summary=TeacherLexicalSummary(
totalDocuments=len(doc_results),
flaggedDocuments=flagged_count,
highestSimilarity=highest_any,
averageSimilarity=avg,
totalMatches=total_matches,
),
)
# Save to MongoDB
try:
mongo_client = await get_mongo_client()
db = mongo_client.sluethink
reports_collection = db.reports
# Extract unique sources from all matches
all_sources = set()
for doc in doc_results:
for match in doc.matches:
all_sources.add(match.source_url)
# Prepare document for MongoDB
report_doc = {
"name": f"Lexical_Batch_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}",
"analysisType": "lexical",
"submittedBy": current_user.get("username", "System"),
"uploadDate": datetime.utcnow().strftime("%Y-%m-%d"),
"similarity": highest_any,
"status": "completed",
"flagged": flagged_count > 0,
"fileCount": len(doc_results),
"processingTime": processing,
"avgSimilarity": avg,
"sources": list(all_sources),
"createdAt": datetime.utcnow(),
"userId": current_user.get("sub") or current_user.get("user_id"),
# Store full analysis details
"documents": [
{
"id": doc.id,
"name": doc.name,
"similarity": doc.similarity,
"flagged": doc.flagged,
"wordCount": doc.wordCount,
"matchCount": len(doc.matches),
"matches": [
{
"matched_text": m.matched_text,
"similarity": m.similarity,
"source_url": m.source_url,
"source_title": m.source_title,
"source_type": m.source_type,
}
for m in doc.matches
]
}
for doc in doc_results
],
"summary": {
"totalDocuments": result.summary.totalDocuments,
"flaggedDocuments": result.summary.flaggedDocuments,
"highestSimilarity": result.summary.highestSimilarity,
"averageSimilarity": result.summary.averageSimilarity,
"totalMatches": result.summary.totalMatches,
}
}
# Insert into MongoDB
insert_result = await reports_collection.insert_one(report_doc)
logger.info(f"πΎ Report saved to MongoDB with ID: {insert_result.inserted_id}")
# Update the result with the MongoDB ID
result.id = str(insert_result.inserted_id)
mongo_client.close()
except Exception as e:
logger.error(f"β Error saving to MongoDB: {str(e)}")
logger.info(f"\nπ§Ύ Returning report:")
logger.info(f" Total Docs: {result.summary.totalDocuments}")
logger.info(f" Flagged Docs: {result.summary.flaggedDocuments}")
logger.info(f" Avg Similarity: {result.summary.averageSimilarity}%")
logger.info(f" Highest Similarity: {result.summary.highestSimilarity}%")
logger.info(f" Total Matches: {result.summary.totalMatches}\n")
return result |