Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 15,438 Bytes
0c676dc 0e85825 0c676dc 0e85825 0c676dc a7a02d1 a8db41d 0c676dc a7a02d1 0c676dc a7a02d1 a8db41d 0c676dc a7a02d1 733101e a7a02d1 733101e a7a02d1 733101e a7a02d1 733101e a7a02d1 0c676dc a7a02d1 0c676dc 9c80bb4 0c676dc a7a02d1 0c676dc a7a02d1 9c80bb4 a7a02d1 9c80bb4 a7a02d1 9c80bb4 a7a02d1 9c80bb4 0c676dc a7a02d1 9c80bb4 0c676dc a7a02d1 0c676dc a7a02d1 0c676dc 9c80bb4 0c676dc 9c80bb4 733101e 9c80bb4 733101e 9c80bb4 0c676dc a7a02d1 0c676dc a7a02d1 9c80bb4 a7a02d1 9c80bb4 a7a02d1 9c80bb4 a7a02d1 9c80bb4 0c676dc a7a02d1 9c80bb4 0c676dc |
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 |
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:80%;
height:80vh; /* μ 체 νλ©΄ λμ΄μ 80%λ‘ μΆμ */
max-width:80%; /* μ΅λ λλΉ 80%λ‘ μ ν */
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);
}
</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 {
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, thumbnails: true}
});
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 = '1001'; // λ·°μ΄λ³΄λ€ λμ z-index
$id('homeBtn').style.fontSize = '24px'; // ν¬κΈ° μ¦κ°
$id('homeBtn').style.width = '48px';
$id('homeBtn').style.height = '48px';
// λ°°κ²½ μ€λ²λ μ΄ μΆκ°
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 = '';
// λ°°κ²½ μλλλ‘
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))) |