File size: 12,191 Bytes
8ac3a87
 
 
b40c73b
c81c490
8ac3a87
 
 
898cc4c
b40c73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66aed24
 
 
8ac3a87
 
 
 
 
66aed24
8ac3a87
 
 
 
 
08e6637
66aed24
 
 
 
 
 
 
 
b40c73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66aed24
b40c73b
 
 
 
 
 
 
 
 
 
 
 
66aed24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd3060e
08e6637
66aed24
 
 
 
b40c73b
 
 
66aed24
 
 
 
 
 
 
 
 
b40c73b
 
 
 
 
 
 
 
 
 
 
 
66aed24
fd3060e
66aed24
 
 
 
 
 
8ac3a87
fd3060e
66aed24
 
 
 
 
 
 
 
 
 
 
 
 
b40c73b
66aed24
 
 
fd3060e
66aed24
b40c73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66aed24
 
 
 
b40c73b
 
 
66aed24
b40c73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66aed24
fd3060e
66aed24
 
 
 
 
 
8ac3a87
b40c73b
 
 
08e6637
66aed24
08e6637
 
b40c73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ac3a87
 
66aed24
31c4a0e
 
b40c73b
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
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: 130%;  /* λ°°κ²½ 이미지 30% ν™•λŒ€ */
  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:65%;  /* 썸넀일 크기 μ‘°μ • */
  height:auto;
  object-fit:contain;
  position:absolute;  /* μ ˆλŒ€ μœ„μΉ˜λ‘œ λ³€κ²½ */
  top:50%;  /* μƒλ‹¨μ—μ„œ 50% */
  left:50%;  /* μ’ŒμΈ‘μ—μ„œ 50% */
  transform: translate(-50%, -50%);  /* 정쀑앙 배치 */
  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;
}
button.upload{all:unset;cursor:pointer;border:1px solid #bbb;padding:8px 14px;border-radius:6px;background:#fff;margin:0 8px}
#viewer{
  width:100%;
  height:100vh; /* 전체 ν™”λ©΄ λ†’μ΄λ‘œ ν™•μž₯ */
  max-width:100%; /* μ΅œλŒ€ λ„ˆλΉ„ μ œν•œ ν•΄μ œ */
  margin:0; /* λ§ˆμ§„ 제거 */
  background:#fff;
  border:none; /* ν…Œλ‘λ¦¬ 제거 */
  position:fixed; /* κ³ μ • μœ„μΉ˜ */
  top:0;
  left:0;
  z-index:1000; /* μ΅œμƒμœ„ ν‘œμ‹œ */
}
</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) {
    // μ„œλ²„ 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 = [];
        for(let p = 1; p <= pdf.numPages; p++) {
          console.log('νŽ˜μ΄μ§€ λ Œλ”λ§ 쀑:', p + '/' + pdf.numPages);
          
          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()});
        }
        
        console.log('λͺ¨λ“  νŽ˜μ΄μ§€ λ Œλ”λ§ μ™„λ£Œ:', pdfPages.length);
        createFlipBook(pdfPages);
      })
      .catch(error => {
        console.error('PDF 처리 쀑 였λ₯˜ λ°œμƒ:', error);
        alert('PDFλ₯Ό λ‘œλ“œν•˜λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: ' + error.message);
      });
  } 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=()=>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';
}

// νŽ˜μ΄μ§€ λ‘œλ“œ μ‹œ μ„œλ²„ 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()
            
        # 응닡 헀더 μ„€μ • - PDF νŒŒμΌμž„μ„ λͺ…μ‹œ
        headers = {
            "Content-Type": "application/pdf",
            "Content-Disposition": f"inline; filename={pdf_path.name}"
        }
        
        # 파일 μ½˜ν…μΈ  λ°˜ν™˜
        from fastapi.responses import Response
        return Response(content=content, headers=headers)
    except Exception as e:
        import traceback
        error_details = traceback.format_exc()
        print(f"PDF μ½˜ν…μΈ  λ‘œλ“œ 였λ₯˜: {str(e)}\n{error_details}")
        return {"error": str(e)}, 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)))