Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 19,991 Bytes
e9d99da ed6dfe5 e9d99da ed6dfe5 e9d99da ed6dfe5 e9d99da ed6dfe5 e9d99da 9e3d558 e9d99da 9e3d558 e9d99da ed6dfe5 e9d99da 9e3d558 e9d99da ed6dfe5 9e3d558 e9d99da 9e3d558 e9d99da 9e3d558 e9d99da 9e3d558 e9d99da |
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 |
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
import pathlib, os, uvicorn, base64
BASE = pathlib.Path(__file__).parent
app = FastAPI()
app.mount("/static", StaticFiles(directory=BASE), name="static")
# PDF λλ ν 리 μ€μ
PDF_DIR = BASE / "pdf"
if not PDF_DIR.exists():
PDF_DIR.mkdir(parents=True)
# PDF νμΌ λͺ©λ‘ κ°μ Έμ€κΈ°
def get_pdf_files():
pdf_files = []
if PDF_DIR.exists():
pdf_files = [f for f in PDF_DIR.glob("*.pdf")]
return pdf_files
# PDF μΈλ€μΌ μμ± λ° νλ‘μ νΈ λ°μ΄ν° μ€λΉ
def generate_pdf_projects():
projects_data = []
pdf_files = get_pdf_files()
for pdf_file in pdf_files:
projects_data.append({
"path": str(pdf_file),
"name": pdf_file.stem
})
return projects_data
HTML = """
<!doctype html><html lang="ko"><head>
<meta charset="utf-8"><title>FlipBook Space</title>
<link rel="stylesheet" href="/static/flipbook.css">
<script src="/static/three.js"></script>
<script src="/static/iscroll.js"></script>
<script src="/static/mark.js"></script>
<script src="/static/mod3d.js"></script>
<script src="/static/pdf.js"></script>
<script src="/static/flipbook.js"></script>
<script src="/static/flipbook.book3.js"></script>
<script src="/static/flipbook.scroll.js"></script>
<script src="/static/flipbook.swipe.js"></script>
<script src="/static/flipbook.webgl.js"></script>
<style>
body{margin:0;background:#f0f0f0;font-family:sans-serif}
header{max-width:960px;margin:0 auto;padding:18px 20px;display:flex;align-items:center}
#homeBtn{display:none;width:38px;height:38px;border:none;border-radius:50%;cursor:pointer;
background:#0077c2;color:#fff;font-size:20px;margin-right:12px}
#homeBtn:hover{background:#005999}
h2{margin:0;font-size:1.5rem;font-weight:600}
#home,#viewerPage{max-width:960px;margin:0 auto;padding:0 20px 40px}
.grid{display:grid;grid-template-columns:repeat(auto-fill,180px);gap:16px;margin-top:24px}
.card{
background:#fff url('/static/book2.jpg') no-repeat center center;
background-size: 169%; /* λ°°κ²½ μ΄λ―Έμ§λ₯Ό νμ¬λ³΄λ€ 30% λ ν€μ (130% * 1.3 = 169%) */
border:1px solid #ccc;
border-radius:6px;
cursor:pointer;
box-shadow:0 2px 4px rgba(0,0,0,.12);
width: 180px;
height: 240px;
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.card img{
width:55%; /* μΈλ€μΌ ν¬κΈ° μ€μ (λ°°κ²½μ΄ μ»€μ Έμ λΉμ¨ μ μ§) */
height:auto;
object-fit:contain;
position:absolute; /* μ λ μμΉλ‘ λ³κ²½ */
top:50%; /* μλ¨μμ 50% */
left:50%; /* μ’μΈ‘μμ 50% */
transform: translate(-50%, -70%); /* μ μ€μμμ 20% μλ‘ μ΄λ */
border: 1px solid #ddd;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
.card p{
text-align:center;
margin:6px 0;
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
background: rgba(255, 255, 255, 0.7);
padding: 4px 8px;
border-radius: 4px;
width: 85%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 150px;
font-size: 11px; /* κΈ°λ³Έ 16pxμμ μ½ 30% κ°μ */
}
button.upload{all:unset;cursor:pointer;border:1px solid #bbb;padding:8px 14px;border-radius:6px;background:#fff;margin:0 8px}
#viewer{
width:90%;
height:90vh;
max-width:90%;
margin:0;
background:#fff;
border:1px solid #ddd;
border-radius:8px;
position:fixed;
top:50%;
left:50%;
transform:translate(-50%, -50%);
z-index:1000;
box-shadow:0 4px 20px rgba(0,0,0,0.15);
/* νλ©΄ λΉμ¨μ λ§κ² μ‘°μ */
max-height: calc(90vh - 40px); /* μ¬λ°± κ³ λ € */
aspect-ratio: auto; /* λΉμ¨ μλ μ‘°μ */
object-fit: contain; /* λ΄μ©λ¬Ό λΉμ¨ μ μ§ */
overflow: hidden; /* λ΄μ© λμΉ¨ λ°©μ§ */
}
/* FlipBook 컨νΈλ‘€λ° κ΄λ ¨ μ€νμΌ μ€λ²λΌμ΄λ */
.flipbook-container .fb3d-menu-bar {
z-index: 2000 !important; /* 컨νΈλ‘€λ°κ° λ€λ₯Έ μμλ³΄λ€ μμ μ€λλ‘ ν¨ */
opacity: 1 !important; /* νμ νμλλλ‘ ν¨ */
bottom: 0 !important; /* νλ¨μ κ³ μ */
background-color: rgba(0,0,0,0.7) !important; /* λ°°κ²½μ μ€μ */
border-radius: 0 0 8px 8px !important; /* νλ¨ λͺ¨μλ¦¬λ§ λ₯κΈκ² */
padding: 8px 0 !important; /* μν ν¨λ© μΆκ° */
}
.flipbook-container .fb3d-menu-bar > ul > li > img,
.flipbook-container .fb3d-menu-bar > ul > li > div {
opacity: 1 !important; /* λ©λ΄ μμ΄μ½ νμ νμ */
transform: scale(1.2) !important; /* μμ΄μ½ ν¬κΈ° μ½κ° ν€μ */
}
.flipbook-container .fb3d-menu-bar > ul > li {
margin: 0 8px !important; /* λ©λ΄ μμ΄ν
κ°κ²© μ‘°μ */
}
/* λ©λ΄ ν΄ν μ€νμΌ κ°μ */
.flipbook-container .fb3d-menu-bar > ul > li > span {
background-color: rgba(0,0,0,0.8) !important;
color: white !important;
border-radius: 4px !important;
padding: 4px 8px !important;
font-size: 12px !important;
bottom: 45px !important; /* ν΄ν μμΉ μ‘°μ */
}
</style></head><body>
<header>
<button id="homeBtn" title="νμΌλ‘">π </button>
<h2>My FlipBook Projects</h2>
</header>
<section id="home">
<div>
<label class="upload">π· μ΄λ―Έμ§ <input id="imgInput" type="file" accept="image/*" multiple hidden></label>
<label class="upload">π PDF <input id="pdfInput" type="file" accept="application/pdf" hidden></label>
</div>
<div class="grid" id="grid"></div>
</section>
<section id="viewerPage" style="display:none">
<div id="viewer"></div>
</section>
<script>
let projects=[], fb=null;
const grid=$id('grid'), viewer=$id('viewer');
pdfjsLib.GlobalWorkerOptions.workerSrc='/static/pdf.worker.js';
// μλ²μμ 미리 λ‘λλ PDF νλ‘μ νΈ
let serverProjects = [];
/* π μ€λμ€ unlock β λ΄μ₯ Audio μ κ°μ MP3 κ²½λ‘ μ¬μ© */
['click','touchstart'].forEach(evt=>{
document.addEventListener(evt,function u(){new Audio('static/turnPage2.mp3')
.play().then(a=>a.pause()).catch(()=>{});document.removeEventListener(evt,u,{capture:true});},
{once:true,capture:true});
});
/* ββ μ νΈ ββ */
function $id(id){return document.getElementById(id)}
function addCard(i,thumb,title){
const d=document.createElement('div');
d.className='card';
d.onclick=()=>open(i);
// μ λͺ© 10κΈμ μ ν λ° λ§μ€μν μ²λ¦¬
const displayTitle = title ?
(title.length > 10 ? title.substring(0, 10) + '...' : title) :
'νλ‘μ νΈ ' + (i+1);
d.innerHTML=`<img src="${thumb}"><p title="${title || 'νλ‘μ νΈ ' + (i+1)}">${displayTitle}</p>`;
grid.appendChild(d);
}
/* ββ μ΄λ―Έμ§ μ
λ‘λ ββ */
$id('imgInput').onchange=e=>{
const files=[...e.target.files]; if(!files.length) return;
const pages=[],tot=files.length;let done=0;
files.forEach((f,i)=>{const r=new FileReader();r.onload=x=>{pages[i]={src:x.target.result,thumb:x.target.result};
if(++done===tot) save(pages);};r.readAsDataURL(f);});
};
/* ββ PDF μ
λ‘λ ββ */
$id('pdfInput').onchange=e=>{
const file=e.target.files[0]; if(!file) return;
const fr=new FileReader();
fr.onload=v=>{
pdfjsLib.getDocument({data:v.target.result}).promise.then(async pdf=>{
const pages=[];
for(let p=1;p<=pdf.numPages;p++){
const pg=await pdf.getPage(p), vp=pg.getViewport({scale:1});
const c=document.createElement('canvas');c.width=vp.width;c.height=vp.height;
await pg.render({canvasContext:c.getContext('2d'),viewport:vp}).promise;
pages.push({src:c.toDataURL(),thumb:c.toDataURL()});
}
save(pages, file.name.replace('.pdf', ''));
});
};fr.readAsArrayBuffer(file);
};
/* ββ νλ‘μ νΈ μ μ₯ ββ */
function save(pages, title){
const id=projects.push(pages)-1;
addCard(id,pages[0].thumb, title);
}
/* ββ μλ² PDF λ‘λ ββ */
async function loadServerPDFs() {
try {
const response = await fetch('/api/pdf-projects');
serverProjects = await response.json();
// μλ² PDF λ‘λ λ° μΈλ€μΌ μμ±
for(let i = 0; i < serverProjects.length; i++) {
const project = serverProjects[i];
const response = await fetch(`/api/pdf-thumbnail?path=${encodeURIComponent(project.path)}`);
const data = await response.json();
if(data.thumbnail) {
const pages = [{
src: data.thumbnail,
thumb: data.thumbnail,
path: project.path
}];
save(pages, project.name);
}
}
} catch(error) {
console.error('μλ² PDF λ‘λ μ€ν¨:', error);
}
}
/* ββ μΉ΄λ β FlipBook ββ */
function open(i){
toggle(false);
const pages = projects[i];
// λ‘컬 νλ‘μ νΈ λλ μλ² PDF λ‘λ
if(fb){fb.destroy();viewer.innerHTML='';}
if(pages[0].path) {
// λ‘λ© νμ
viewer.innerHTML = '<div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;"><div style="border:4px solid #f3f3f3;border-top:4px solid #3498db;border-radius:50%;width:50px;height:50px;margin:0 auto;animation:spin 2s linear infinite;"></div><p style="margin-top:20px;font-size:16px;">PDF λ‘λ© μ€...</p></div>';
// μ€νμΌ μΆκ°
if (!document.getElementById('loadingStyle')) {
const style = document.createElement('style');
style.id = 'loadingStyle';
style.textContent = '@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}';
document.head.appendChild(style);
}
// μλ² PDF νμΌ λ‘λ
fetch(`/api/pdf-content?path=${encodeURIComponent(pages[0].path)}`)
.then(response => {
if (!response.ok) {
throw new Error('PDF λ‘λ μ€ν¨: ' + response.statusText);
}
return response.arrayBuffer();
})
.then(pdfData => {
// PDF λ°μ΄ν° λ‘λ νμΈ λ‘κΉ
console.log('PDF λ°μ΄ν° λ‘λ μλ£:', pdfData.byteLength + ' λ°μ΄νΈ');
return pdfjsLib.getDocument({data: pdfData}).promise;
})
.then(async pdf => {
console.log('PDF λ¬Έμ λ‘λ μλ£. νμ΄μ§ μ:', pdf.numPages);
const pdfPages = [];
const progressElement = viewer.querySelector('p');
for(let p = 1; p <= pdf.numPages; p++) {
if (progressElement) {
progressElement.textContent = `PDF νμ΄μ§ λ‘λ© μ€... (${p}/${pdf.numPages})`;
}
try {
const pg = await pdf.getPage(p);
const vp = pg.getViewport({scale: 1});
const c = document.createElement('canvas');
c.width = vp.width;
c.height = vp.height;
await pg.render({canvasContext: c.getContext('2d'), viewport: vp}).promise;
pdfPages.push({src: c.toDataURL(), thumb: c.toDataURL()});
} catch (pageError) {
console.error(`νμ΄μ§ ${p} λ λλ§ μ€λ₯:`, pageError);
}
}
console.log('λͺ¨λ νμ΄μ§ λ λλ§ μλ£:', pdfPages.length);
if (pdfPages.length > 0) {
createFlipBook(pdfPages);
} else {
throw new Error('PDFμμ νμ΄μ§λ₯Ό μΆμΆν μ μμ΅λλ€.');
}
})
.catch(error => {
console.error('PDF μ²λ¦¬ μ€ μ€λ₯ λ°μ:', error);
viewer.innerHTML = `<div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;"><p style="color:red;font-size:16px;">PDFλ₯Ό λ‘λνλ μ€ μ€λ₯κ° λ°μνμ΅λλ€:<br>${error.message}</p><button id="backBtn" style="margin-top:20px;padding:10px 20px;background:#0077c2;color:white;border:none;border-radius:4px;cursor:pointer;">νμΌλ‘ λμκ°κΈ°</button></div>`;
document.getElementById('backBtn').addEventListener('click', function() {
toggle(true);
});
});
} else {
// μ
λ‘λλ νλ‘μ νΈ λ³΄κΈ°
console.log('λ‘컬 μ
λ‘λλ νλ‘μ νΈ λ λλ§:', pages.length + 'νμ΄μ§');
createFlipBook(pages);
}
}
function createFlipBook(pages) {
console.log('FlipBook μμ± μμ. νμ΄μ§ μ:', pages.length);
try {
// νλ©΄ λΉμ¨ κ³μ°
const calculateAspectRatio = () => {
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const aspectRatio = windowWidth / windowHeight;
// λλΉ λλ λμ΄ κΈ°μ€μΌλ‘ μ΅λ 90% μ ν
let width, height;
if (aspectRatio > 1) { // κ°λ‘ νλ©΄
height = Math.min(windowHeight * 0.9, windowHeight - 40);
width = height * aspectRatio * 0.8; // κ°λ‘ νλ©΄μμλ μ½κ° μ€μ
if (width > windowWidth * 0.9) {
width = windowWidth * 0.9;
height = width / (aspectRatio * 0.8);
}
} else { // μΈλ‘ νλ©΄
width = Math.min(windowWidth * 0.9, windowWidth - 40);
height = width / aspectRatio * 0.9; // μΈλ‘ νλ©΄μμλ μ½κ° λλ¦Ό
if (height > windowHeight * 0.9) {
height = windowHeight * 0.9;
width = height * aspectRatio * 0.9;
}
}
// μ΅μ μ¬μ΄μ¦ λ°ν
return {
width: Math.round(width),
height: Math.round(height)
};
};
// μ΄κΈ° νλ©΄ λΉμ¨ κ³μ°
const size = calculateAspectRatio();
viewer.style.width = size.width + 'px';
viewer.style.height = size.height + 'px';
fb = new FlipBook(viewer, {
pages: pages,
viewMode: 'webgl',
autoSize: true,
flipDuration: 800,
backgroundColor: '#fff',
/* π λ΄μ₯ μ¬μ΄λ */
sound: true,
assets: {flipMp3: 'static/turnPage2.mp3', hardFlipMp3: 'static/turnPage2.mp3'},
controlsProps: {
enableFullscreen: true,
enableToc: true,
enableDownload: false,
enablePrint: false,
enableZoom: true,
enableShare: false,
enableSearch: true,
enableAutoPlay: true,
enableAnnotation: false,
enableSound: true,
enableLightbox: false,
layout: 10, // λ μ΄μμ μ΅μ
skin: 'light', // μ€ν¨ μ€νμΌ
autoNavigationTime: 3600, // μλ λκΉ μκ°(μ΄)
hideControls: false, // 컨νΈλ‘€ μ¨κΉ λΉνμ±ν
paddingTop: 10, // μλ¨ ν¨λ©
paddingLeft: 10, // μ’μΈ‘ ν¨λ©
paddingRight: 10, // μ°μΈ‘ ν¨λ©
paddingBottom: 10, // νλ¨ ν¨λ©
pageTextureSize: 1024, // νμ΄μ§ ν
μ€μ² ν¬κΈ°
thumbnails: true, // μ¬λ€μΌ νμ±ν
autoHideControls: false, // μλ μ¨κΉ λΉνμ±ν
controlsTimeout: 8000 // 컨νΈλ‘€ νμ μκ° μ°μ₯
}
});
// νλ©΄ ν¬κΈ° λ³κ²½ μ FlipBook ν¬κΈ° μ‘°μ
window.addEventListener('resize', () => {
if (fb) {
const newSize = calculateAspectRatio();
viewer.style.width = newSize.width + 'px';
viewer.style.height = newSize.height + 'px';
fb.resize();
}
});
// FlipBook μμ± ν 컨νΈλ‘€λ° κ°μ νμ
setTimeout(() => {
try {
// 컨νΈλ‘€λ° κ΄λ ¨ μμ μ°ΎκΈ° λ° μ€νμΌ μ μ©
const menuBars = document.querySelectorAll('.flipbook-container .fb3d-menu-bar');
if (menuBars && menuBars.length > 0) {
menuBars.forEach(menuBar => {
menuBar.style.display = 'block';
menuBar.style.opacity = '1';
menuBar.style.visibility = 'visible';
menuBar.style.zIndex = '9999';
});
}
} catch (e) {
console.warn('컨νΈλ‘€λ° μ€νμΌ μ μ© μ€ μ€λ₯:', e);
}
}, 1000);
console.log('FlipBook μμ± μλ£');
} catch (error) {
console.error('FlipBook μμ± μ€ μ€λ₯ λ°μ:', error);
alert('FlipBookμ μμ±νλ μ€ μ€λ₯κ° λ°μνμ΅λλ€: ' + error.message);
}
}
/* ββ λ€λΉκ²μ΄μ
ββ */
$id('homeBtn').onclick=()=>{
if(fb) {
fb.destroy();
viewer.innerHTML = '';
fb = null;
}
toggle(true);
};
function toggle(showHome){
$id('home').style.display=showHome?'block':'none';
$id('viewerPage').style.display=showHome?'none':'block';
$id('homeBtn').style.display=showHome?'none':'inline-block';
// μΆκ°: μ 체 νλ©΄ λͺ¨λμμ homeBtn μμΉ μ‘°μ
if(!showHome) {
$id('homeBtn').style.position = 'fixed';
$id('homeBtn').style.top = '20px';
$id('homeBtn').style.left = '20px';
$id('homeBtn').style.zIndex = '9999'; // μ΅μμ z-indexλ‘ λ³κ²½
$id('homeBtn').style.fontSize = '24px'; // ν¬κΈ° μ¦κ°
$id('homeBtn').style.width = '48px';
$id('homeBtn').style.height = '48px';
$id('homeBtn').style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)'; // κ·Έλ¦Όμ μΆκ°
// λ°°κ²½ μ€λ²λ μ΄ μΆκ°
document.body.style.backgroundColor = '#3a3a3a';
} else {
$id('homeBtn').style.position = '';
$id('homeBtn').style.top = '';
$id('homeBtn').style.left = '';
$id('homeBtn').style.zIndex = '';
$id('homeBtn').style.fontSize = '';
$id('homeBtn').style.width = '';
$id('homeBtn').style.height = '';
$id('homeBtn').style.boxShadow = '';
// λ°°κ²½ μλλλ‘
document.body.style.backgroundColor = '#f0f0f0';
}
}
// νμ΄μ§ λ‘λ μ μλ² PDF λ‘λ
window.addEventListener('DOMContentLoaded', loadServerPDFs);
</script>
</body></html>
"""
# API μλν¬μΈνΈ: PDF νλ‘μ νΈ λͺ©λ‘
@app.get("/api/pdf-projects")
async def get_pdf_projects():
return generate_pdf_projects()
# API μλν¬μΈνΈ: PDF μΈλ€μΌ μμ±
@app.get("/api/pdf-thumbnail")
async def get_pdf_thumbnail(path: str):
try:
import fitz # PyMuPDF
# PDF νμΌ μ΄κΈ°
doc = fitz.open(path)
# 첫 νμ΄μ§ κ°μ Έμ€κΈ°
if doc.page_count > 0:
page = doc[0]
# μΈλ€μΌμ© μ΄λ―Έμ§ λ λλ§ (ν΄μλ μ‘°μ )
pix = page.get_pixmap(matrix=fitz.Matrix(0.5, 0.5))
img_data = pix.tobytes("png")
# Base64 μΈμ½λ©
b64_img = base64.b64encode(img_data).decode('utf-8')
return {"thumbnail": f"data:image/png;base64,{b64_img}"}
return {"thumbnail": None}
except Exception as e:
return {"error": str(e), "thumbnail": None}
@app.get("/api/pdf-content")
async def get_pdf_content(path: str):
try:
# νμΌ μ‘΄μ¬ μ¬λΆ νμΈ
pdf_path = pathlib.Path(path)
if not pdf_path.exists():
return {"error": f"νμΌμ μ°Ύμ μ μμ΅λλ€: {path}"}, 404
# νμΌ μ½κΈ°
with open(path, "rb") as pdf_file:
content = pdf_file.read()
# νμΌλͺ
μ²λ¦¬ - URL μΈμ½λ©μΌλ‘ νκΈ λ± νΉμ λ¬Έμ μ²λ¦¬
import urllib.parse
filename = pdf_path.name
encoded_filename = urllib.parse.quote(filename)
# μλ΅ ν€λ μ€μ - RFC 6266 νμ€ μ¬μ©
headers = {
"Content-Type": "application/pdf",
"Content-Disposition": f"inline; filename=\"{encoded_filename}\"; filename*=UTF-8''{encoded_filename}"
}
# νμΌ μ½ν
μΈ μ§μ λ°ν (dictκ° μλ Response κ°μ²΄)
from fastapi.responses import Response
return Response(content=content, media_type="application/pdf")
except Exception as e:
import traceback
error_details = traceback.format_exc()
print(f"PDF μ½ν
μΈ λ‘λ μ€λ₯: {str(e)}\n{error_details}")
# μ€λ₯ μλ΅ λ°ν (JSON νμ)
from fastapi.responses import JSONResponse
return JSONResponse(content={"error": str(e)}, status_code=500)
@app.get("/", response_class=HTMLResponse)
async def root():
return HTML
if __name__ == "__main__":
uvicorn.run("app:app", host="0.0.0.0", port=int(os.getenv("PORT", 7860))) |