Spaces:
Running
Running
Update server.py
Browse files
server.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
FastAPI-sync + Gradio
|
| 3 |
"""
|
| 4 |
|
| 5 |
import logging
|
|
@@ -8,11 +8,11 @@ import tempfile
|
|
| 8 |
import traceback
|
| 9 |
import uuid
|
| 10 |
from pathlib import Path
|
| 11 |
-
from typing import List
|
| 12 |
|
| 13 |
import gradio as gr
|
| 14 |
from fastapi import FastAPI, File, HTTPException, Request, Response, UploadFile, status
|
| 15 |
-
from fastapi.responses import HTMLResponse, RedirectResponse, FileResponse
|
| 16 |
from starlette.middleware.sessions import SessionMiddleware
|
| 17 |
from starlette.responses import PlainTextResponse
|
| 18 |
from werkzeug.utils import secure_filename # type: ignore
|
|
@@ -61,15 +61,13 @@ def _allowed_file(name: str) -> bool:
|
|
| 61 |
return "." in name and name.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 62 |
|
| 63 |
|
| 64 |
-
def
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
request.url_for(endpoint), status_code=status.HTTP_303_SEE_OTHER
|
| 72 |
-
)
|
| 73 |
|
| 74 |
|
| 75 |
# --------------------------------------------------------------------------- #
|
|
@@ -77,7 +75,7 @@ def _redirect_with_flash(request: Request, message: str, endpoint: str = "index"
|
|
| 77 |
# --------------------------------------------------------------------------- #
|
| 78 |
from jinja2 import Template # noqa
|
| 79 |
|
| 80 |
-
HTML_TEMPLATE =
|
| 81 |
<!DOCTYPE html>
|
| 82 |
<html lang="en">
|
| 83 |
<head>
|
|
@@ -147,6 +145,11 @@ HTML_TEMPLATE = HTML_TEMPLATE = """
|
|
| 147 |
box-shadow: 0 4px 16px rgba(255, 255, 255, 0.1);
|
| 148 |
}
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
.upload-icon {
|
| 151 |
font-size: 48px;
|
| 152 |
color: #9ca3af;
|
|
@@ -174,6 +177,11 @@ HTML_TEMPLATE = HTML_TEMPLATE = """
|
|
| 174 |
.content-container {
|
| 175 |
min-height: 90vh;
|
| 176 |
padding: 20px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
}
|
| 178 |
|
| 179 |
.content-area {
|
|
@@ -211,11 +219,17 @@ HTML_TEMPLATE = HTML_TEMPLATE = """
|
|
| 211 |
cursor: pointer;
|
| 212 |
backdrop-filter: blur(10px);
|
| 213 |
transition: all 0.2s ease;
|
| 214 |
-
opacity:
|
| 215 |
z-index: 1000;
|
| 216 |
white-space: nowrap;
|
| 217 |
width: auto;
|
| 218 |
max-width: fit-content;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
}
|
| 220 |
|
| 221 |
.refresh-btn:hover {
|
|
@@ -224,25 +238,36 @@ HTML_TEMPLATE = HTML_TEMPLATE = """
|
|
| 224 |
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
| 225 |
}
|
| 226 |
|
| 227 |
-
/*
|
| 228 |
-
.
|
| 229 |
position: fixed;
|
| 230 |
top: 25px;
|
| 231 |
left: 50%;
|
| 232 |
transform: translateX(-50%);
|
| 233 |
z-index: 1001;
|
| 234 |
-
}
|
| 235 |
-
|
| 236 |
-
.flash-message {
|
| 237 |
background: rgba(0, 57, 150, 0.4);
|
| 238 |
color: #fff;
|
| 239 |
padding: 12px 20px;
|
| 240 |
border-radius: 6px;
|
| 241 |
-
margin-bottom: 10px;
|
| 242 |
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3), 0 1px 2px rgba(0, 0, 0, 0.2);
|
| 243 |
font-weight: 500;
|
| 244 |
backdrop-filter: blur(10px);
|
| 245 |
text-align: center;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
}
|
| 247 |
|
| 248 |
/* Loading Animation */
|
|
@@ -272,6 +297,31 @@ HTML_TEMPLATE = HTML_TEMPLATE = """
|
|
| 272 |
100% { transform: rotate(360deg); }
|
| 273 |
}
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
/* Responsive Design */
|
| 276 |
@media (max-width: 768px) {
|
| 277 |
.upload-area {
|
|
@@ -334,136 +384,251 @@ HTML_TEMPLATE = HTML_TEMPLATE = """
|
|
| 334 |
</style>
|
| 335 |
</head>
|
| 336 |
<body>
|
| 337 |
-
<!--
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
<!-- Refresh Button (only visible after upload) -->
|
| 349 |
-
{% if session.uploaded_file %}
|
| 350 |
-
<button class="refresh-btn" onclick="refreshSession()">
|
| 351 |
-
Start over
|
| 352 |
-
</button>
|
| 353 |
-
{% endif %}
|
| 354 |
-
|
| 355 |
-
{% if not session.uploaded_file %}
|
| 356 |
-
<!-- Upload Interface -->
|
| 357 |
<h2 style="text-align: center; margin-top: 0.25rem;">Rag Document Viewer Demo</h2>
|
| 358 |
-
<div class="upload-
|
| 359 |
-
<
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
</form>
|
| 370 |
</div>
|
| 371 |
-
|
| 372 |
-
|
|
|
|
|
|
|
| 373 |
<h2 style="text-align: center; margin-top: 0.25rem;">Rag Document Viewer Demo</h2>
|
| 374 |
-
<div class="content-
|
| 375 |
-
<div class="content-
|
| 376 |
-
<
|
| 377 |
-
|
| 378 |
-
style="width: 100%; height: 100%; border: none; display: block;">
|
| 379 |
-
</iframe>
|
| 380 |
-
</div>
|
| 381 |
</div>
|
| 382 |
</div>
|
| 383 |
-
|
| 384 |
|
| 385 |
<script>
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
// Drag and drop
|
| 399 |
-
uploadArea.addEventListener('dragover', (e) => {
|
| 400 |
-
e.preventDefault();
|
| 401 |
-
uploadArea.classList.add('dragover');
|
| 402 |
-
});
|
| 403 |
-
|
| 404 |
-
uploadArea.addEventListener('dragleave', () => {
|
| 405 |
-
uploadArea.classList.remove('dragover');
|
| 406 |
-
});
|
| 407 |
-
|
| 408 |
-
uploadArea.addEventListener('drop', (e) => {
|
| 409 |
-
e.preventDefault();
|
| 410 |
-
uploadArea.classList.remove('dragover');
|
| 411 |
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 421 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
|
|
|
|
|
|
|
|
|
| 427 |
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
|
| 434 |
-
if (
|
| 435 |
-
|
| 436 |
-
fileInput.value = ''; // Clear the file input
|
| 437 |
-
window.location.href = '/file_size_error';
|
| 438 |
-
return;
|
| 439 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 440 |
|
| 441 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
}
|
| 443 |
-
}
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
}
|
| 449 |
}
|
| 450 |
-
|
|
|
|
|
|
|
|
|
|
| 451 |
// Refresh session function
|
| 452 |
-
function refreshSession() {
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
}
|
|
|
|
|
|
|
|
|
|
| 465 |
}
|
| 466 |
-
}
|
| 467 |
</script>
|
| 468 |
</body>
|
| 469 |
</html>
|
|
@@ -471,22 +636,8 @@ HTML_TEMPLATE = HTML_TEMPLATE = """
|
|
| 471 |
|
| 472 |
template = Template(HTML_TEMPLATE)
|
| 473 |
|
| 474 |
-
|
| 475 |
-
def render_template(request: Request, **ctx) -> HTMLResponse:
|
| 476 |
-
def _get_flashed_messages() -> List[str]:
|
| 477 |
-
return request.session.pop("flash_messages", [])
|
| 478 |
-
|
| 479 |
-
rendered = template.render(
|
| 480 |
-
session=request.session,
|
| 481 |
-
get_flashed_messages=_get_flashed_messages,
|
| 482 |
-
url_for=request.url_for, # make url_for available
|
| 483 |
-
**ctx,
|
| 484 |
-
)
|
| 485 |
-
return HTMLResponse(rendered)
|
| 486 |
-
|
| 487 |
-
|
| 488 |
# --------------------------------------------------------------------------- #
|
| 489 |
-
# FastAPI (synchronous)
|
| 490 |
# --------------------------------------------------------------------------- #
|
| 491 |
backend = FastAPI()
|
| 492 |
backend.add_middleware(
|
|
@@ -499,34 +650,53 @@ backend.add_middleware(
|
|
| 499 |
|
| 500 |
@backend.get("/", name="index")
|
| 501 |
def index(request: Request):
|
| 502 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 503 |
|
| 504 |
|
| 505 |
-
@backend.post("/upload")
|
| 506 |
-
def
|
| 507 |
if RAG_DV is None:
|
| 508 |
-
return
|
| 509 |
-
|
|
|
|
| 510 |
)
|
| 511 |
|
| 512 |
if not file.filename or not _allowed_file(file.filename):
|
| 513 |
-
return
|
| 514 |
-
|
|
|
|
| 515 |
)
|
| 516 |
|
| 517 |
-
#
|
| 518 |
-
# when reading them. We do the check manually:
|
| 519 |
file.file.seek(0, 2) # go to end
|
| 520 |
size = file.file.tell()
|
| 521 |
file.file.seek(0)
|
| 522 |
if size > MAX_CONTENT_LENGTH:
|
| 523 |
-
return
|
| 524 |
-
|
|
|
|
| 525 |
)
|
| 526 |
|
| 527 |
filename = secure_filename(file.filename)
|
| 528 |
if not filename:
|
| 529 |
-
return
|
| 530 |
|
| 531 |
unique_filename = f"{uuid.uuid4()}_{filename}"
|
| 532 |
dir_path = UPLOADS_DIR / Path(unique_filename).stem
|
|
@@ -539,7 +709,7 @@ def upload_file(request: Request, file: UploadFile = File(...)):
|
|
| 539 |
f_out.write(file.file.read())
|
| 540 |
except Exception as err:
|
| 541 |
logger.error(f"Failed saving upload: {err}")
|
| 542 |
-
return
|
| 543 |
|
| 544 |
# RAG_DV processing
|
| 545 |
out_path = filepath.parent / "rag_dv"
|
|
@@ -550,23 +720,29 @@ def upload_file(request: Request, file: UploadFile = File(...)):
|
|
| 550 |
filepath.unlink(missing_ok=True)
|
| 551 |
if not any(dir_path.iterdir()):
|
| 552 |
dir_path.rmdir()
|
| 553 |
-
return
|
| 554 |
-
|
|
|
|
| 555 |
)
|
| 556 |
|
| 557 |
if not (out_path / "index.html").exists():
|
| 558 |
-
return
|
| 559 |
|
| 560 |
request.session["uploaded_file"] = unique_filename
|
| 561 |
request.session["original_filename"] = filename
|
| 562 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
|
| 564 |
|
| 565 |
-
@backend.
|
| 566 |
-
def
|
| 567 |
request.session.pop("uploaded_file", None)
|
| 568 |
request.session.pop("original_filename", None)
|
| 569 |
-
return
|
| 570 |
|
| 571 |
|
| 572 |
@backend.get("/load/{filename:path}")
|
|
@@ -576,18 +752,18 @@ def load(request: Request, filename: str):
|
|
| 576 |
idx_file = filepath.parent / "rag_dv" / "index.html"
|
| 577 |
|
| 578 |
if not idx_file.exists():
|
| 579 |
-
|
| 580 |
|
| 581 |
-
logger.info(f"{filename}")
|
| 582 |
with open(idx_file, "r", encoding="utf-8") as f:
|
| 583 |
-
|
| 584 |
-
return HTMLResponse(
|
| 585 |
|
| 586 |
|
| 587 |
@backend.get("/load/assets/{asset_type}/{file_name:path}")
|
| 588 |
def load_assets(request: Request, asset_type: str, file_name: str):
|
| 589 |
if "uploaded_file" not in request.session:
|
| 590 |
-
|
| 591 |
|
| 592 |
asset_type = secure_filename(asset_type)
|
| 593 |
file_name = secure_filename(file_name)
|
|
@@ -600,32 +776,31 @@ def load_assets(request: Request, asset_type: str, file_name: str):
|
|
| 600 |
)
|
| 601 |
file_path = base / file_name
|
| 602 |
if not file_path.exists():
|
| 603 |
-
|
| 604 |
|
| 605 |
return FileResponse(file_path)
|
| 606 |
|
| 607 |
|
| 608 |
-
@backend.get("/file_size_error")
|
| 609 |
-
def file_size_error(request: Request):
|
| 610 |
-
_flash(request, "File size too large. Please upload a file smaller than 16MB.")
|
| 611 |
-
return RedirectResponse(request.url_for("index"), status_code=303)
|
| 612 |
-
|
| 613 |
-
|
| 614 |
# ----------------------------- Error handling ------------------------------ #
|
| 615 |
@backend.exception_handler(HTTPException)
|
| 616 |
def http_exception_handler(request: Request, exc: HTTPException):
|
| 617 |
if exc.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE:
|
| 618 |
-
return
|
| 619 |
-
|
|
|
|
| 620 |
)
|
| 621 |
-
return
|
|
|
|
|
|
|
|
|
|
| 622 |
|
| 623 |
|
| 624 |
@backend.exception_handler(Exception)
|
| 625 |
def unhandled_exception(request: Request, exc: Exception):
|
| 626 |
logger.error(f"Unhandled error: {exc}\n{traceback.format_exc()}")
|
| 627 |
-
return
|
| 628 |
-
|
|
|
|
| 629 |
)
|
| 630 |
|
| 631 |
|
|
|
|
| 1 |
"""
|
| 2 |
+
FastAPI-sync + Gradio with AJAX (all route handlers are now synchronous with JSON responses)
|
| 3 |
"""
|
| 4 |
|
| 5 |
import logging
|
|
|
|
| 8 |
import traceback
|
| 9 |
import uuid
|
| 10 |
from pathlib import Path
|
| 11 |
+
from typing import List, Dict, Any
|
| 12 |
|
| 13 |
import gradio as gr
|
| 14 |
from fastapi import FastAPI, File, HTTPException, Request, Response, UploadFile, status
|
| 15 |
+
from fastapi.responses import HTMLResponse, RedirectResponse, FileResponse, JSONResponse
|
| 16 |
from starlette.middleware.sessions import SessionMiddleware
|
| 17 |
from starlette.responses import PlainTextResponse
|
| 18 |
from werkzeug.utils import secure_filename # type: ignore
|
|
|
|
| 61 |
return "." in name and name.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 62 |
|
| 63 |
|
| 64 |
+
def _json_response(success: bool = True, message: str = "", data: Dict[Any, Any] = None) -> JSONResponse:
|
| 65 |
+
"""Helper to create consistent JSON responses"""
|
| 66 |
+
return JSONResponse({
|
| 67 |
+
"success": success,
|
| 68 |
+
"message": message,
|
| 69 |
+
"data": data or {}
|
| 70 |
+
})
|
|
|
|
|
|
|
| 71 |
|
| 72 |
|
| 73 |
# --------------------------------------------------------------------------- #
|
|
|
|
| 75 |
# --------------------------------------------------------------------------- #
|
| 76 |
from jinja2 import Template # noqa
|
| 77 |
|
| 78 |
+
HTML_TEMPLATE = """
|
| 79 |
<!DOCTYPE html>
|
| 80 |
<html lang="en">
|
| 81 |
<head>
|
|
|
|
| 145 |
box-shadow: 0 4px 16px rgba(255, 255, 255, 0.1);
|
| 146 |
}
|
| 147 |
|
| 148 |
+
.upload-area.uploading {
|
| 149 |
+
pointer-events: none;
|
| 150 |
+
opacity: 0.7;
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
.upload-icon {
|
| 154 |
font-size: 48px;
|
| 155 |
color: #9ca3af;
|
|
|
|
| 177 |
.content-container {
|
| 178 |
min-height: 90vh;
|
| 179 |
padding: 20px;
|
| 180 |
+
display: none;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
.content-container.active {
|
| 184 |
+
display: block;
|
| 185 |
}
|
| 186 |
|
| 187 |
.content-area {
|
|
|
|
| 219 |
cursor: pointer;
|
| 220 |
backdrop-filter: blur(10px);
|
| 221 |
transition: all 0.2s ease;
|
| 222 |
+
opacity: 0;
|
| 223 |
z-index: 1000;
|
| 224 |
white-space: nowrap;
|
| 225 |
width: auto;
|
| 226 |
max-width: fit-content;
|
| 227 |
+
pointer-events: none;
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
.refresh-btn.visible {
|
| 231 |
+
opacity: 1;
|
| 232 |
+
pointer-events: all;
|
| 233 |
}
|
| 234 |
|
| 235 |
.refresh-btn:hover {
|
|
|
|
| 238 |
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
| 239 |
}
|
| 240 |
|
| 241 |
+
/* Message Styles */
|
| 242 |
+
.message {
|
| 243 |
position: fixed;
|
| 244 |
top: 25px;
|
| 245 |
left: 50%;
|
| 246 |
transform: translateX(-50%);
|
| 247 |
z-index: 1001;
|
|
|
|
|
|
|
|
|
|
| 248 |
background: rgba(0, 57, 150, 0.4);
|
| 249 |
color: #fff;
|
| 250 |
padding: 12px 20px;
|
| 251 |
border-radius: 6px;
|
|
|
|
| 252 |
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3), 0 1px 2px rgba(0, 0, 0, 0.2);
|
| 253 |
font-weight: 500;
|
| 254 |
backdrop-filter: blur(10px);
|
| 255 |
text-align: center;
|
| 256 |
+
opacity: 0;
|
| 257 |
+
transition: opacity 0.3s ease;
|
| 258 |
+
pointer-events: none;
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
.message.success {
|
| 262 |
+
background: rgba(0, 150, 57, 0.4);
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
.message.error {
|
| 266 |
+
background: rgba(150, 0, 0, 0.4);
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
.message.visible {
|
| 270 |
+
opacity: 1;
|
| 271 |
}
|
| 272 |
|
| 273 |
/* Loading Animation */
|
|
|
|
| 297 |
100% { transform: rotate(360deg); }
|
| 298 |
}
|
| 299 |
|
| 300 |
+
/* Progress Bar */
|
| 301 |
+
.progress-container {
|
| 302 |
+
position: absolute;
|
| 303 |
+
bottom: 20px;
|
| 304 |
+
left: 20px;
|
| 305 |
+
right: 20px;
|
| 306 |
+
height: 4px;
|
| 307 |
+
background: rgba(255, 255, 255, 0.1);
|
| 308 |
+
border-radius: 2px;
|
| 309 |
+
overflow: hidden;
|
| 310 |
+
display: none;
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
.progress-container.active {
|
| 314 |
+
display: block;
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
.progress-bar {
|
| 318 |
+
height: 100%;
|
| 319 |
+
background: linear-gradient(90deg, #4f46e5, #7c3aed);
|
| 320 |
+
width: 0%;
|
| 321 |
+
transition: width 0.3s ease;
|
| 322 |
+
border-radius: 2px;
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
/* Responsive Design */
|
| 326 |
@media (max-width: 768px) {
|
| 327 |
.upload-area {
|
|
|
|
| 384 |
</style>
|
| 385 |
</head>
|
| 386 |
<body>
|
| 387 |
+
<!-- Message Display -->
|
| 388 |
+
<div class="message" id="message"></div>
|
| 389 |
+
|
| 390 |
+
<!-- Refresh Button -->
|
| 391 |
+
<button class="refresh-btn" id="refreshBtn" onclick="refreshSession()">
|
| 392 |
+
Start over
|
| 393 |
+
</button>
|
| 394 |
+
|
| 395 |
+
<!-- Upload Interface -->
|
| 396 |
+
<div class="upload-container" id="uploadContainer">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
<h2 style="text-align: center; margin-top: 0.25rem;">Rag Document Viewer Demo</h2>
|
| 398 |
+
<div class="upload-area" id="uploadArea">
|
| 399 |
+
<div class="upload-icon">📂</div>
|
| 400 |
+
<div class="upload-text">Drop your file here or click to browse</div>
|
| 401 |
+
<div class="upload-subtext">Supports: PDFs, Office Documents, OpenOffice Documents <br>(Max: 16MB)</div>
|
| 402 |
+
<input type="file" class="file-input" id="fileInput" accept=".txt,.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.odt,.odp,.ods">
|
| 403 |
+
<div class="loading" id="loading">
|
| 404 |
+
<div class="spinner"></div>
|
| 405 |
+
</div>
|
| 406 |
+
<div class="progress-container" id="progressContainer">
|
| 407 |
+
<div class="progress-bar" id="progressBar"></div>
|
| 408 |
+
</div>
|
|
|
|
| 409 |
</div>
|
| 410 |
+
</div>
|
| 411 |
+
|
| 412 |
+
<!-- Content Interface -->
|
| 413 |
+
<div class="content-container" id="contentContainer">
|
| 414 |
<h2 style="text-align: center; margin-top: 0.25rem;">Rag Document Viewer Demo</h2>
|
| 415 |
+
<div class="content-area">
|
| 416 |
+
<div class="content-iframe">
|
| 417 |
+
<iframe id="contentFrame" style="width: 100%; height: 100%; border: none; display: block;">
|
| 418 |
+
</iframe>
|
|
|
|
|
|
|
|
|
|
| 419 |
</div>
|
| 420 |
</div>
|
| 421 |
+
</div>
|
| 422 |
|
| 423 |
<script>
|
| 424 |
+
class FileUploader {
|
| 425 |
+
constructor() {
|
| 426 |
+
this.uploadArea = document.getElementById('uploadArea');
|
| 427 |
+
this.fileInput = document.getElementById('fileInput');
|
| 428 |
+
this.loading = document.getElementById('loading');
|
| 429 |
+
this.progressContainer = document.getElementById('progressContainer');
|
| 430 |
+
this.progressBar = document.getElementById('progressBar');
|
| 431 |
+
this.uploadContainer = document.getElementById('uploadContainer');
|
| 432 |
+
this.contentContainer = document.getElementById('contentContainer');
|
| 433 |
+
this.contentFrame = document.getElementById('contentFrame');
|
| 434 |
+
this.refreshBtn = document.getElementById('refreshBtn');
|
| 435 |
+
this.messageEl = document.getElementById('message');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
|
| 437 |
+
this.maxFileSize = 16 * 1024 * 1024; // 16MB
|
| 438 |
+
this.isUploading = false;
|
| 439 |
+
|
| 440 |
+
this.initEventListeners();
|
| 441 |
+
this.checkSession();
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
initEventListeners() {
|
| 445 |
+
// Click to browse
|
| 446 |
+
this.uploadArea.addEventListener('click', () => {
|
| 447 |
+
if (!this.isUploading) {
|
| 448 |
+
this.fileInput.click();
|
| 449 |
+
}
|
| 450 |
+
});
|
| 451 |
+
|
| 452 |
+
// Drag and drop
|
| 453 |
+
this.uploadArea.addEventListener('dragover', (e) => {
|
| 454 |
+
e.preventDefault();
|
| 455 |
+
if (!this.isUploading) {
|
| 456 |
+
this.uploadArea.classList.add('dragover');
|
| 457 |
}
|
| 458 |
+
});
|
| 459 |
+
|
| 460 |
+
this.uploadArea.addEventListener('dragleave', () => {
|
| 461 |
+
this.uploadArea.classList.remove('dragover');
|
| 462 |
+
});
|
| 463 |
+
|
| 464 |
+
this.uploadArea.addEventListener('drop', (e) => {
|
| 465 |
+
e.preventDefault();
|
| 466 |
+
this.uploadArea.classList.remove('dragover');
|
| 467 |
|
| 468 |
+
if (this.isUploading) return;
|
| 469 |
+
|
| 470 |
+
const files = e.dataTransfer.files;
|
| 471 |
+
if (files.length > 0) {
|
| 472 |
+
this.handleFileSelection(files[0]);
|
| 473 |
+
}
|
| 474 |
+
});
|
| 475 |
|
| 476 |
+
// File input change
|
| 477 |
+
this.fileInput.addEventListener('change', () => {
|
| 478 |
+
if (this.fileInput.files.length > 0 && !this.isUploading) {
|
| 479 |
+
this.handleFileSelection(this.fileInput.files[0]);
|
| 480 |
+
}
|
| 481 |
+
});
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
async checkSession() {
|
| 485 |
+
try {
|
| 486 |
+
const response = await fetch('/api/session');
|
| 487 |
+
const result = await response.json();
|
| 488 |
|
| 489 |
+
if (result.success && result.data.has_uploaded_file) {
|
| 490 |
+
this.showContentInterface(result.data.filename);
|
|
|
|
|
|
|
|
|
|
| 491 |
}
|
| 492 |
+
} catch (error) {
|
| 493 |
+
console.error('Session check failed:', error);
|
| 494 |
+
}
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
+
validateFile(file) {
|
| 498 |
+
// Check file size
|
| 499 |
+
if (file.size > this.maxFileSize) {
|
| 500 |
+
this.showMessage('File size too large. Please upload a file smaller than 16MB.', 'error');
|
| 501 |
+
return false;
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
// Check file type
|
| 505 |
+
const allowedExtensions = ['txt', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'odt', 'odp', 'ods'];
|
| 506 |
+
const fileExtension = file.name.split('.').pop().toLowerCase();
|
| 507 |
+
|
| 508 |
+
if (!allowedExtensions.includes(fileExtension)) {
|
| 509 |
+
this.showMessage('Invalid file type. Please upload a supported document.', 'error');
|
| 510 |
+
return false;
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
return true;
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
async handleFileSelection(file) {
|
| 517 |
+
if (!this.validateFile(file)) {
|
| 518 |
+
this.fileInput.value = '';
|
| 519 |
+
return;
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
await this.uploadFile(file);
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
async uploadFile(file) {
|
| 526 |
+
this.isUploading = true;
|
| 527 |
+
this.uploadArea.classList.add('uploading');
|
| 528 |
+
this.loading.classList.add('active');
|
| 529 |
+
this.progressContainer.classList.add('active');
|
| 530 |
+
|
| 531 |
+
const formData = new FormData();
|
| 532 |
+
formData.append('file', file);
|
| 533 |
+
|
| 534 |
+
try {
|
| 535 |
+
const xhr = new XMLHttpRequest();
|
| 536 |
|
| 537 |
+
return new Promise((resolve, reject) => {
|
| 538 |
+
xhr.upload.addEventListener('progress', (e) => {
|
| 539 |
+
if (e.lengthComputable) {
|
| 540 |
+
const percentComplete = (e.loaded / e.total) * 100;
|
| 541 |
+
this.progressBar.style.width = percentComplete + '%';
|
| 542 |
+
}
|
| 543 |
+
});
|
| 544 |
+
|
| 545 |
+
xhr.addEventListener('load', () => {
|
| 546 |
+
if (xhr.status === 200) {
|
| 547 |
+
const result = JSON.parse(xhr.responseText);
|
| 548 |
+
if (result.success) {
|
| 549 |
+
this.showMessage(result.message, 'success');
|
| 550 |
+
setTimeout(() => {
|
| 551 |
+
this.showContentInterface(result.data.filename);
|
| 552 |
+
}, 1000);
|
| 553 |
+
} else {
|
| 554 |
+
this.showMessage(result.message, 'error');
|
| 555 |
+
this.resetUploadState();
|
| 556 |
+
}
|
| 557 |
+
resolve(result);
|
| 558 |
+
} else {
|
| 559 |
+
reject(new Error('Upload failed'));
|
| 560 |
+
}
|
| 561 |
+
});
|
| 562 |
+
|
| 563 |
+
xhr.addEventListener('error', () => {
|
| 564 |
+
reject(new Error('Upload failed'));
|
| 565 |
+
});
|
| 566 |
+
|
| 567 |
+
xhr.open('POST', '/api/upload');
|
| 568 |
+
xhr.send(formData);
|
| 569 |
+
});
|
| 570 |
+
} catch (error) {
|
| 571 |
+
console.error('Upload error:', error);
|
| 572 |
+
this.showMessage('Upload failed. Please try again.', 'error');
|
| 573 |
+
this.resetUploadState();
|
| 574 |
}
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
resetUploadState() {
|
| 578 |
+
this.isUploading = false;
|
| 579 |
+
this.uploadArea.classList.remove('uploading');
|
| 580 |
+
this.loading.classList.remove('active');
|
| 581 |
+
this.progressContainer.classList.remove('active');
|
| 582 |
+
this.progressBar.style.width = '0%';
|
| 583 |
+
this.fileInput.value = '';
|
| 584 |
+
}
|
| 585 |
+
|
| 586 |
+
showContentInterface(filename) {
|
| 587 |
+
this.uploadContainer.style.display = 'none';
|
| 588 |
+
this.contentContainer.classList.add('active');
|
| 589 |
+
this.refreshBtn.classList.add('visible');
|
| 590 |
+
this.contentFrame.src = `/load/${filename}`;
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
showUploadInterface() {
|
| 594 |
+
this.uploadContainer.style.display = 'flex';
|
| 595 |
+
this.contentContainer.classList.remove('active');
|
| 596 |
+
this.refreshBtn.classList.remove('visible');
|
| 597 |
+
this.resetUploadState();
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
showMessage(message, type = 'info') {
|
| 601 |
+
this.messageEl.textContent = message;
|
| 602 |
+
this.messageEl.className = `message ${type} visible`;
|
| 603 |
+
|
| 604 |
+
setTimeout(() => {
|
| 605 |
+
this.messageEl.classList.remove('visible');
|
| 606 |
+
}, 5000);
|
| 607 |
}
|
| 608 |
}
|
| 609 |
+
|
| 610 |
+
// Initialize uploader
|
| 611 |
+
const uploader = new FileUploader();
|
| 612 |
+
|
| 613 |
// Refresh session function
|
| 614 |
+
async function refreshSession() {
|
| 615 |
+
try {
|
| 616 |
+
const response = await fetch('/api/refresh', { method: 'POST' });
|
| 617 |
+
const result = await response.json();
|
| 618 |
+
|
| 619 |
+
if (result.success) {
|
| 620 |
+
uploader.showMessage(result.message, 'success');
|
| 621 |
+
setTimeout(() => {
|
| 622 |
+
uploader.showUploadInterface();
|
| 623 |
+
}, 1000);
|
| 624 |
+
} else {
|
| 625 |
+
uploader.showMessage(result.message, 'error');
|
| 626 |
+
}
|
| 627 |
+
} catch (error) {
|
| 628 |
+
console.error('Refresh failed:', error);
|
| 629 |
+
uploader.showMessage('Refresh failed. Please try again.', 'error');
|
| 630 |
}
|
| 631 |
+
}
|
| 632 |
</script>
|
| 633 |
</body>
|
| 634 |
</html>
|
|
|
|
| 636 |
|
| 637 |
template = Template(HTML_TEMPLATE)
|
| 638 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 639 |
# --------------------------------------------------------------------------- #
|
| 640 |
+
# FastAPI (synchronous with AJAX endpoints) #
|
| 641 |
# --------------------------------------------------------------------------- #
|
| 642 |
backend = FastAPI()
|
| 643 |
backend.add_middleware(
|
|
|
|
| 650 |
|
| 651 |
@backend.get("/", name="index")
|
| 652 |
def index(request: Request):
|
| 653 |
+
return HTMLResponse(template.render())
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
@backend.get("/api/session")
|
| 657 |
+
def get_session_info(request: Request):
|
| 658 |
+
"""Get current session information"""
|
| 659 |
+
has_uploaded_file = "uploaded_file" in request.session
|
| 660 |
+
filename = request.session.get("uploaded_file", "")
|
| 661 |
+
original_filename = request.session.get("original_filename", "")
|
| 662 |
+
|
| 663 |
+
return _json_response(
|
| 664 |
+
success=True,
|
| 665 |
+
data={
|
| 666 |
+
"has_uploaded_file": has_uploaded_file,
|
| 667 |
+
"filename": filename,
|
| 668 |
+
"original_filename": original_filename
|
| 669 |
+
}
|
| 670 |
+
)
|
| 671 |
|
| 672 |
|
| 673 |
+
@backend.post("/api/upload")
|
| 674 |
+
def upload_file_ajax(request: Request, file: UploadFile = File(...)):
|
| 675 |
if RAG_DV is None:
|
| 676 |
+
return _json_response(
|
| 677 |
+
success=False,
|
| 678 |
+
message="RAG Document Viewer is not available. Please check installation."
|
| 679 |
)
|
| 680 |
|
| 681 |
if not file.filename or not _allowed_file(file.filename):
|
| 682 |
+
return _json_response(
|
| 683 |
+
success=False,
|
| 684 |
+
message="Invalid file type. Please upload a supported document."
|
| 685 |
)
|
| 686 |
|
| 687 |
+
# Check file size
|
|
|
|
| 688 |
file.file.seek(0, 2) # go to end
|
| 689 |
size = file.file.tell()
|
| 690 |
file.file.seek(0)
|
| 691 |
if size > MAX_CONTENT_LENGTH:
|
| 692 |
+
return _json_response(
|
| 693 |
+
success=False,
|
| 694 |
+
message="File is too large. Maximum size is 16MB."
|
| 695 |
)
|
| 696 |
|
| 697 |
filename = secure_filename(file.filename)
|
| 698 |
if not filename:
|
| 699 |
+
return _json_response(success=False, message="Invalid filename")
|
| 700 |
|
| 701 |
unique_filename = f"{uuid.uuid4()}_{filename}"
|
| 702 |
dir_path = UPLOADS_DIR / Path(unique_filename).stem
|
|
|
|
| 709 |
f_out.write(file.file.read())
|
| 710 |
except Exception as err:
|
| 711 |
logger.error(f"Failed saving upload: {err}")
|
| 712 |
+
return _json_response(success=False, message="Failed to save uploaded file")
|
| 713 |
|
| 714 |
# RAG_DV processing
|
| 715 |
out_path = filepath.parent / "rag_dv"
|
|
|
|
| 720 |
filepath.unlink(missing_ok=True)
|
| 721 |
if not any(dir_path.iterdir()):
|
| 722 |
dir_path.rmdir()
|
| 723 |
+
return _json_response(
|
| 724 |
+
success=False,
|
| 725 |
+
message="Failed to process document. Please try again."
|
| 726 |
)
|
| 727 |
|
| 728 |
if not (out_path / "index.html").exists():
|
| 729 |
+
return _json_response(success=False, message="Document processing incomplete.")
|
| 730 |
|
| 731 |
request.session["uploaded_file"] = unique_filename
|
| 732 |
request.session["original_filename"] = filename
|
| 733 |
+
|
| 734 |
+
return _json_response(
|
| 735 |
+
success=True,
|
| 736 |
+
message="File successfully uploaded and processed.",
|
| 737 |
+
data={"filename": unique_filename, "original_filename": filename}
|
| 738 |
+
)
|
| 739 |
|
| 740 |
|
| 741 |
+
@backend.post("/api/refresh")
|
| 742 |
+
def refresh_session_ajax(request: Request):
|
| 743 |
request.session.pop("uploaded_file", None)
|
| 744 |
request.session.pop("original_filename", None)
|
| 745 |
+
return _json_response(success=True, message="Session refreshed successfully.")
|
| 746 |
|
| 747 |
|
| 748 |
@backend.get("/load/{filename:path}")
|
|
|
|
| 752 |
idx_file = filepath.parent / "rag_dv" / "index.html"
|
| 753 |
|
| 754 |
if not idx_file.exists():
|
| 755 |
+
raise HTTPException(status_code=404, detail="Document index not found.")
|
| 756 |
|
| 757 |
+
logger.info(f"Loading document: {filename}")
|
| 758 |
with open(idx_file, "r", encoding="utf-8") as f:
|
| 759 |
+
content = f.read()
|
| 760 |
+
return HTMLResponse(content)
|
| 761 |
|
| 762 |
|
| 763 |
@backend.get("/load/assets/{asset_type}/{file_name:path}")
|
| 764 |
def load_assets(request: Request, asset_type: str, file_name: str):
|
| 765 |
if "uploaded_file" not in request.session:
|
| 766 |
+
raise HTTPException(status_code=404, detail="No active session")
|
| 767 |
|
| 768 |
asset_type = secure_filename(asset_type)
|
| 769 |
file_name = secure_filename(file_name)
|
|
|
|
| 776 |
)
|
| 777 |
file_path = base / file_name
|
| 778 |
if not file_path.exists():
|
| 779 |
+
raise HTTPException(status_code=404, detail="Asset not found")
|
| 780 |
|
| 781 |
return FileResponse(file_path)
|
| 782 |
|
| 783 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 784 |
# ----------------------------- Error handling ------------------------------ #
|
| 785 |
@backend.exception_handler(HTTPException)
|
| 786 |
def http_exception_handler(request: Request, exc: HTTPException):
|
| 787 |
if exc.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE:
|
| 788 |
+
return _json_response(
|
| 789 |
+
success=False,
|
| 790 |
+
message="File is too large. Maximum size is 16MB."
|
| 791 |
)
|
| 792 |
+
return JSONResponse(
|
| 793 |
+
{"success": False, "message": str(exc.detail)},
|
| 794 |
+
status_code=exc.status_code
|
| 795 |
+
)
|
| 796 |
|
| 797 |
|
| 798 |
@backend.exception_handler(Exception)
|
| 799 |
def unhandled_exception(request: Request, exc: Exception):
|
| 800 |
logger.error(f"Unhandled error: {exc}\n{traceback.format_exc()}")
|
| 801 |
+
return _json_response(
|
| 802 |
+
success=False,
|
| 803 |
+
message="An unexpected error occurred. Please try again."
|
| 804 |
)
|
| 805 |
|
| 806 |
|