Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
| from fastapi import FastAPI, BackgroundTasks, UploadFile, File, Form, Request, Query | |
| from fastapi.responses import HTMLResponse, JSONResponse, Response, RedirectResponse | |
| from fastapi.staticfiles import StaticFiles | |
| import pathlib, os, uvicorn, base64, json, shutil, uuid, time, urllib.parse | |
| from typing import Dict, List, Any, Optional | |
| import asyncio | |
| import logging | |
| import threading | |
| import concurrent.futures | |
| from openai import OpenAI | |
| import fitz # PyMuPDF | |
| import tempfile | |
| from reportlab.lib.pagesizes import letter | |
| from reportlab.pdfgen import canvas | |
| from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer | |
| from reportlab.lib.styles import getSampleStyleSheet | |
| import io | |
| import docx2txt | |
| # ๋ก๊น ์ค์ | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
| logger = logging.getLogger(__name__) | |
| 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 ๋๋ ํ ๋ฆฌ ์ค์ (Hugging Face ์๊ตฌ ๋์คํฌ) | |
| PERMANENT_PDF_DIR = pathlib.Path("/data/pdfs") if os.path.exists("/data") else BASE / "permanent_pdfs" | |
| if not PERMANENT_PDF_DIR.exists(): | |
| PERMANENT_PDF_DIR.mkdir(parents=True) | |
| # ์บ์ ๋๋ ํ ๋ฆฌ ์ค์ | |
| CACHE_DIR = BASE / "cache" | |
| if not CACHE_DIR.exists(): | |
| CACHE_DIR.mkdir(parents=True) | |
| # PDF ๋ฉํ๋ฐ์ดํฐ ๋๋ ํ ๋ฆฌ ๋ฐ ํ์ผ ์ค์ | |
| METADATA_DIR = pathlib.Path("/data/metadata") if os.path.exists("/data") else BASE / "metadata" | |
| if not METADATA_DIR.exists(): | |
| METADATA_DIR.mkdir(parents=True) | |
| PDF_METADATA_FILE = METADATA_DIR / "pdf_metadata.json" | |
| # ์๋ฒ ๋ฉ ์บ์ ๋๋ ํ ๋ฆฌ ์ค์ | |
| EMBEDDING_DIR = pathlib.Path("/data/embeddings") if os.path.exists("/data") else BASE / "embeddings" | |
| if not EMBEDDING_DIR.exists(): | |
| EMBEDDING_DIR.mkdir(parents=True) | |
| # ๊ด๋ฆฌ์ ๋น๋ฐ๋ฒํธ | |
| ADMIN_PASSWORD = os.getenv("PASSWORD", "admin") # ํ๊ฒฝ ๋ณ์์์ ๊ฐ์ ธ์ค๊ธฐ, ๊ธฐ๋ณธ๊ฐ์ ํ ์คํธ์ฉ | |
| # OpenAI API ํค ์ค์ | |
| OPENAI_API_KEY = os.getenv("LLM_API", "") | |
| # API ํค๊ฐ ์๊ฑฐ๋ ๋น์ด์์ ๋ ํ๋๊ทธ ์ค์ | |
| HAS_VALID_API_KEY = bool(OPENAI_API_KEY and OPENAI_API_KEY.strip()) | |
| if HAS_VALID_API_KEY: | |
| try: | |
| openai_client = OpenAI(api_key=OPENAI_API_KEY, timeout=30.0) | |
| logger.info("OpenAI ํด๋ผ์ด์ธํธ ์ด๊ธฐํ ์ฑ๊ณต") | |
| except Exception as e: | |
| logger.error(f"OpenAI ํด๋ผ์ด์ธํธ ์ด๊ธฐํ ์คํจ: {e}") | |
| HAS_VALID_API_KEY = False | |
| else: | |
| logger.warning("์ ํจํ OpenAI API ํค๊ฐ ์์ต๋๋ค. AI ๊ธฐ๋ฅ์ด ์ ํ๋ฉ๋๋ค.") | |
| openai_client = None | |
| # ์ ์ญ ์บ์ ๊ฐ์ฒด | |
| pdf_cache: Dict[str, Dict[str, Any]] = {} | |
| # ์บ์ฑ ๋ฝ | |
| cache_locks = {} | |
| # PDF ๋ฉํ๋ฐ์ดํฐ (ID to ๊ฒฝ๋ก ๋งคํ) | |
| pdf_metadata: Dict[str, str] = {} | |
| # PDF ์๋ฒ ๋ฉ ์บ์ | |
| pdf_embeddings: Dict[str, Dict[str, Any]] = {} | |
| # PDF ๋ฉํ๋ฐ์ดํฐ ๋ก๋ | |
| def load_pdf_metadata(): | |
| global pdf_metadata | |
| if PDF_METADATA_FILE.exists(): | |
| try: | |
| with open(PDF_METADATA_FILE, "r") as f: | |
| pdf_metadata = json.load(f) | |
| logger.info(f"PDF ๋ฉํ๋ฐ์ดํฐ ๋ก๋ ์๋ฃ: {len(pdf_metadata)} ํญ๋ชฉ") | |
| except Exception as e: | |
| logger.error(f"๋ฉํ๋ฐ์ดํฐ ๋ก๋ ์ค๋ฅ: {e}") | |
| pdf_metadata = {} | |
| else: | |
| pdf_metadata = {} | |
| # PDF ๋ฉํ๋ฐ์ดํฐ ์ ์ฅ | |
| def save_pdf_metadata(): | |
| try: | |
| with open(PDF_METADATA_FILE, "w") as f: | |
| json.dump(pdf_metadata, f) | |
| except Exception as e: | |
| logger.error(f"๋ฉํ๋ฐ์ดํฐ ์ ์ฅ ์ค๋ฅ: {e}") | |
| # PDF ID ์์ฑ (ํ์ผ๋ช + ํ์์คํฌํ ๊ธฐ๋ฐ) - ๋ ๋จ์ํ๊ณ ์์ ํ ๋ฐฉ์์ผ๋ก ๋ณ๊ฒฝ | |
| def generate_pdf_id(filename: str) -> str: | |
| # ํ์ผ๋ช ์์ ํ์ฅ์ ์ ๊ฑฐ | |
| base_name = os.path.splitext(filename)[0] | |
| # ์์ ํ ๋ฌธ์์ด๋ก ๋ณํ (URL ์ธ์ฝ๋ฉ ๋์ ์ง์ ๋ณํ) | |
| import re | |
| safe_name = re.sub(r'[^\w\-_]', '_', base_name.replace(" ", "_")) | |
| # ํ์์คํฌํ ์ถ๊ฐ๋ก ๊ณ ์ ์ฑ ๋ณด์ฅ | |
| timestamp = int(time.time()) | |
| # ์งง์ ์์ ๋ฌธ์์ด ์ถ๊ฐ | |
| random_suffix = uuid.uuid4().hex[:6] | |
| return f"{safe_name}_{timestamp}_{random_suffix}" | |
| # 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 get_permanent_pdf_files(): | |
| pdf_files = [] | |
| if PERMANENT_PDF_DIR.exists(): | |
| pdf_files = [f for f in PERMANENT_PDF_DIR.glob("*.pdf")] | |
| return pdf_files | |
| # PDF ์ธ๋ค์ผ ์์ฑ ๋ฐ ํ๋ก์ ํธ ๋ฐ์ดํฐ ์ค๋น | |
| def generate_pdf_projects(): | |
| projects_data = [] | |
| # ๋ฉ์ธ ๋๋ ํ ๋ฆฌ์ ์๊ตฌ ์ ์ฅ์์ ํ์ผ๋ค ๊ฐ์ ธ์ค๊ธฐ | |
| pdf_files = get_pdf_files() | |
| permanent_pdf_files = get_permanent_pdf_files() | |
| # ๋ชจ๋ ํ์ผ ํฉ์น๊ธฐ (ํ์ผ๋ช ๊ธฐ์ค์ผ๋ก ์ค๋ณต ์ ๊ฑฐ) | |
| unique_files = {} | |
| # ๋จผ์ ๋ฉ์ธ ๋๋ ํ ๋ฆฌ์ ํ์ผ๋ค ์ถ๊ฐ | |
| for file in pdf_files: | |
| unique_files[file.name] = file | |
| # ์๊ตฌ ์ ์ฅ์์ ํ์ผ๋ค ์ถ๊ฐ (๋์ผ ํ์ผ๋ช ์ด ์์ผ๋ฉด ์๊ตฌ ์ ์ฅ์ ํ์ผ ์ฐ์ ) | |
| for file in permanent_pdf_files: | |
| unique_files[file.name] = file | |
| # ์ค๋ณต ์ ๊ฑฐ๋ ํ์ผ๋ค๋ก ํ๋ก์ ํธ ๋ฐ์ดํฐ ์์ฑ | |
| for pdf_file in unique_files.values(): | |
| # ํด๋น ํ์ผ์ PDF ID ์ฐพ๊ธฐ | |
| pdf_id = None | |
| for pid, path in pdf_metadata.items(): | |
| if os.path.basename(path) == pdf_file.name: | |
| pdf_id = pid | |
| break | |
| # ID๊ฐ ์์ผ๋ฉด ์๋ก ์์ฑํ๊ณ ๋ฉํ๋ฐ์ดํฐ์ ์ถ๊ฐ | |
| if not pdf_id: | |
| pdf_id = generate_pdf_id(pdf_file.name) | |
| pdf_metadata[pdf_id] = str(pdf_file) | |
| save_pdf_metadata() | |
| projects_data.append({ | |
| "path": str(pdf_file), | |
| "name": pdf_file.stem, | |
| "id": pdf_id, | |
| "cached": pdf_file.stem in pdf_cache and pdf_cache[pdf_file.stem].get("status") == "completed" | |
| }) | |
| return projects_data | |
| # ์บ์ ํ์ผ ๊ฒฝ๋ก ์์ฑ | |
| def get_cache_path(pdf_name: str): | |
| return CACHE_DIR / f"{pdf_name}_cache.json" | |
| # ์๋ฒ ๋ฉ ์บ์ ํ์ผ ๊ฒฝ๋ก ์์ฑ | |
| def get_embedding_path(pdf_id: str): | |
| return EMBEDDING_DIR / f"{pdf_id}_embedding.json" | |
| # PDF ํ ์คํธ ์ถ์ถ ํจ์ | |
| def extract_pdf_text(pdf_path: str) -> List[Dict[str, Any]]: | |
| try: | |
| doc = fitz.open(pdf_path) | |
| chunks = [] | |
| for page_num in range(len(doc)): | |
| page = doc[page_num] | |
| text = page.get_text() | |
| # ํ์ด์ง ํ ์คํธ๊ฐ ์๋ ๊ฒฝ์ฐ๋ง ์ถ๊ฐ | |
| if text.strip(): | |
| chunks.append({ | |
| "page": page_num + 1, | |
| "text": text, | |
| "chunk_id": f"page_{page_num + 1}" | |
| }) | |
| return chunks | |
| except Exception as e: | |
| logger.error(f"PDF ํ ์คํธ ์ถ์ถ ์ค๋ฅ: {e}") | |
| return [] | |
| # PDF ID๋ก ์๋ฒ ๋ฉ ์์ฑ ๋๋ ๊ฐ์ ธ์ค๊ธฐ | |
| async def get_pdf_embedding(pdf_id: str) -> Dict[str, Any]: | |
| try: | |
| # ์๋ฒ ๋ฉ ์บ์ ํ์ธ | |
| embedding_path = get_embedding_path(pdf_id) | |
| if embedding_path.exists(): | |
| try: | |
| with open(embedding_path, "r", encoding="utf-8") as f: | |
| return json.load(f) | |
| except Exception as e: | |
| logger.error(f"์๋ฒ ๋ฉ ์บ์ ๋ก๋ ์ค๋ฅ: {e}") | |
| # PDF ๊ฒฝ๋ก ์ฐพ๊ธฐ | |
| pdf_path = get_pdf_path_by_id(pdf_id) | |
| if not pdf_path: | |
| raise ValueError(f"PDF ID {pdf_id}์ ํด๋นํ๋ ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค") | |
| # ํ ์คํธ ์ถ์ถ | |
| chunks = extract_pdf_text(pdf_path) | |
| if not chunks: | |
| raise ValueError(f"PDF์์ ํ ์คํธ๋ฅผ ์ถ์ถํ ์ ์์ต๋๋ค: {pdf_path}") | |
| # ์๋ฒ ๋ฉ ์ ์ฅ ๋ฐ ๋ฐํ | |
| embedding_data = { | |
| "pdf_id": pdf_id, | |
| "pdf_path": pdf_path, | |
| "chunks": chunks, | |
| "created_at": time.time() | |
| } | |
| # ์๋ฒ ๋ฉ ์บ์ ์ ์ฅ | |
| with open(embedding_path, "w", encoding="utf-8") as f: | |
| json.dump(embedding_data, f, ensure_ascii=False) | |
| return embedding_data | |
| except Exception as e: | |
| logger.error(f"PDF ์๋ฒ ๋ฉ ์์ฑ ์ค๋ฅ: {e}") | |
| return {"error": str(e), "pdf_id": pdf_id} | |
| # PDF ๋ด์ฉ ๊ธฐ๋ฐ ์ง์์๋ต | |
| # PDF ๋ด์ฉ ๊ธฐ๋ฐ ์ง์์๋ต ํจ์ ๊ฐ์ | |
| async def query_pdf(pdf_id: str, query: str) -> Dict[str, Any]: | |
| try: | |
| # API ํค๊ฐ ์๊ฑฐ๋ ์ ํจํ์ง ์์ ๊ฒฝ์ฐ | |
| if not HAS_VALID_API_KEY or not openai_client: | |
| return { | |
| "error": "OpenAI API ํค๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค.", | |
| "answer": "์ฃ์กํฉ๋๋ค. ํ์ฌ AI ๊ธฐ๋ฅ์ด ๋นํ์ฑํ๋์ด ์์ด ์ง๋ฌธ์ ๋ต๋ณํ ์ ์์ต๋๋ค. ์์คํ ๊ด๋ฆฌ์์๊ฒ ๋ฌธ์ํ์ธ์." | |
| } | |
| # ์๋ฒ ๋ฉ ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ | |
| embedding_data = await get_pdf_embedding(pdf_id) | |
| if "error" in embedding_data: | |
| return {"error": embedding_data["error"]} | |
| # ์ฒญํฌ ํ ์คํธ ๋ชจ์ผ๊ธฐ (์์๋ก ๊ฐ๋จํ๊ฒ ์ ์ฒด ํ ์คํธ ์ฌ์ฉ) | |
| all_text = "\n\n".join([f"Page {chunk['page']}: {chunk['text']}" for chunk in embedding_data["chunks"]]) | |
| # ์ปจํ ์คํธ ํฌ๊ธฐ๋ฅผ ๊ณ ๋ คํ์ฌ ํ ์คํธ๊ฐ ๋๋ฌด ๊ธธ๋ฉด ์๋ถ๋ถ๋ง ์ฌ์ฉ | |
| max_context_length = 60000 # ํ ํฐ ์๊ฐ ์๋ ๋ฌธ์ ์ ๊ธฐ์ค (๋๋ต์ ์ธ ์ ํ) | |
| if len(all_text) > max_context_length: | |
| all_text = all_text[:max_context_length] + "...(์ดํ ์๋ต)" | |
| # ์์คํ ํ๋กฌํํธ ์ค๋น | |
| system_prompt = """ | |
| ๋น์ ์ PDF ๋ด์ฉ์ ๊ธฐ๋ฐ์ผ๋ก ์ง๋ฌธ์ ๋ต๋ณํ๋ ๋์ฐ๋ฏธ์ ๋๋ค. ์ ๊ณต๋ PDF ์ปจํ ์คํธ ์ ๋ณด๋ง์ ์ฌ์ฉํ์ฌ ๋ต๋ณํ์ธ์. | |
| ์ปจํ ์คํธ์ ๊ด๋ จ ์ ๋ณด๊ฐ ์๋ ๊ฒฝ์ฐ, '์ ๊ณต๋ PDF์์ ํด๋น ์ ๋ณด๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค'๋ผ๊ณ ์์งํ ๋ตํ์ธ์. | |
| ๋ต๋ณ์ ๋ช ํํ๊ณ ๊ฐ๊ฒฐํ๊ฒ ์์ฑํ๊ณ , ๊ด๋ จ ํ์ด์ง ๋ฒํธ๋ฅผ ์ธ์ฉํ์ธ์. ๋ฐ๋์ ๊ณต์ํ ๋งํฌ๋ก ์น์ ํ๊ฒ ์๋ตํ์ธ์. | |
| """ | |
| # gpt-4.1-mini ๋ชจ๋ธ ์ฌ์ฉ | |
| try: | |
| # ํ์์์ ๋ฐ ์ฌ์๋ ์ค์ ๊ฐ์ | |
| for attempt in range(3): # ์ต๋ 3๋ฒ ์ฌ์๋ | |
| try: | |
| response = openai_client.chat.completions.create( | |
| model="gpt-4.1-mini", | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": f"๋ค์ PDF ๋ด์ฉ์ ์ฐธ๊ณ ํ์ฌ ์ง๋ฌธ์ ๋ต๋ณํด์ฃผ์ธ์.\n\nPDF ๋ด์ฉ:\n{all_text}\n\n์ง๋ฌธ: {query}"} | |
| ], | |
| temperature=0.7, | |
| max_tokens=2048, | |
| timeout=30.0 # 30์ด ํ์์์ | |
| ) | |
| answer = response.choices[0].message.content | |
| return { | |
| "answer": answer, | |
| "pdf_id": pdf_id, | |
| "query": query | |
| } | |
| except Exception as api_error: | |
| logger.error(f"OpenAI API ํธ์ถ ์ค๋ฅ (์๋ {attempt+1}/3): {api_error}") | |
| if attempt == 2: # ๋ง์ง๋ง ์๋์์๋ ์คํจ | |
| raise api_error | |
| await asyncio.sleep(1 * (attempt + 1)) # ์ฌ์๋ ๊ฐ ์ง์ฐ ์๊ฐ ์ฆ๊ฐ | |
| # ์ฌ๊ธฐ๊น์ง ๋๋ฌํ์ง ์์์ผ ํจ | |
| raise Exception("API ํธ์ถ ์ฌ์๋ ๋ชจ๋ ์คํจ") | |
| except Exception as api_error: | |
| logger.error(f"OpenAI API ํธ์ถ ์ต์ข ์ค๋ฅ: {api_error}") | |
| # ์ค๋ฅ ์ ํ์ ๋ฐ๋ฅธ ๋ ๋ช ํํ ๋ฉ์์ง ์ ๊ณต | |
| error_message = str(api_error) | |
| if "Connection" in error_message: | |
| return {"error": "OpenAI ์๋ฒ์ ์ฐ๊ฒฐํ ์ ์์ต๋๋ค. ์ธํฐ๋ท ์ฐ๊ฒฐ์ ํ์ธํ์ธ์."} | |
| elif "Unauthorized" in error_message or "Authentication" in error_message: | |
| return {"error": "API ํค๊ฐ ์ ํจํ์ง ์์ต๋๋ค."} | |
| elif "Rate limit" in error_message: | |
| return {"error": "API ํธ์ถ ํ๋๋ฅผ ์ด๊ณผํ์ต๋๋ค. ์ ์ ํ ๋ค์ ์๋ํ์ธ์."} | |
| else: | |
| return {"error": f"AI ์๋ต ์์ฑ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: {error_message}"} | |
| except Exception as e: | |
| logger.error(f"์ง์์๋ต ์ฒ๋ฆฌ ์ค๋ฅ: {e}") | |
| return {"error": str(e)} | |
| # PDF ์์ฝ ์์ฑ | |
| # PDF ์์ฝ ์์ฑ ํจ์ ๊ฐ์ | |
| async def summarize_pdf(pdf_id: str) -> Dict[str, Any]: | |
| try: | |
| # API ํค๊ฐ ์๊ฑฐ๋ ์ ํจํ์ง ์์ ๊ฒฝ์ฐ | |
| if not HAS_VALID_API_KEY or not openai_client: | |
| return { | |
| "error": "OpenAI API ํค๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค. 'LLM_API' ํ๊ฒฝ ๋ณ์๋ฅผ ํ์ธํ์ธ์.", | |
| "summary": "API ํค๊ฐ ์์ด ์์ฝ์ ์์ฑํ ์ ์์ต๋๋ค. ์์คํ ๊ด๋ฆฌ์์๊ฒ ๋ฌธ์ํ์ธ์." | |
| } | |
| # ์๋ฒ ๋ฉ ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ | |
| embedding_data = await get_pdf_embedding(pdf_id) | |
| if "error" in embedding_data: | |
| return {"error": embedding_data["error"], "summary": "PDF์์ ํ ์คํธ๋ฅผ ์ถ์ถํ ์ ์์ต๋๋ค."} | |
| # ์ฒญํฌ ํ ์คํธ ๋ชจ์ผ๊ธฐ (์ ํ๋ ๊ธธ์ด) | |
| all_text = "\n\n".join([f"Page {chunk['page']}: {chunk['text']}" for chunk in embedding_data["chunks"]]) | |
| # ์ปจํ ์คํธ ํฌ๊ธฐ๋ฅผ ๊ณ ๋ คํ์ฌ ํ ์คํธ๊ฐ ๋๋ฌด ๊ธธ๋ฉด ์๋ถ๋ถ๋ง ์ฌ์ฉ | |
| max_context_length = 60000 # ํ ํฐ ์๊ฐ ์๋ ๋ฌธ์ ์ ๊ธฐ์ค (๋๋ต์ ์ธ ์ ํ) | |
| if len(all_text) > max_context_length: | |
| all_text = all_text[:max_context_length] + "...(์ดํ ์๋ต)" | |
| # OpenAI API ํธ์ถ | |
| try: | |
| # ํ์์์ ๋ฐ ์ฌ์๋ ์ค์ ๊ฐ์ | |
| for attempt in range(3): # ์ต๋ 3๋ฒ ์ฌ์๋ | |
| try: | |
| response = openai_client.chat.completions.create( | |
| model="gpt-4.1-mini", | |
| messages=[ | |
| {"role": "system", "content": "๋ค์ PDF ๋ด์ฉ์ ๊ฐ๊ฒฐํ๊ฒ ์์ฝํด์ฃผ์ธ์. ํต์ฌ ์ฃผ์ ์ ์ฃผ์ ํฌ์ธํธ๋ฅผ ํฌํจํ ์์ฝ์ 500์ ์ด๋ด๋ก ์์ฑํด์ฃผ์ธ์."}, | |
| {"role": "user", "content": f"PDF ๋ด์ฉ:\n{all_text}"} | |
| ], | |
| temperature=0.7, | |
| max_tokens=1024, | |
| timeout=30.0 # 30์ด ํ์์์ | |
| ) | |
| summary = response.choices[0].message.content | |
| return { | |
| "summary": summary, | |
| "pdf_id": pdf_id | |
| } | |
| except Exception as api_error: | |
| logger.error(f"OpenAI API ํธ์ถ ์ค๋ฅ (์๋ {attempt+1}/3): {api_error}") | |
| if attempt == 2: # ๋ง์ง๋ง ์๋์์๋ ์คํจ | |
| raise api_error | |
| await asyncio.sleep(1 * (attempt + 1)) # ์ฌ์๋ ๊ฐ ์ง์ฐ ์๊ฐ ์ฆ๊ฐ | |
| # ์ฌ๊ธฐ๊น์ง ๋๋ฌํ์ง ์์์ผ ํจ | |
| raise Exception("API ํธ์ถ ์ฌ์๋ ๋ชจ๋ ์คํจ") | |
| except Exception as api_error: | |
| logger.error(f"OpenAI API ํธ์ถ ์ต์ข ์ค๋ฅ: {api_error}") | |
| # ์ค๋ฅ ์ ํ์ ๋ฐ๋ฅธ ๋ ๋ช ํํ ๋ฉ์์ง ์ ๊ณต | |
| error_message = str(api_error) | |
| if "Connection" in error_message: | |
| return {"error": "OpenAI ์๋ฒ์ ์ฐ๊ฒฐํ ์ ์์ต๋๋ค. ์ธํฐ๋ท ์ฐ๊ฒฐ์ ํ์ธํ์ธ์.", "pdf_id": pdf_id} | |
| elif "Unauthorized" in error_message or "Authentication" in error_message: | |
| return {"error": "API ํค๊ฐ ์ ํจํ์ง ์์ต๋๋ค.", "pdf_id": pdf_id} | |
| elif "Rate limit" in error_message: | |
| return {"error": "API ํธ์ถ ํ๋๋ฅผ ์ด๊ณผํ์ต๋๋ค. ์ ์ ํ ๋ค์ ์๋ํ์ธ์.", "pdf_id": pdf_id} | |
| else: | |
| return {"error": f"AI ์์ฝ ์์ฑ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: {error_message}", "pdf_id": pdf_id} | |
| except Exception as e: | |
| logger.error(f"PDF ์์ฝ ์์ฑ ์ค๋ฅ: {e}") | |
| return { | |
| "error": str(e), | |
| "summary": "PDF ์์ฝ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. PDF ํ์ด์ง ์๊ฐ ๋๋ฌด ๋ง๊ฑฐ๋ ํ์์ด ์ง์๋์ง ์์ ์ ์์ต๋๋ค." | |
| } | |
| # ์ต์ ํ๋ PDF ํ์ด์ง ์บ์ฑ ํจ์ | |
| async def cache_pdf(pdf_path: str): | |
| try: | |
| import fitz # PyMuPDF | |
| pdf_file = pathlib.Path(pdf_path) | |
| pdf_name = pdf_file.stem | |
| # ๋ฝ ์์ฑ - ๋์ผํ PDF์ ๋ํด ๋์ ์บ์ฑ ๋ฐฉ์ง | |
| if pdf_name not in cache_locks: | |
| cache_locks[pdf_name] = threading.Lock() | |
| # ์ด๋ฏธ ์บ์ฑ ์ค์ด๊ฑฐ๋ ์บ์ฑ ์๋ฃ๋ PDF๋ ๊ฑด๋๋ฐ๊ธฐ | |
| if pdf_name in pdf_cache and pdf_cache[pdf_name].get("status") in ["processing", "completed"]: | |
| logger.info(f"PDF {pdf_name} ์ด๋ฏธ ์บ์ฑ ์๋ฃ ๋๋ ์งํ ์ค") | |
| return | |
| with cache_locks[pdf_name]: | |
| # ์ด์ค ์ฒดํฌ - ๋ฝ ํ๋ ํ ๋ค์ ํ์ธ | |
| if pdf_name in pdf_cache and pdf_cache[pdf_name].get("status") in ["processing", "completed"]: | |
| return | |
| # ์บ์ ์ํ ์ ๋ฐ์ดํธ | |
| pdf_cache[pdf_name] = {"status": "processing", "progress": 0, "pages": []} | |
| # ์บ์ ํ์ผ์ด ์ด๋ฏธ ์กด์ฌํ๋์ง ํ์ธ | |
| cache_path = get_cache_path(pdf_name) | |
| if cache_path.exists(): | |
| try: | |
| with open(cache_path, "r") as cache_file: | |
| cached_data = json.load(cache_file) | |
| if cached_data.get("status") == "completed" and cached_data.get("pages"): | |
| pdf_cache[pdf_name] = cached_data | |
| pdf_cache[pdf_name]["status"] = "completed" | |
| logger.info(f"์บ์ ํ์ผ์์ {pdf_name} ๋ก๋ ์๋ฃ") | |
| return | |
| except Exception as e: | |
| logger.error(f"์บ์ ํ์ผ ๋ก๋ ์คํจ: {e}") | |
| # PDF ํ์ผ ์ด๊ธฐ | |
| doc = fitz.open(pdf_path) | |
| total_pages = doc.page_count | |
| # ๋ฏธ๋ฆฌ ์ธ๋ค์ผ๋ง ๋จผ์ ์์ฑ (๋น ๋ฅธ UI ๋ก๋ฉ์ฉ) | |
| if total_pages > 0: | |
| # ์ฒซ ํ์ด์ง ์ธ๋ค์ผ ์์ฑ | |
| page = doc[0] | |
| pix_thumb = page.get_pixmap(matrix=fitz.Matrix(0.2, 0.2)) # ๋ ์์ ์ธ๋ค์ผ | |
| thumb_data = pix_thumb.tobytes("png") | |
| b64_thumb = base64.b64encode(thumb_data).decode('utf-8') | |
| thumb_src = f"data:image/png;base64,{b64_thumb}" | |
| # ์ธ๋ค์ผ ํ์ด์ง๋ง ๋จผ์ ์บ์ | |
| pdf_cache[pdf_name]["pages"] = [{"thumb": thumb_src, "src": ""}] | |
| pdf_cache[pdf_name]["progress"] = 1 | |
| pdf_cache[pdf_name]["total_pages"] = total_pages | |
| # ์ด๋ฏธ์ง ํด์๋ ๋ฐ ์์ถ ํ์ง ์ค์ (์ฑ๋ฅ ์ต์ ํ) | |
| scale_factor = 1.0 # ๊ธฐ๋ณธ ํด์๋ (๋ฎ์ถ์๋ก ๋ก๋ฉ ๋น ๋ฆ) | |
| jpeg_quality = 80 # JPEG ํ์ง (๋ฎ์ถ์๋ก ์ฉ๋ ์์์ง) | |
| # ํ์ด์ง ์ฒ๋ฆฌ ์์ ์ ํจ์ (๋ณ๋ ฌ ์ฒ๋ฆฌ์ฉ) | |
| def process_page(page_num): | |
| try: | |
| page = doc[page_num] | |
| # ์ด๋ฏธ์ง๋ก ๋ณํ ์ ๋งคํธ๋ฆญ์ค ์ค์ผ์ผ๋ง ์ ์ฉ (์ฑ๋ฅ ์ต์ ํ) | |
| pix = page.get_pixmap(matrix=fitz.Matrix(scale_factor, scale_factor)) | |
| # JPEG ํ์์ผ๋ก ์ธ์ฝ๋ฉ (PNG๋ณด๋ค ํฌ๊ธฐ ์์) | |
| img_data = pix.tobytes("jpeg", jpeg_quality) | |
| b64_img = base64.b64encode(img_data).decode('utf-8') | |
| img_src = f"data:image/jpeg;base64,{b64_img}" | |
| # ์ธ๋ค์ผ (์ฒซ ํ์ด์ง๊ฐ ์๋๋ฉด ๋น ๋ฌธ์์ด) | |
| thumb_src = "" if page_num > 0 else pdf_cache[pdf_name]["pages"][0]["thumb"] | |
| return { | |
| "page_num": page_num, | |
| "src": img_src, | |
| "thumb": thumb_src | |
| } | |
| except Exception as e: | |
| logger.error(f"ํ์ด์ง {page_num} ์ฒ๋ฆฌ ์ค๋ฅ: {e}") | |
| return { | |
| "page_num": page_num, | |
| "src": "", | |
| "thumb": "", | |
| "error": str(e) | |
| } | |
| # ๋ณ๋ ฌ ์ฒ๋ฆฌ๋ก ๋ชจ๋ ํ์ด์ง ์ฒ๋ฆฌ | |
| pages = [None] * total_pages | |
| processed_count = 0 | |
| # ํ์ด์ง ๋ฐฐ์น ์ฒ๋ฆฌ (๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ) | |
| batch_size = 5 # ํ ๋ฒ์ ์ฒ๋ฆฌํ ํ์ด์ง ์ | |
| for batch_start in range(0, total_pages, batch_size): | |
| batch_end = min(batch_start + batch_size, total_pages) | |
| current_batch = list(range(batch_start, batch_end)) | |
| # ๋ณ๋ ฌ ์ฒ๋ฆฌ๋ก ๋ฐฐ์น ํ์ด์ง ๋ ๋๋ง | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=min(5, batch_size)) as executor: | |
| batch_results = list(executor.map(process_page, current_batch)) | |
| # ๊ฒฐ๊ณผ ์ ์ฅ | |
| for result in batch_results: | |
| page_num = result["page_num"] | |
| pages[page_num] = { | |
| "src": result["src"], | |
| "thumb": result["thumb"] | |
| } | |
| processed_count += 1 | |
| progress = round(processed_count / total_pages * 100) | |
| pdf_cache[pdf_name]["progress"] = progress | |
| # ์ค๊ฐ ์ ์ฅ | |
| pdf_cache[pdf_name]["pages"] = pages | |
| try: | |
| with open(cache_path, "w") as cache_file: | |
| json.dump({ | |
| "status": "processing", | |
| "progress": pdf_cache[pdf_name]["progress"], | |
| "pages": pdf_cache[pdf_name]["pages"], | |
| "total_pages": total_pages | |
| }, cache_file) | |
| except Exception as e: | |
| logger.error(f"์ค๊ฐ ์บ์ ์ ์ฅ ์คํจ: {e}") | |
| # ์บ์ฑ ์๋ฃ | |
| pdf_cache[pdf_name] = { | |
| "status": "completed", | |
| "progress": 100, | |
| "pages": pages, | |
| "total_pages": total_pages | |
| } | |
| # ์ต์ข ์บ์ ํ์ผ ์ ์ฅ | |
| try: | |
| with open(cache_path, "w") as cache_file: | |
| json.dump(pdf_cache[pdf_name], cache_file) | |
| logger.info(f"PDF {pdf_name} ์บ์ฑ ์๋ฃ, {total_pages}ํ์ด์ง") | |
| except Exception as e: | |
| logger.error(f"์ต์ข ์บ์ ์ ์ฅ ์คํจ: {e}") | |
| except Exception as e: | |
| import traceback | |
| logger.error(f"PDF ์บ์ฑ ์ค๋ฅ: {str(e)}\n{traceback.format_exc()}") | |
| if pdf_name in pdf_cache: | |
| pdf_cache[pdf_name]["status"] = "error" | |
| pdf_cache[pdf_name]["error"] = str(e) | |
| # PDF ID๋ก PDF ๊ฒฝ๋ก ์ฐพ๊ธฐ (๊ฐ์ ๋ ๊ฒ์ ๋ก์ง) | |
| def get_pdf_path_by_id(pdf_id: str) -> str: | |
| logger.info(f"PDF ID๋ก ํ์ผ ์กฐํ: {pdf_id}") | |
| # 1. ๋ฉํ๋ฐ์ดํฐ์์ ์ง์ ID๋ก ๊ฒ์ | |
| if pdf_id in pdf_metadata: | |
| path = pdf_metadata[pdf_id] | |
| # ํ์ผ ์กด์ฌ ํ์ธ | |
| if os.path.exists(path): | |
| return path | |
| # ํ์ผ์ด ์ด๋ํ์ ์ ์์ผ๋ฏ๋ก ํ์ผ๋ช ์ผ๋ก ๊ฒ์ | |
| filename = os.path.basename(path) | |
| # ์๊ตฌ ์ ์ฅ์์์ ๊ฒ์ | |
| perm_path = PERMANENT_PDF_DIR / filename | |
| if perm_path.exists(): | |
| # ๋ฉํ๋ฐ์ดํฐ ์ ๋ฐ์ดํธ | |
| pdf_metadata[pdf_id] = str(perm_path) | |
| save_pdf_metadata() | |
| return str(perm_path) | |
| # ๋ฉ์ธ ๋๋ ํ ๋ฆฌ์์ ๊ฒ์ | |
| main_path = PDF_DIR / filename | |
| if main_path.exists(): | |
| # ๋ฉํ๋ฐ์ดํฐ ์ ๋ฐ์ดํธ | |
| pdf_metadata[pdf_id] = str(main_path) | |
| save_pdf_metadata() | |
| return str(main_path) | |
| # 2. ํ์ผ๋ช ๋ถ๋ถ๋ง ์ถ์ถํ์ฌ ๋ชจ๋ PDF ํ์ผ ๊ฒ์ | |
| try: | |
| # ID ํ์: filename_timestamp_random | |
| # ํ์ผ๋ช ๋ถ๋ถ๋ง ์ถ์ถ | |
| name_part = pdf_id.split('_')[0] if '_' in pdf_id else pdf_id | |
| # ๋ชจ๋ PDF ํ์ผ ๊ฒ์ | |
| for file_path in get_pdf_files() + get_permanent_pdf_files(): | |
| # ํ์ผ๋ช ์ด ID์ ์์ ๋ถ๋ถ๊ณผ ์ผ์นํ๋ฉด | |
| file_basename = os.path.basename(file_path) | |
| if file_basename.startswith(name_part) or file_path.stem.startswith(name_part): | |
| # ID ๋งคํ ์ ๋ฐ์ดํธ | |
| pdf_metadata[pdf_id] = str(file_path) | |
| save_pdf_metadata() | |
| return str(file_path) | |
| except Exception as e: | |
| logger.error(f"ํ์ผ๋ช ๊ฒ์ ์ค ์ค๋ฅ: {e}") | |
| # 3. ๋ชจ๋ PDF ํ์ผ์ ๋ํด ๋ฉํ๋ฐ์ดํฐ ํ์ธ | |
| for pid, path in pdf_metadata.items(): | |
| if os.path.exists(path): | |
| file_basename = os.path.basename(path) | |
| # ์ ์ฌํ ํ์ผ๋ช ์ ๊ฐ์ง ๊ฒฝ์ฐ | |
| if pdf_id in pid or pid in pdf_id: | |
| pdf_metadata[pdf_id] = path | |
| save_pdf_metadata() | |
| return path | |
| return None | |
| # ์์ ์ ๋ชจ๋ PDF ํ์ผ ์บ์ฑ | |
| async def init_cache_all_pdfs(): | |
| logger.info("PDF ์บ์ฑ ์์ ์์") | |
| # PDF ๋ฉํ๋ฐ์ดํฐ ๋ก๋ | |
| load_pdf_metadata() | |
| # ๋ฉ์ธ ๋ฐ ์๊ตฌ ๋๋ ํ ๋ฆฌ์์ PDF ํ์ผ ๋ชจ๋ ๊ฐ์ ธ์ค๊ธฐ | |
| pdf_files = get_pdf_files() + get_permanent_pdf_files() | |
| # ์ค๋ณต ์ ๊ฑฐ | |
| unique_pdf_paths = set(str(p) for p in pdf_files) | |
| pdf_files = [pathlib.Path(p) for p in unique_pdf_paths] | |
| # ํ์ผ ๊ธฐ๋ฐ ๋ฉํ๋ฐ์ดํฐ ์ ๋ฐ์ดํธ | |
| for pdf_file in pdf_files: | |
| # ID๊ฐ ์๋ ํ์ผ์ ๋ํด ID ์์ฑ | |
| found = False | |
| for pid, path in pdf_metadata.items(): | |
| if os.path.basename(path) == pdf_file.name: | |
| found = True | |
| # ๊ฒฝ๋ก ์ ๋ฐ์ดํธ ํ์ํ ๊ฒฝ์ฐ | |
| if not os.path.exists(path): | |
| pdf_metadata[pid] = str(pdf_file) | |
| break | |
| if not found: | |
| pdf_id = generate_pdf_id(pdf_file.name) | |
| pdf_metadata[pdf_id] = str(pdf_file) | |
| # ๋ฉํ๋ฐ์ดํฐ ์ ์ฅ | |
| save_pdf_metadata() | |
| # ์ด๋ฏธ ์บ์๋ PDF ํ์ผ ๋ก๋ (๋น ๋ฅธ ์์์ ์ํด ๋จผ์ ์ํ) | |
| for cache_file in CACHE_DIR.glob("*_cache.json"): | |
| try: | |
| pdf_name = cache_file.stem.replace("_cache", "") | |
| with open(cache_file, "r") as f: | |
| cached_data = json.load(f) | |
| if cached_data.get("status") == "completed" and cached_data.get("pages"): | |
| pdf_cache[pdf_name] = cached_data | |
| pdf_cache[pdf_name]["status"] = "completed" | |
| logger.info(f"๊ธฐ์กด ์บ์ ๋ก๋: {pdf_name}") | |
| except Exception as e: | |
| logger.error(f"์บ์ ํ์ผ ๋ก๋ ์ค๋ฅ: {str(e)}") | |
| # ์บ์ฑ๋์ง ์์ PDF ํ์ผ ๋ณ๋ ฌ ์ฒ๋ฆฌ | |
| await asyncio.gather(*[asyncio.create_task(cache_pdf(str(pdf_file))) | |
| for pdf_file in pdf_files | |
| if pdf_file.stem not in pdf_cache | |
| or pdf_cache[pdf_file.stem].get("status") != "completed"]) | |
| # ๋ฐฑ๊ทธ๋ผ์ด๋ ์์ ์์ ํจ์ | |
| async def startup_event(): | |
| # PDF ๋ฉํ๋ฐ์ดํฐ ๋ก๋ | |
| load_pdf_metadata() | |
| # ๋๋ฝ๋ PDF ํ์ผ์ ๋ํ ๋ฉํ๋ฐ์ดํฐ ์์ฑ | |
| for pdf_file in get_pdf_files() + get_permanent_pdf_files(): | |
| found = False | |
| for pid, path in pdf_metadata.items(): | |
| if os.path.basename(path) == pdf_file.name: | |
| found = True | |
| # ๊ฒฝ๋ก ์ ๋ฐ์ดํธ | |
| if not os.path.exists(path): | |
| pdf_metadata[pid] = str(pdf_file) | |
| break | |
| if not found: | |
| # ์ ID ์์ฑ ๋ฐ ๋ฉํ๋ฐ์ดํฐ์ ์ถ๊ฐ | |
| pdf_id = generate_pdf_id(pdf_file.name) | |
| pdf_metadata[pdf_id] = str(pdf_file) | |
| # ๋ณ๊ฒฝ์ฌํญ ์ ์ฅ | |
| save_pdf_metadata() | |
| # ๋ฐฑ๊ทธ๋ผ์ด๋ ํ์คํฌ๋ก ์บ์ฑ ์คํ | |
| asyncio.create_task(init_cache_all_pdfs()) | |
| # API ์๋ํฌ์ธํธ: PDF ํ๋ก์ ํธ ๋ชฉ๋ก | |
| async def get_pdf_projects_api(): | |
| return generate_pdf_projects() | |
| # API ์๋ํฌ์ธํธ: ์๊ตฌ ์ ์ฅ๋ PDF ํ๋ก์ ํธ ๋ชฉ๋ก | |
| async def get_permanent_pdf_projects_api(): | |
| pdf_files = get_permanent_pdf_files() | |
| projects_data = [] | |
| for pdf_file in pdf_files: | |
| # PDF ID ์ฐพ๊ธฐ | |
| pdf_id = None | |
| for pid, path in pdf_metadata.items(): | |
| if os.path.basename(path) == pdf_file.name: | |
| pdf_id = pid | |
| break | |
| # ID๊ฐ ์์ผ๋ฉด ์์ฑ | |
| if not pdf_id: | |
| pdf_id = generate_pdf_id(pdf_file.name) | |
| pdf_metadata[pdf_id] = str(pdf_file) | |
| save_pdf_metadata() | |
| projects_data.append({ | |
| "path": str(pdf_file), | |
| "name": pdf_file.stem, | |
| "id": pdf_id, | |
| "cached": pdf_file.stem in pdf_cache and pdf_cache[pdf_file.stem].get("status") == "completed" | |
| }) | |
| return projects_data | |
| # API ์๋ํฌ์ธํธ: PDF ID๋ก ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ | |
| async def get_pdf_info_by_id(pdf_id: str): | |
| pdf_path = get_pdf_path_by_id(pdf_id) | |
| if pdf_path: | |
| pdf_file = pathlib.Path(pdf_path) | |
| return { | |
| "path": pdf_path, | |
| "name": pdf_file.stem, | |
| "id": pdf_id, | |
| "exists": True, | |
| "cached": pdf_file.stem in pdf_cache and pdf_cache[pdf_file.stem].get("status") == "completed" | |
| } | |
| return {"exists": False, "error": "PDF๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค"} | |
| # API ์๋ํฌ์ธํธ: PDF ์ธ๋ค์ผ ์ ๊ณต (์ต์ ํ) | |
| async def get_pdf_thumbnail(path: str): | |
| try: | |
| pdf_file = pathlib.Path(path) | |
| pdf_name = pdf_file.stem | |
| # ์บ์์์ ์ธ๋ค์ผ ๊ฐ์ ธ์ค๊ธฐ | |
| if pdf_name in pdf_cache and pdf_cache[pdf_name].get("pages"): | |
| if pdf_cache[pdf_name]["pages"][0].get("thumb"): | |
| return {"thumbnail": pdf_cache[pdf_name]["pages"][0]["thumb"]} | |
| # ์บ์์ ์์ผ๋ฉด ์์ฑ (๋ ์๊ณ ๋น ๋ฅธ ์ธ๋ค์ผ) | |
| import fitz | |
| doc = fitz.open(path) | |
| if doc.page_count > 0: | |
| page = doc[0] | |
| pix = page.get_pixmap(matrix=fitz.Matrix(0.2, 0.2)) # ๋ ์์ ์ธ๋ค์ผ | |
| img_data = pix.tobytes("jpeg", 70) # JPEG ์์ถ ์ฌ์ฉ | |
| b64_img = base64.b64encode(img_data).decode('utf-8') | |
| # ๋ฐฑ๊ทธ๋ผ์ด๋์์ ์บ์ฑ ์์ | |
| asyncio.create_task(cache_pdf(path)) | |
| return {"thumbnail": f"data:image/jpeg;base64,{b64_img}"} | |
| return {"thumbnail": None} | |
| except Exception as e: | |
| logger.error(f"์ธ๋ค์ผ ์์ฑ ์ค๋ฅ: {str(e)}") | |
| return {"error": str(e), "thumbnail": None} | |
| # API ์๋ํฌ์ธํธ: ์บ์ ์ํ ํ์ธ | |
| async def get_cache_status(path: str = None): | |
| if path: | |
| pdf_file = pathlib.Path(path) | |
| pdf_name = pdf_file.stem | |
| if pdf_name in pdf_cache: | |
| return pdf_cache[pdf_name] | |
| return {"status": "not_cached"} | |
| else: | |
| return {name: {"status": info["status"], "progress": info.get("progress", 0)} | |
| for name, info in pdf_cache.items()} | |
| # API ์๋ํฌ์ธํธ: PDF์ ๋ํ ์ง์์๋ต | |
| async def api_query_pdf(pdf_id: str, query: Dict[str, str]): | |
| try: | |
| user_query = query.get("query", "") | |
| if not user_query: | |
| return JSONResponse(content={"error": "์ง๋ฌธ์ด ์ ๊ณต๋์ง ์์์ต๋๋ค"}, status_code=400) | |
| # PDF ๊ฒฝ๋ก ํ์ธ | |
| pdf_path = get_pdf_path_by_id(pdf_id) | |
| if not pdf_path: | |
| return JSONResponse(content={"error": f"PDF ID {pdf_id}์ ํด๋นํ๋ ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค"}, status_code=404) | |
| # ์ง์์๋ต ์ฒ๋ฆฌ | |
| result = await query_pdf(pdf_id, user_query) | |
| if "error" in result: | |
| return JSONResponse(content={"error": result["error"]}, status_code=500) | |
| return result | |
| except Exception as e: | |
| logger.error(f"์ง์์๋ต API ์ค๋ฅ: {e}") | |
| return JSONResponse(content={"error": str(e)}, status_code=500) | |
| # API ์๋ํฌ์ธํธ: PDF ์์ฝ | |
| async def api_summarize_pdf(pdf_id: str): | |
| try: | |
| # PDF ๊ฒฝ๋ก ํ์ธ | |
| pdf_path = get_pdf_path_by_id(pdf_id) | |
| if not pdf_path: | |
| return JSONResponse(content={"error": f"PDF ID {pdf_id}์ ํด๋นํ๋ ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค"}, status_code=404) | |
| # ์์ฝ ์ฒ๋ฆฌ | |
| result = await summarize_pdf(pdf_id) | |
| if "error" in result: | |
| return JSONResponse(content={"error": result["error"]}, status_code=500) | |
| return result | |
| except Exception as e: | |
| logger.error(f"PDF ์์ฝ API ์ค๋ฅ: {e}") | |
| return JSONResponse(content={"error": str(e)}, status_code=500) | |
| # API ์๋ํฌ์ธํธ: ์บ์๋ PDF ์ฝํ ์ธ ์ ๊ณต (์ ์ง์ ๋ก๋ฉ ์ง์) | |
| async def get_cached_pdf(path: str, background_tasks: BackgroundTasks): | |
| try: | |
| pdf_file = pathlib.Path(path) | |
| pdf_name = pdf_file.stem | |
| # ์บ์ ํ์ธ | |
| if pdf_name in pdf_cache: | |
| status = pdf_cache[pdf_name].get("status", "") | |
| # ์๋ฃ๋ ๊ฒฝ์ฐ ์ ์ฒด ๋ฐ์ดํฐ ๋ฐํ | |
| if status == "completed": | |
| return pdf_cache[pdf_name] | |
| # ์ฒ๋ฆฌ ์ค์ธ ๊ฒฝ์ฐ ํ์ฌ๊น์ง์ ํ์ด์ง ๋ฐ์ดํฐ ํฌํจ (์ ์ง์ ๋ก๋ฉ) | |
| elif status == "processing": | |
| progress = pdf_cache[pdf_name].get("progress", 0) | |
| pages = pdf_cache[pdf_name].get("pages", []) | |
| total_pages = pdf_cache[pdf_name].get("total_pages", 0) | |
| # ์ผ๋ถ๋ง ์ฒ๋ฆฌ๋ ๊ฒฝ์ฐ์๋ ์ฌ์ฉ ๊ฐ๋ฅํ ํ์ด์ง ์ ๊ณต | |
| return { | |
| "status": "processing", | |
| "progress": progress, | |
| "pages": pages, | |
| "total_pages": total_pages, | |
| "available_pages": len([p for p in pages if p and p.get("src")]) | |
| } | |
| # ์บ์๊ฐ ์๋ ๊ฒฝ์ฐ ๋ฐฑ๊ทธ๋ผ์ด๋์์ ์บ์ฑ ์์ | |
| background_tasks.add_task(cache_pdf, path) | |
| return {"status": "started", "progress": 0} | |
| except Exception as e: | |
| logger.error(f"์บ์๋ PDF ์ ๊ณต ์ค๋ฅ: {str(e)}") | |
| return {"error": str(e), "status": "error"} | |
| # API ์๋ํฌ์ธํธ: PDF ์๋ณธ ์ฝํ ์ธ ์ ๊ณต(์บ์๊ฐ ์๋ ๊ฒฝ์ฐ) | |
| async def get_pdf_content(path: str, background_tasks: BackgroundTasks): | |
| try: | |
| # ์บ์ฑ ์ํ ํ์ธ | |
| pdf_file = pathlib.Path(path) | |
| if not pdf_file.exists(): | |
| return JSONResponse(content={"error": f"ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค: {path}"}, status_code=404) | |
| pdf_name = pdf_file.stem | |
| # ์บ์๋ ๊ฒฝ์ฐ ๋ฆฌ๋ค์ด๋ ํธ | |
| if pdf_name in pdf_cache and (pdf_cache[pdf_name].get("status") == "completed" | |
| or (pdf_cache[pdf_name].get("status") == "processing" | |
| and pdf_cache[pdf_name].get("progress", 0) > 10)): | |
| return JSONResponse(content={"redirect": f"/api/cached-pdf?path={path}"}) | |
| # ํ์ผ ์ฝ๊ธฐ | |
| with open(path, "rb") as pdf_file: | |
| content = pdf_file.read() | |
| # ํ์ผ๋ช ์ฒ๋ฆฌ | |
| import urllib.parse | |
| filename = pdf_file.name | |
| encoded_filename = urllib.parse.quote(filename) | |
| # ๋ฐฑ๊ทธ๋ผ์ด๋์์ ์บ์ฑ ์์ | |
| background_tasks.add_task(cache_pdf, path) | |
| # ์๋ต ํค๋ ์ค์ | |
| headers = { | |
| "Content-Type": "application/pdf", | |
| "Content-Disposition": f"inline; filename=\"{encoded_filename}\"; filename*=UTF-8''{encoded_filename}" | |
| } | |
| return Response(content=content, media_type="application/pdf", headers=headers) | |
| except Exception as e: | |
| import traceback | |
| error_details = traceback.format_exc() | |
| logger.error(f"PDF ์ฝํ ์ธ ๋ก๋ ์ค๋ฅ: {str(e)}\n{error_details}") | |
| return JSONResponse(content={"error": str(e)}, status_code=500) | |
| # PDF ์ ๋ก๋ ์๋ํฌ์ธํธ - ์๊ตฌ ์ ์ฅ์์ ์ ์ฅ ๋ฐ ๋ฉ์ธ ํ๋ฉด์ ์๋ ํ์ | |
| async def upload_pdf(file: UploadFile = File(...)): | |
| try: | |
| # ํ์ผ ์ด๋ฆ ํ์ธ | |
| if not file.filename.lower().endswith('.pdf'): | |
| return JSONResponse( | |
| content={"success": False, "message": "PDF ํ์ผ๋ง ์ ๋ก๋ ๊ฐ๋ฅํฉ๋๋ค"}, | |
| status_code=400 | |
| ) | |
| # ์๊ตฌ ์ ์ฅ์์ ํ์ผ ์ ์ฅ | |
| file_path = PERMANENT_PDF_DIR / file.filename | |
| # ํ์ผ ์ฝ๊ธฐ ๋ฐ ์ ์ฅ | |
| content = await file.read() | |
| with open(file_path, "wb") as buffer: | |
| buffer.write(content) | |
| # ๋ฉ์ธ ๋๋ ํ ๋ฆฌ์๋ ์๋์ผ๋ก ๋ณต์ฌ (์๋ ํ์) | |
| with open(PDF_DIR / file.filename, "wb") as buffer: | |
| buffer.write(content) | |
| # PDF ID ์์ฑ ๋ฐ ๋ฉํ๋ฐ์ดํฐ ์ ์ฅ | |
| pdf_id = generate_pdf_id(file.filename) | |
| pdf_metadata[pdf_id] = str(file_path) | |
| save_pdf_metadata() | |
| # ๋ฐฑ๊ทธ๋ผ์ด๋์์ ์บ์ฑ ์์ | |
| asyncio.create_task(cache_pdf(str(file_path))) | |
| return JSONResponse( | |
| content={ | |
| "success": True, | |
| "path": str(file_path), | |
| "name": file_path.stem, | |
| "id": pdf_id, | |
| "viewUrl": f"/view/{pdf_id}" | |
| }, | |
| status_code=200 | |
| ) | |
| except Exception as e: | |
| import traceback | |
| error_details = traceback.format_exc() | |
| logger.error(f"PDF ์ ๋ก๋ ์ค๋ฅ: {str(e)}\n{error_details}") | |
| return JSONResponse( | |
| content={"success": False, "message": str(e)}, | |
| status_code=500 | |
| ) | |
| # ํ ์คํธ ํ์ผ์ PDF๋ก ๋ณํํ๋ ํจ์ | |
| async def convert_text_to_pdf(text_content: str, title: str) -> str: | |
| try: | |
| # ์ ๋ชฉ์์ ์ ํจํ ํ์ผ๋ช ์์ฑ | |
| import re | |
| safe_title = re.sub(r'[^\w\-_\. ]', '_', title) | |
| if not safe_title: | |
| safe_title = "aibook" | |
| # ํ์์คํฌํ ์ถ๊ฐ๋ก ๊ณ ์ ํ ํ์ผ๋ช ์์ฑ | |
| timestamp = int(time.time()) | |
| filename = f"{safe_title}_{timestamp}.pdf" | |
| # ์๊ตฌ ์ ์ฅ์์ ํ์ผ ๊ฒฝ๋ก | |
| file_path = PERMANENT_PDF_DIR / filename | |
| # ์์ PDF ํ์ผ ์์ฑ | |
| pdf_buffer = io.BytesIO() | |
| doc = SimpleDocTemplate(pdf_buffer, pagesize=letter) | |
| styles = getSampleStyleSheet() | |
| # ๋ด์ฉ์ ๋ฌธ๋จ์ผ๋ก ๋ถํ | |
| content = [] | |
| # ์ ๋ชฉ ์ถ๊ฐ | |
| title_style = styles['Title'] | |
| content.append(Paragraph(title, title_style)) | |
| content.append(Spacer(1, 12)) | |
| # ๋ณธ๋ฌธ ํ ์คํธ ์คํ์ผ | |
| normal_style = styles['Normal'] | |
| # ํ ์คํธ๋ฅผ ๋จ๋ฝ์ผ๋ก ๋ถ๋ฆฌํ์ฌ ์ถ๊ฐ | |
| paragraphs = text_content.split('\n\n') | |
| for para in paragraphs: | |
| if para.strip(): | |
| p = Paragraph(para.replace('\n', '<br/>'), normal_style) | |
| content.append(p) | |
| content.append(Spacer(1, 10)) | |
| # PDF ์์ฑ | |
| doc.build(content) | |
| # ํ์ผ๋ก ์ ์ฅ | |
| with open(file_path, 'wb') as f: | |
| f.write(pdf_buffer.getvalue()) | |
| # ๋ฉ์ธ ๋๋ ํ ๋ฆฌ์๋ ๋ณต์ฌ | |
| with open(PDF_DIR / filename, 'wb') as f: | |
| f.write(pdf_buffer.getvalue()) | |
| # PDF ID ์์ฑ ๋ฐ ๋ฉํ๋ฐ์ดํฐ ์ ์ฅ | |
| pdf_id = generate_pdf_id(filename) | |
| pdf_metadata[pdf_id] = str(file_path) | |
| save_pdf_metadata() | |
| # ๋ฐฑ๊ทธ๋ผ์ด๋์์ ์บ์ฑ ์์ | |
| asyncio.create_task(cache_pdf(str(file_path))) | |
| return { | |
| "path": str(file_path), | |
| "filename": filename, | |
| "id": pdf_id | |
| } | |
| except Exception as e: | |
| logger.error(f"ํ ์คํธ๋ฅผ PDF๋ก ๋ณํ ์ค ์ค๋ฅ: {e}") | |
| raise e | |
| # AI๋ฅผ ์ฌ์ฉํ์ฌ ํ ์คํธ๋ฅผ ๋ ๊ตฌ์กฐํ๋ ํ์์ผ๋ก ๋ณํ | |
| async def enhance_text_with_ai(text_content: str, title: str) -> str: | |
| try: | |
| # API ํค๊ฐ ์๊ฑฐ๋ ์ ํจํ์ง ์์ ๊ฒฝ์ฐ ์๋ณธ ํ ์คํธ ๋ฐํ | |
| if not HAS_VALID_API_KEY or not openai_client: | |
| return text_content | |
| # ํ ์คํธ๊ฐ ์งง์ ๊ฒฝ์ฐ ์๋ณธ ๋ฐํ | |
| if len(text_content) < 100: | |
| return text_content | |
| # ์ปจํ ์คํธ ํฌ๊ธฐ๋ฅผ ๊ณ ๋ คํ์ฌ ํ ์คํธ๊ฐ ๋๋ฌด ๊ธธ๋ฉด ์๋ถ๋ถ๋ง ์ฌ์ฉ | |
| max_context_length = 60000 | |
| if len(text_content) > max_context_length: | |
| text_to_process = text_content[:max_context_length] + "...(์ดํ ์๋ต)" | |
| else: | |
| text_to_process = text_content | |
| # OpenAI API ํธ์ถํ์ฌ ํ ์คํธ ๊ตฌ์กฐํ | |
| try: | |
| system_prompt = """ | |
| ๋น์ ์ ํ ์คํธ๋ฅผ ์ ๊ตฌ์กฐํ๋ ์ ์์ฑ ํ์์ผ๋ก ๋ณํํ๋ ์ ๋ฌธ๊ฐ์ ๋๋ค. | |
| ์ ๊ณต๋ ์๋ณธ ํ ์คํธ๋ฅผ ๋ถ์ํ๊ณ , ๋ค์๊ณผ ๊ฐ์ด ๊ฐ์ ํด์ฃผ์ธ์: | |
| 1. ๋ ผ๋ฆฌ์ ์ธ ์น์ ์ผ๋ก ๋๋๊ณ ์ ์ ํ ์ ๋ชฉ๊ณผ ๋ถ์ ๋ชฉ ์ถ๊ฐ | |
| 2. ๋จ๋ฝ์ ์์ฐ์ค๋ฝ๊ฒ ๊ตฌ์ฑํ๊ณ ๊ฐ๋ ์ฑ ๊ฐ์ | |
| 3. ์ค์ํ ๋ด์ฉ์ ๊ฐ์กฐํ๊ฑฐ๋ ์์ฝํ์ฌ ํ์ | |
| 4. ์๋ณธ ๋ด์ฉ์ ์๋ฏธ์ ๋งฅ๋ฝ์ ์ ์งํ๋ฉด์ ๊น๋ํ๊ฒ ์ ๋ฆฌ | |
| 5. ๋ง์ถค๋ฒ๊ณผ ๋ฌธ๋ฒ ์ค๋ฅ ์์ | |
| ์๋ณธ ๋ด์ฉ์ ๋ชจ๋ ์ ์งํ๋, ์ ์ ๋ฆฌ๋ ์ ์์ฑ ์ฒ๋ผ ๋ณด์ด๋๋ก ๊ตฌ์กฐํํด์ฃผ์ธ์. | |
| ์์ ๋ณธ์ ์ง์ ๋ฐํํ๊ณ , ์๋ณธ ๋ด์ฉ์ ๋ชจ๋ ํฌํจํด์ผ ํฉ๋๋ค. | |
| """ | |
| response = openai_client.chat.completions.create( | |
| model="gpt-4.1-mini", | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": f"์ ๋ชฉ: {title}\n\n์๋ณธ ํ ์คํธ:\n{text_to_process}"} | |
| ], | |
| temperature=0.7, | |
| max_tokens=4000, | |
| timeout=60.0 | |
| ) | |
| enhanced_text = response.choices[0].message.content | |
| return enhanced_text | |
| except Exception as api_error: | |
| logger.error(f"AI ํ ์คํธ ํฅ์ ์ค๋ฅ: {api_error}") | |
| # ์ค๋ฅ ๋ฐ์ ์ ์๋ณธ ํ ์คํธ ๋ฐํ | |
| return text_content | |
| except Exception as e: | |
| logger.error(f"AI ํ ์คํธ ํฅ์ ์ค๋ฅ: {e}") | |
| return text_content | |
| # ํ ์คํธ ํ์ผ์ PDF๋ก ๋ณํํ๋ ์๋ํฌ์ธํธ | |
| async def text_to_pdf(file: UploadFile = File(...)): | |
| try: | |
| # ์ง์ํ๋ ํ์ผ ํ์ ํ์ธ | |
| filename = file.filename.lower() | |
| if not (filename.endswith('.txt') or filename.endswith('.docx') or filename.endswith('.doc')): | |
| return JSONResponse( | |
| content={"success": False, "message": "์ง์ํ๋ ํ์ผ ํ์์ .txt, .docx, .doc์ ๋๋ค."}, | |
| status_code=400 | |
| ) | |
| # ํ์ผ ๋ด์ฉ ์ฝ๊ธฐ | |
| content = await file.read() | |
| # ํ์ผ ํ์ ์ ๋ฐ๋ผ ํ ์คํธ ์ถ์ถ | |
| if filename.endswith('.txt'): | |
| text_content = content.decode('utf-8', errors='replace') | |
| elif filename.endswith('.docx') or filename.endswith('.doc'): | |
| # ์์ ํ์ผ๋ก ์ ์ฅ | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(filename)[1]) as temp_file: | |
| temp_file.write(content) | |
| temp_path = temp_file.name | |
| try: | |
| # docx2txt๋ก ํ ์คํธ ์ถ์ถ | |
| text_content = docx2txt.process(temp_path) | |
| finally: | |
| # ์์ ํ์ผ ์ญ์ | |
| os.unlink(temp_path) | |
| # ํ์ผ๋ช ์์ ์ ๋ชฉ ์ถ์ถ (ํ์ฅ์ ์ ์ธ) | |
| title = os.path.splitext(filename)[0] | |
| # AI๋ก ํ ์คํธ ๋ด์ฉ ํฅ์ | |
| enhanced_text = await enhance_text_with_ai(text_content, title) | |
| # ํ ์คํธ๋ฅผ PDF๋ก ๋ณํ | |
| pdf_info = await convert_text_to_pdf(enhanced_text, title) | |
| return JSONResponse( | |
| content={ | |
| "success": True, | |
| "path": pdf_info["path"], | |
| "name": os.path.splitext(pdf_info["filename"])[0], | |
| "id": pdf_info["id"], | |
| "viewUrl": f"/view/{pdf_info['id']}" | |
| }, | |
| status_code=200 | |
| ) | |
| except Exception as e: | |
| import traceback | |
| error_details = traceback.format_exc() | |
| logger.error(f"ํ ์คํธ๋ฅผ PDF๋ก ๋ณํ ์ค ์ค๋ฅ: {str(e)}\n{error_details}") | |
| return JSONResponse( | |
| content={"success": False, "message": str(e)}, | |
| status_code=500 | |
| ) | |
| # ๊ด๋ฆฌ์ ์ธ์ฆ ์๋ํฌ์ธํธ | |
| async def admin_login(password: str = Form(...)): | |
| if password == ADMIN_PASSWORD: | |
| return {"success": True} | |
| return {"success": False, "message": "์ธ์ฆ ์คํจ"} | |
| # ๊ด๋ฆฌ์์ฉ PDF ์ญ์ ์๋ํฌ์ธํธ | |
| async def delete_pdf(path: str): | |
| try: | |
| pdf_file = pathlib.Path(path) | |
| if not pdf_file.exists(): | |
| return {"success": False, "message": "ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค"} | |
| # PDF ํ์ผ๋ช ๊ฐ์ ธ์ค๊ธฐ | |
| filename = pdf_file.name | |
| # PDF ํ์ผ ์ญ์ (์๊ตฌ ์ ์ฅ์์์) | |
| pdf_file.unlink() | |
| # ๋ฉ์ธ ๋๋ ํ ๋ฆฌ์์๋ ๋์ผํ ํ์ผ์ด ์์ผ๋ฉด ์ญ์ (๋ฒ๊ทธ ์์ ) | |
| main_file_path = PDF_DIR / filename | |
| if main_file_path.exists(): | |
| main_file_path.unlink() | |
| # ๊ด๋ จ ์บ์ ํ์ผ ์ญ์ | |
| pdf_name = pdf_file.stem | |
| cache_path = get_cache_path(pdf_name) | |
| if cache_path.exists(): | |
| cache_path.unlink() | |
| # ์บ์ ๋ฉ๋ชจ๋ฆฌ์์๋ ์ ๊ฑฐ | |
| if pdf_name in pdf_cache: | |
| del pdf_cache[pdf_name] | |
| # ๋ฉํ๋ฐ์ดํฐ์์ ํด๋น ํ์ผ ID ์ ๊ฑฐ | |
| to_remove = [] | |
| for pid, fpath in pdf_metadata.items(): | |
| if os.path.basename(fpath) == filename: | |
| to_remove.append(pid) | |
| for pid in to_remove: | |
| del pdf_metadata[pid] | |
| save_pdf_metadata() | |
| return {"success": True} | |
| except Exception as e: | |
| logger.error(f"PDF ์ญ์ ์ค๋ฅ: {str(e)}") | |
| return {"success": False, "message": str(e)} | |
| # PDF๋ฅผ ๋ฉ์ธ ๋๋ ํ ๋ฆฌ์ ํ์ ์ค์ | |
| async def feature_pdf(path: str): | |
| try: | |
| pdf_file = pathlib.Path(path) | |
| if not pdf_file.exists(): | |
| return {"success": False, "message": "ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค"} | |
| # ๋ฉ์ธ ๋๋ ํ ๋ฆฌ์ ๋ณต์ฌ | |
| target_path = PDF_DIR / pdf_file.name | |
| shutil.copy2(pdf_file, target_path) | |
| return {"success": True} | |
| except Exception as e: | |
| logger.error(f"PDF ํ์ ์ค์ ์ค๋ฅ: {str(e)}") | |
| return {"success": False, "message": str(e)} | |
| # PDF๋ฅผ ๋ฉ์ธ ๋๋ ํ ๋ฆฌ์์ ์ ๊ฑฐ (์๊ตฌ ์ ์ฅ์์์๋ ์ ์ง) | |
| async def unfeature_pdf(path: str): | |
| try: | |
| pdf_name = pathlib.Path(path).name | |
| target_path = PDF_DIR / pdf_name | |
| if target_path.exists(): | |
| target_path.unlink() | |
| return {"success": True} | |
| except Exception as e: | |
| logger.error(f"PDF ํ์ ํด์ ์ค๋ฅ: {str(e)}") | |
| return {"success": False, "message": str(e)} | |
| # ์ง์ PDF ๋ทฐ์ด URL ์ ๊ทผ์ฉ ๋ผ์ฐํธ | |
| async def view_pdf_by_id(pdf_id: str): | |
| # PDF ID ์ ํจํ์ง ํ์ธ | |
| pdf_path = get_pdf_path_by_id(pdf_id) | |
| if not pdf_path: | |
| # ์ผ๋จ ๋ชจ๋ PDF ๋ฉํ๋ฐ์ดํฐ๋ฅผ ๋ค์ ๋ก๋ํ๊ณ ์ฌ์๋ | |
| load_pdf_metadata() | |
| pdf_path = get_pdf_path_by_id(pdf_id) | |
| if not pdf_path: | |
| # ๋ชจ๋ PDF ํ์ผ์ ์ง์ ์ค์บํ์ฌ ์ ์ฌํ ์ด๋ฆ ์ฐพ๊ธฐ | |
| for file_path in get_pdf_files() + get_permanent_pdf_files(): | |
| name_part = pdf_id.split('_')[0] if '_' in pdf_id else pdf_id | |
| if file_path.stem.startswith(name_part): | |
| pdf_metadata[pdf_id] = str(file_path) | |
| save_pdf_metadata() | |
| pdf_path = str(file_path) | |
| break | |
| if not pdf_path: | |
| return HTMLResponse( | |
| content=f"<html><body><h1>PDF๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค</h1><p>ID: {pdf_id}</p><a href='/'>ํ์ผ๋ก ๋์๊ฐ๊ธฐ</a></body></html>", | |
| status_code=404 | |
| ) | |
| # ๋ฉ์ธ ํ์ด์ง๋ก ๋ฆฌ๋ค์ด๋ ํธํ๋, PDF ID ํ๋ผ๋ฏธํฐ ์ถ๊ฐ | |
| return get_html_content(pdf_id=pdf_id) | |
| # HTML ํ์ผ ์ฝ๊ธฐ ํจ์ | |
| def get_html_content(pdf_id: str = None): | |
| html_path = BASE / "flipbook_template.html" | |
| content = "" | |
| if html_path.exists(): | |
| with open(html_path, "r", encoding="utf-8") as f: | |
| content = f.read() | |
| else: | |
| content = HTML # ๊ธฐ๋ณธ HTML ์ฌ์ฉ | |
| # PDF ID๊ฐ ์ ๊ณต๋ ๊ฒฝ์ฐ, ์๋ ๋ก๋ ์คํฌ๋ฆฝํธ ์ถ๊ฐ | |
| if pdf_id: | |
| auto_load_script = f""" | |
| <script> | |
| // ํ์ด์ง ๋ก๋ ์ ์๋์ผ๋ก ํด๋น PDF ์ด๊ธฐ | |
| document.addEventListener('DOMContentLoaded', async function() {{ | |
| try {{ | |
| // PDF ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ | |
| const response = await fetch('/api/pdf-info-by-id/{pdf_id}'); | |
| const pdfInfo = await response.json(); | |
| if (pdfInfo.exists && pdfInfo.path) {{ | |
| // ์ฝ๊ฐ์ ์ง์ฐ ํ PDF ๋ทฐ์ด ์ด๊ธฐ (UI๊ฐ ์ค๋น๋ ํ) | |
| setTimeout(() => {{ | |
| openPdfById('{pdf_id}', pdfInfo.path, pdfInfo.cached); | |
| }}, 500); | |
| }} else {{ | |
| showError("์์ฒญํ PDF๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."); | |
| }} | |
| }} catch (e) {{ | |
| console.error("์๋ PDF ๋ก๋ ์ค๋ฅ:", e); | |
| }} | |
| }}); | |
| </script> | |
| """ | |
| # body ์ข ๋ฃ ํ๊ทธ ์ ์ ์คํฌ๋ฆฝํธ ์ฝ์ | |
| content = content.replace("</body>", auto_load_script + "</body>") | |
| return HTMLResponse(content=content) | |
| async def root(request: Request, pdf_id: Optional[str] = Query(None)): | |
| # PDF ID๊ฐ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ก ์ ๊ณต๋ ๊ฒฝ์ฐ /view/{pdf_id}๋ก ๋ฆฌ๋ค์ด๋ ํธ | |
| if pdf_id: | |
| return RedirectResponse(url=f"/view/{pdf_id}") | |
| return get_html_content() | |
| # HTML ๋ฌธ์์ด (AI ๋ฒํผ ๋ฐ ์ฑ๋ด UI ์ถ๊ฐ) | |
| HTML = """ | |
| <!doctype html> | |
| <html lang="ko"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <title>FlipBook Space</title> | |
| <link rel="stylesheet" href="/static/flipbook.css"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.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> | |
| /* ์ ์ฒด ์ฌ์ดํธ ํ์คํ ํค ํ ๋ง */ | |
| :root { | |
| --primary-color: #a5d8ff; /* ํ์คํ ๋ธ๋ฃจ */ | |
| --secondary-color: #ffd6e0; /* ํ์คํ ํํฌ */ | |
| --tertiary-color: #c3fae8; /* ํ์คํ ๋ฏผํธ */ | |
| --accent-color: #d0bfff; /* ํ์คํ ํผํ */ | |
| --ai-color: #86e8ab; /* AI ๋ฒํผ ์์ */ | |
| --ai-hover: #65d68a; /* AI ํธ๋ฒ ์์ */ | |
| --bg-color: #f8f9fa; /* ๋ฐ์ ๋ฐฐ๊ฒฝ */ | |
| --text-color: #495057; /* ๋ถ๋๋ฌ์ด ์ด๋์ด ์ */ | |
| --card-bg: #ffffff; /* ์นด๋ ๋ฐฐ๊ฒฝ์ */ | |
| --shadow-sm: 0 2px 8px rgba(0,0,0,0.05); | |
| --shadow-md: 0 4px 12px rgba(0,0,0,0.08); | |
| --shadow-lg: 0 8px 24px rgba(0,0,0,0.12); | |
| --radius-sm: 8px; | |
| --radius-md: 12px; | |
| --radius-lg: 16px; | |
| --transition: all 0.3s ease; | |
| } | |
| body { | |
| margin: 0; | |
| background: var(--bg-color); | |
| font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
| color: var(--text-color); | |
| /* ์๋ก์ด ํผํ ๊ณํต ๊ณ ๊ธ์ค๋ฌ์ด ๊ทธ๋ผ๋์์ด์ ๋ฐฐ๊ฒฝ */ | |
| background-image: linear-gradient(135deg, #2a0845 0%, #6441a5 50%, #c9a8ff 100%); | |
| background-attachment: fixed; | |
| } | |
| /* ๋ทฐ์ด ๋ชจ๋์ผ ๋ ๋ฐฐ๊ฒฝ ๋ณ๊ฒฝ */ | |
| .viewer-mode { | |
| background-image: linear-gradient(135deg, #30154e 0%, #6b47ad 50%, #d5b8ff 100%) !important; | |
| } | |
| /* ํค๋ ์ ๋ชฉ ์ ๊ฑฐ ๋ฐ Home ๋ฒํผ ๋ ์ด์ด ์ฒ๋ฆฌ */ | |
| .floating-home, .floating-ai { | |
| position: fixed; | |
| top: 20px; | |
| left: 20px; | |
| width: 60px; | |
| height: 60px; | |
| border-radius: 50%; | |
| background: rgba(255, 255, 255, 0.9); | |
| backdrop-filter: blur(10px); | |
| box-shadow: var(--shadow-md); | |
| z-index: 9999; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| cursor: pointer; | |
| transition: var(--transition); | |
| overflow: hidden; | |
| } | |
| .floating-ai { | |
| top: 90px; /* Home ๋ฒํผ ์๋์ ์์น */ | |
| background: rgba(134, 232, 171, 0.9); /* AI ๋ฒํผ ์์ */ | |
| } | |
| .floating-home:hover, .floating-ai:hover { | |
| transform: scale(1.05); | |
| box-shadow: var(--shadow-lg); | |
| } | |
| .floating-home .icon, .floating-ai .icon { | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| width: 100%; | |
| height: 100%; | |
| font-size: 22px; | |
| color: var(--primary-color); | |
| transition: var(--transition); | |
| } | |
| .floating-ai .icon { | |
| color: white; | |
| } | |
| .floating-home:hover .icon { | |
| color: #8bc5f8; | |
| } | |
| .floating-ai:hover .icon { | |
| color: #ffffff; | |
| } | |
| .floating-home .title, .floating-ai .title { | |
| position: absolute; | |
| left: 70px; | |
| background: rgba(255, 255, 255, 0.95); | |
| padding: 8px 20px; | |
| border-radius: 20px; | |
| box-shadow: var(--shadow-sm); | |
| font-weight: 600; | |
| font-size: 14px; | |
| white-space: nowrap; | |
| pointer-events: none; | |
| opacity: 0; | |
| transform: translateX(-10px); | |
| transition: all 0.3s ease; | |
| } | |
| .floating-home:hover .title, .floating-ai:hover .title { | |
| opacity: 1; | |
| transform: translateX(0); | |
| } | |
| /* ๊ด๋ฆฌ์ ๋ฒํผ ์คํ์ผ */ | |
| #adminButton { | |
| position: fixed; | |
| top: 20px; | |
| right: 20px; | |
| background: rgba(255, 255, 255, 0.9); | |
| backdrop-filter: blur(10px); | |
| box-shadow: var(--shadow-md); | |
| border-radius: 30px; | |
| padding: 8px 20px; | |
| display: flex; | |
| align-items: center; | |
| font-weight: 600; | |
| font-size: 14px; | |
| cursor: pointer; | |
| transition: var(--transition); | |
| z-index: 9999; | |
| } | |
| #adminButton i { | |
| margin-right: 8px; | |
| color: var(--accent-color); | |
| } | |
| #adminButton:hover { | |
| transform: translateY(-3px); | |
| box-shadow: var(--shadow-lg); | |
| } | |
| /* ๊ด๋ฆฌ์ ๋ก๊ทธ์ธ ๋ชจ๋ฌ */ | |
| .modal { | |
| display: none; | |
| position: fixed; | |
| top: 0; | |
| left: 0; | |
| width: 100%; | |
| height: 100%; | |
| background: rgba(0, 0, 0, 0.5); | |
| backdrop-filter: blur(5px); | |
| z-index: 10000; | |
| align-items: center; | |
| justify-content: center; | |
| } | |
| .modal-content { | |
| background: white; | |
| border-radius: var(--radius-md); | |
| padding: 30px; | |
| width: 90%; | |
| max-width: 400px; | |
| box-shadow: var(--shadow-lg); | |
| text-align: center; | |
| } | |
| .modal-content h2 { | |
| margin-top: 0; | |
| color: var(--accent-color); | |
| margin-bottom: 20px; | |
| } | |
| .modal-content input { | |
| width: 100%; | |
| padding: 12px; | |
| margin-bottom: 20px; | |
| border: 1px solid #ddd; | |
| border-radius: var(--radius-sm); | |
| font-size: 16px; | |
| box-sizing: border-box; | |
| } | |
| .modal-content button { | |
| padding: 10px 20px; | |
| border: none; | |
| border-radius: var(--radius-sm); | |
| background: var(--accent-color); | |
| color: white; | |
| font-weight: 600; | |
| cursor: pointer; | |
| margin: 0 5px; | |
| transition: var(--transition); | |
| } | |
| .modal-content button:hover { | |
| opacity: 0.9; | |
| transform: translateY(-2px); | |
| } | |
| .modal-content #adminLoginClose { | |
| background: #f1f3f5; | |
| color: var(--text-color); | |
| } | |
| #home, #viewerPage, #adminPage { | |
| padding-top: 100px; | |
| max-width: 1200px; | |
| margin: 0 auto; | |
| padding-bottom: 60px; | |
| padding-left: 30px; | |
| padding-right: 30px; | |
| position: relative; | |
| } | |
| /* ์ ๋ก๋ ๋ฒํผ ์คํ์ผ */ | |
| .upload-container { | |
| display: flex; | |
| margin-bottom: 30px; | |
| justify-content: center; | |
| } | |
| button.upload { | |
| all: unset; | |
| cursor: pointer; | |
| padding: 12px 20px; | |
| border-radius: var(--radius-md); | |
| background: white; | |
| margin: 0 10px; | |
| font-weight: 500; | |
| display: flex; | |
| align-items: center; | |
| box-shadow: var(--shadow-sm); | |
| transition: var(--transition); | |
| position: relative; | |
| overflow: hidden; | |
| } | |
| button.upload::before { | |
| content: ''; | |
| position: absolute; | |
| top: 0; | |
| left: 0; | |
| width: 100%; | |
| height: 100%; | |
| background: linear-gradient(120deg, var(--primary-color) 0%, var(--secondary-color) 100%); | |
| opacity: 0.08; | |
| z-index: -1; | |
| } | |
| button.upload:hover { | |
| transform: translateY(-3px); | |
| box-shadow: var(--shadow-md); | |
| } | |
| button.upload:hover::before { | |
| opacity: 0.15; | |
| } | |
| button.upload i { | |
| margin-right: 8px; | |
| font-size: 20px; | |
| } | |
| /* ๊ทธ๋ฆฌ๋ ๋ฐ ์นด๋ ์คํ์ผ */ | |
| .grid { | |
| display: grid; | |
| grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); | |
| gap: 24px; | |
| margin-top: 36px; | |
| } | |
| .card { | |
| background: var(--card-bg); | |
| border-radius: var(--radius-md); | |
| cursor: pointer; | |
| box-shadow: var(--shadow-sm); | |
| width: 100%; | |
| height: 280px; | |
| position: relative; | |
| display: flex; | |
| flex-direction: column; | |
| align-items: center; | |
| justify-content: center; | |
| transition: var(--transition); | |
| overflow: hidden; | |
| } | |
| .card::before { | |
| content: ''; | |
| position: absolute; | |
| top: 0; | |
| left: 0; | |
| width: 100%; | |
| height: 100%; | |
| background: linear-gradient(135deg, var(--secondary-color) 0%, var(--primary-color) 100%); | |
| opacity: 0.06; | |
| z-index: 1; | |
| } | |
| .card::after { | |
| content: ''; | |
| position: absolute; | |
| top: 0; | |
| left: 0; | |
| width: 100%; | |
| height: 30%; | |
| background: linear-gradient(to bottom, rgba(255,255,255,0.8) 0%, rgba(255,255,255,0) 100%); | |
| z-index: 2; | |
| } | |
| .card img { | |
| width: 65%; | |
| height: auto; | |
| object-fit: contain; | |
| position: absolute; | |
| top: 50%; | |
| left: 50%; | |
| transform: translate(-50%, -65%); | |
| border: 1px solid rgba(0,0,0,0.05); | |
| box-shadow: 0 4px 15px rgba(0,0,0,0.08); | |
| z-index: 3; | |
| transition: var(--transition); | |
| } | |
| .card:hover { | |
| transform: translateY(-5px); | |
| box-shadow: var(--shadow-md); | |
| } | |
| .card:hover img { | |
| transform: translate(-50%, -65%) scale(1.03); | |
| box-shadow: 0 8px 20px rgba(0,0,0,0.12); | |
| } | |
| .card p { | |
| position: absolute; | |
| bottom: 20px; | |
| left: 50%; | |
| transform: translateX(-50%); | |
| background: rgba(255, 255, 255, 0.9); | |
| padding: 8px 16px; | |
| border-radius: 30px; | |
| box-shadow: 0 2px 10px rgba(0,0,0,0.05); | |
| width: 80%; | |
| text-align: center; | |
| white-space: nowrap; | |
| overflow: hidden; | |
| text-overflow: ellipsis; | |
| font-size: 14px; | |
| font-weight: 500; | |
| color: var(--text-color); | |
| z-index: 4; | |
| transition: var(--transition); | |
| } | |
| .card:hover p { | |
| background: rgba(255, 255, 255, 0.95); | |
| box-shadow: 0 4px 12px rgba(0,0,0,0.08); | |
| } | |
| /* ์บ์ ์ํ ๋ฑ์ง */ | |
| .cached-status { | |
| position: absolute; | |
| top: 10px; | |
| right: 10px; | |
| background: var(--accent-color); | |
| color: white; | |
| font-size: 11px; | |
| padding: 3px 8px; | |
| border-radius: 12px; | |
| z-index: 5; | |
| box-shadow: var(--shadow-sm); | |
| } | |
| /* ๊ด๋ฆฌ์ ์นด๋ ์ถ๊ฐ ์คํ์ผ */ | |
| .admin-card { | |
| height: 300px; | |
| } | |
| .admin-card .card-inner { | |
| width: 100%; | |
| height: 100%; | |
| position: relative; | |
| display: flex; | |
| flex-direction: column; | |
| align-items: center; | |
| } | |
| .delete-btn, .feature-btn, .unfeature-btn { | |
| position: absolute; | |
| bottom: 60px; | |
| left: 50%; | |
| transform: translateX(-50%); | |
| background: #ff7675; | |
| color: white; | |
| border: none; | |
| border-radius: 20px; | |
| padding: 5px 15px; | |
| font-size: 12px; | |
| cursor: pointer; | |
| z-index: 10; | |
| transition: var(--transition); | |
| } | |
| .feature-btn { | |
| bottom: 95px; | |
| background: #74b9ff; | |
| } | |
| .unfeature-btn { | |
| bottom: 95px; | |
| background: #a29bfe; | |
| } | |
| .delete-btn:hover, .feature-btn:hover, .unfeature-btn:hover { | |
| opacity: 0.9; | |
| transform: translateX(-50%) scale(1.05); | |
| } | |
| /* ๋ทฐ์ด ์คํ์ผ */ | |
| #viewer { | |
| width: 90%; | |
| height: 90vh; | |
| max-width: 90%; | |
| margin: 0; | |
| background: var(--card-bg); | |
| border: none; | |
| border-radius: var(--radius-lg); | |
| position: fixed; | |
| top: 50%; | |
| left: 50%; | |
| transform: translate(-50%, -50%); | |
| z-index: 1000; | |
| box-shadow: var(--shadow-lg); | |
| 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(255,255,255,0.9) !important; | |
| backdrop-filter: blur(10px) !important; | |
| border-radius: 0 0 var(--radius-lg) var(--radius-lg) !important; | |
| padding: 12px 0 !important; | |
| box-shadow: 0 -4px 20px rgba(0,0,0,0.1) !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; | |
| filter: drop-shadow(0 2px 3px rgba(0,0,0,0.1)) !important; | |
| } | |
| .flipbook-container .fb3d-menu-bar > ul > li { | |
| margin: 0 12px !important; | |
| } | |
| /* ๋ฉ๋ด ํดํ ์คํ์ผ */ | |
| .flipbook-container .fb3d-menu-bar > ul > li > span { | |
| background-color: rgba(0,0,0,0.7) !important; | |
| color: white !important; | |
| border-radius: var(--radius-sm) !important; | |
| padding: 8px 12px !important; | |
| font-size: 13px !important; | |
| bottom: 55px !important; | |
| font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important; | |
| letter-spacing: 0.3px !important; | |
| } | |
| /* ๋ทฐ์ด ๋ชจ๋์ผ ๋ ๋ฐฐ๊ฒฝ ์ค๋ฒ๋ ์ด */ | |
| .viewer-mode { | |
| background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%) !important; | |
| } | |
| /* ๋ทฐ์ด ํ์ด์ง ๋ฐฐ๊ฒฝ */ | |
| #viewerPage { | |
| background: transparent; | |
| } | |
| /* ๋ก๋ฉ ์ ๋๋ฉ์ด์ */ | |
| @keyframes spin { | |
| 0% { transform: rotate(0deg); } | |
| 100% { transform: rotate(360deg); } | |
| } | |
| .loading-spinner { | |
| border: 4px solid rgba(255,255,255,0.3); | |
| border-top: 4px solid var(--primary-color); | |
| border-radius: 50%; | |
| width: 50px; | |
| height: 50px; | |
| margin: 0 auto; | |
| animation: spin 1.5s ease-in-out infinite; | |
| } | |
| .loading-container { | |
| position: absolute; | |
| top: 50%; | |
| left: 50%; | |
| transform: translate(-50%, -50%); | |
| text-align: center; | |
| background: rgba(255, 255, 255, 0.85); | |
| backdrop-filter: blur(10px); | |
| padding: 30px; | |
| border-radius: var(--radius-md); | |
| box-shadow: var(--shadow-md); | |
| z-index: 9999; | |
| } | |
| .loading-text { | |
| margin-top: 20px; | |
| font-size: 16px; | |
| color: var(--text-color); | |
| font-weight: 500; | |
| } | |
| /* ํ์ด์ง ์ ํ ์ ๋๋ฉ์ด์ */ | |
| @keyframes fadeIn { | |
| from { opacity: 0; } | |
| to { opacity: 1; } | |
| } | |
| .fade-in { | |
| animation: fadeIn 0.5s ease-out; | |
| } | |
| /* ์ถ๊ฐ ์คํ์ผ */ | |
| .section-title { | |
| font-size: 1.3rem; | |
| font-weight: 600; | |
| margin: 30px 0 15px; | |
| color: var(--text-color); | |
| } | |
| .no-projects { | |
| text-align: center; | |
| margin: 40px 0; | |
| color: var(--text-color); | |
| font-size: 16px; | |
| } | |
| /* ํ๋ก๊ทธ๋ ์ค ๋ฐ */ | |
| .progress-bar-container { | |
| width: 100%; | |
| height: 6px; | |
| background-color: rgba(0,0,0,0.1); | |
| border-radius: 3px; | |
| margin-top: 15px; | |
| overflow: hidden; | |
| } | |
| .progress-bar { | |
| height: 100%; | |
| background: linear-gradient(to right, var(--primary-color), var(--accent-color)); | |
| border-radius: 3px; | |
| transition: width 0.3s ease; | |
| } | |
| /* ํค๋ ๋ก๊ณ ๋ฐ ํ์ดํ */ | |
| .library-header { | |
| position: fixed; | |
| top: 12px; | |
| left: 0; | |
| right: 0; | |
| text-align: center; | |
| z-index: 100; | |
| pointer-events: none; | |
| } | |
| .library-header .title { | |
| display: inline-block; | |
| padding: 8px 24px; /* ํจ๋ฉ ์ถ์ */ | |
| background: rgba(255, 255, 255, 0.85); | |
| backdrop-filter: blur(10px); | |
| border-radius: 25px; /* ํ ๋๋ฆฌ ๋ชจ์๋ฆฌ ์ถ์ */ | |
| box-shadow: var(--shadow-md); | |
| font-size: 1.25rem; /* ๊ธ์ ํฌ๊ธฐ ์ถ์ (1.5rem์์ 1.25rem์ผ๋ก) */ | |
| font-weight: 600; | |
| background-image: linear-gradient(120deg, #8e74eb 0%, #9d66ff 100%); /* ์ ๋ชฉ ์์๋ ๋ฐํํ๋ฉด๊ณผ ์ด์ธ๋ฆฌ๊ฒ ๋ณ๊ฒฝ */ | |
| -webkit-background-clip: text; | |
| background-clip: text; | |
| color: transparent; | |
| pointer-events: all; | |
| } | |
| /* ์ ์ง์ ๋ก๋ฉ ํ์ */ | |
| .loading-pages { | |
| position: absolute; | |
| bottom: 20px; | |
| left: 50%; | |
| transform: translateX(-50%); | |
| background: rgba(255, 255, 255, 0.9); | |
| padding: 10px 20px; | |
| border-radius: 20px; | |
| box-shadow: var(--shadow-md); | |
| font-size: 14px; | |
| color: var(--text-color); | |
| z-index: 9998; | |
| text-align: center; | |
| } | |
| /* ๊ด๋ฆฌ์ ํ์ด์ง ์คํ์ผ */ | |
| #adminPage { | |
| color: white; | |
| max-width: 1400px; | |
| } | |
| #adminPage h1 { | |
| font-size: 2rem; | |
| margin-bottom: 30px; | |
| text-align: center; | |
| background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%); | |
| -webkit-background-clip: text; | |
| background-clip: text; | |
| color: transparent; | |
| } | |
| #adminBackButton { | |
| position: absolute; | |
| top: 20px; | |
| left: 20px; | |
| background: rgba(255, 255, 255, 0.9); | |
| backdrop-filter: blur(10px); | |
| box-shadow: var(--shadow-md); | |
| border: none; | |
| border-radius: 30px; | |
| padding: 8px 20px; | |
| display: flex; | |
| align-items: center; | |
| font-weight: 600; | |
| font-size: 14px; | |
| cursor: pointer; | |
| transition: var(--transition); | |
| } | |
| #adminBackButton:hover { | |
| transform: translateY(-3px); | |
| box-shadow: var(--shadow-lg); | |
| } | |
| /* ๊ด๋ฆฌ์ ๊ทธ๋ฆฌ๋ */ | |
| #adminGrid { | |
| grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); | |
| } | |
| /* AI ์ฑ๋ด UI ์คํ์ผ */ | |
| #aiChatContainer { | |
| display: none; | |
| position: fixed; | |
| top: 0; | |
| right: 0; | |
| width: 400px; | |
| height: 100%; | |
| background: rgba(255, 255, 255, 0.95); | |
| backdrop-filter: blur(10px); | |
| box-shadow: -5px 0 20px rgba(0, 0, 0, 0.1); | |
| z-index: 9999; | |
| transition: all 0.3s ease; | |
| transform: translateX(100%); | |
| padding: 20px; | |
| box-sizing: border-box; | |
| display: flex; | |
| flex-direction: column; | |
| } | |
| #aiChatContainer.active { | |
| transform: translateX(0); | |
| } | |
| #aiChatHeader { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| margin-bottom: 15px; | |
| padding-bottom: 15px; | |
| border-bottom: 1px solid rgba(0, 0, 0, 0.1); | |
| } | |
| #aiChatHeader h3 { | |
| margin: 0; | |
| color: #333; | |
| font-size: 18px; | |
| display: flex; | |
| align-items: center; | |
| } | |
| #aiChatHeader h3 i { | |
| margin-right: 10px; | |
| color: var(--ai-color); | |
| } | |
| #aiChatClose { | |
| background: none; | |
| border: none; | |
| cursor: pointer; | |
| font-size: 18px; | |
| color: #666; | |
| transition: var(--transition); | |
| } | |
| #aiChatClose:hover { | |
| color: #333; | |
| transform: scale(1.1); | |
| } | |
| #aiChatMessages { | |
| flex: 1; | |
| overflow-y: auto; | |
| padding: 10px 0; | |
| margin-bottom: 15px; | |
| } | |
| .chat-message { | |
| margin-bottom: 15px; | |
| display: flex; | |
| align-items: flex-start; | |
| } | |
| .chat-message.user { | |
| flex-direction: row-reverse; | |
| } | |
| .chat-avatar { | |
| width: 35px; | |
| height: 35px; | |
| border-radius: 50%; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| margin-right: 10px; | |
| flex-shrink: 0; | |
| } | |
| .chat-message.user .chat-avatar { | |
| margin-right: 0; | |
| margin-left: 10px; | |
| background: var(--primary-color); | |
| color: white; | |
| } | |
| .chat-message.ai .chat-avatar { | |
| background: var(--ai-color); | |
| color: white; | |
| } | |
| .chat-content { | |
| background: #f1f1f1; | |
| padding: 12px 15px; | |
| border-radius: 18px; | |
| max-width: 75%; | |
| word-break: break-word; | |
| position: relative; | |
| font-size: 14px; | |
| line-height: 1.4; | |
| } | |
| .chat-message.user .chat-content { | |
| background: var(--primary-color); | |
| color: white; | |
| border-bottom-right-radius: 4px; | |
| } | |
| .chat-message.ai .chat-content { | |
| background: #f1f1f1; | |
| color: #333; | |
| border-bottom-left-radius: 4px; | |
| } | |
| #aiChatForm { | |
| display: flex; | |
| border-top: 1px solid rgba(0, 0, 0, 0.1); | |
| padding-top: 15px; | |
| } | |
| #aiChatInput { | |
| flex: 1; | |
| padding: 12px 15px; | |
| border: 1px solid #ddd; | |
| border-radius: 25px; | |
| font-size: 14px; | |
| outline: none; | |
| transition: var(--transition); | |
| } | |
| #aiChatInput:focus { | |
| border-color: var(--ai-color); | |
| box-shadow: 0 0 0 2px rgba(134, 232, 171, 0.2); | |
| } | |
| #aiChatSubmit { | |
| background: var(--ai-color); | |
| border: none; | |
| color: white; | |
| width: 45px; | |
| height: 45px; | |
| border-radius: 50%; | |
| margin-left: 10px; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| cursor: pointer; | |
| transition: var(--transition); | |
| } | |
| #aiChatSubmit:hover { | |
| background: var(--ai-hover); | |
| transform: scale(1.05); | |
| } | |
| #aiChatSubmit:disabled { | |
| background: #ccc; | |
| cursor: not-allowed; | |
| } | |
| .typing-indicator { | |
| display: flex; | |
| align-items: center; | |
| margin-top: 5px; | |
| font-size: 12px; | |
| color: #666; | |
| } | |
| .typing-indicator span { | |
| height: 8px; | |
| width: 8px; | |
| background: var(--ai-color); | |
| border-radius: 50%; | |
| display: inline-block; | |
| margin-right: 3px; | |
| animation: typing 1s infinite; | |
| } | |
| .typing-indicator span:nth-child(2) { | |
| animation-delay: 0.2s; | |
| } | |
| .typing-indicator span:nth-child(3) { | |
| animation-delay: 0.4s; | |
| } | |
| @keyframes typing { | |
| 0% { transform: translateY(0); } | |
| 50% { transform: translateY(-5px); } | |
| 100% { transform: translateY(0); } | |
| } | |
| .chat-time { | |
| font-size: 10px; | |
| color: #999; | |
| margin-top: 5px; | |
| text-align: right; | |
| } | |
| /* ์ฝ๋ ๋ธ๋ก ์คํ์ผ */ | |
| .chat-content pre { | |
| background: rgba(0, 0, 0, 0.05); | |
| padding: 10px; | |
| border-radius: 5px; | |
| overflow-x: auto; | |
| font-family: monospace; | |
| font-size: 12px; | |
| margin: 10px 0; | |
| } | |
| /* ๋งํฌ๋ค์ด ์คํ์ผ */ | |
| .chat-content strong { | |
| font-weight: bold; | |
| } | |
| .chat-content em { | |
| font-style: italic; | |
| } | |
| .chat-content ul, .chat-content ol { | |
| margin-left: 20px; | |
| margin-top: 5px; | |
| margin-bottom: 5px; | |
| } | |
| /* ๊ณต์ ๋ฒํผ */ | |
| #shareChat { | |
| padding: 8px 15px; | |
| background: #f1f1f1; | |
| border: none; | |
| border-radius: 20px; | |
| font-size: 12px; | |
| color: #666; | |
| cursor: pointer; | |
| margin-top: 5px; | |
| transition: var(--transition); | |
| } | |
| #shareChat:hover { | |
| background: #ddd; | |
| } | |
| /* ๋ฐ์ํ ๋์์ธ */ | |
| @media (max-width: 768px) { | |
| .grid { | |
| grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); | |
| gap: 16px; | |
| } | |
| .card { | |
| height: 240px; | |
| } | |
| .library-header .title { | |
| font-size: 1.25rem; | |
| padding: 10px 20px; | |
| } | |
| .floating-home, .floating-ai { | |
| width: 50px; | |
| height: 50px; | |
| } | |
| .floating-home .icon, .floating-ai .icon { | |
| font-size: 18px; | |
| } | |
| #adminButton { | |
| padding: 6px 15px; | |
| font-size: 12px; | |
| } | |
| #aiChatContainer { | |
| width: 100%; | |
| } | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <!-- ์ ๋ชฉ์ Home ๋ฒํผ๊ณผ ํจ๊ป ๋ ์ด์ด๋ก ์ฒ๋ฆฌ --> | |
| <div id="homeButton" class="floating-home" style="display:none;"> | |
| <div class="icon"><i class="fas fa-home"></i></div> | |
| <div class="title">ํ์ผ๋ก ๋์๊ฐ๊ธฐ</div> | |
| </div> | |
| <!-- AI ๋ฒํผ ์ถ๊ฐ --> | |
| <div id="aiButton" class="floating-ai" style="display:none;"> | |
| <div class="icon"><i class="fas fa-robot"></i></div> | |
| <div class="title">AI ์ด์์คํดํธ</div> | |
| </div> | |
| <!-- AI ์ฑ๋ด ์ปจํ ์ด๋ --> | |
| <div id="aiChatContainer"> | |
| <div id="aiChatHeader"> | |
| <h3><i class="fas fa-robot"></i> AI ์ด์์คํดํธ</h3> | |
| <button id="aiChatClose"><i class="fas fa-times"></i></button> | |
| </div> | |
| <div id="aiChatMessages"></div> | |
| <form id="aiChatForm"> | |
| <input type="text" id="aiChatInput" placeholder="PDF์ ๋ํด ์ง๋ฌธํ์ธ์..." autocomplete="off"> | |
| <button type="submit" id="aiChatSubmit"><i class="fas fa-paper-plane"></i></button> | |
| </form> | |
| </div> | |
| <!-- ๊ด๋ฆฌ์ ๋ฒํผ --> | |
| <div id="adminButton"> | |
| <i class="fas fa-cog"></i> Admin | |
| </div> | |
| <!-- ๊ด๋ฆฌ์ ๋ก๊ทธ์ธ ๋ชจ๋ฌ --> | |
| <div id="adminLoginModal" class="modal"> | |
| <div class="modal-content"> | |
| <h2>๊ด๋ฆฌ์ ๋ก๊ทธ์ธ</h2> | |
| <input type="password" id="adminPasswordInput" placeholder="๊ด๋ฆฌ์ ๋น๋ฐ๋ฒํธ"> | |
| <div> | |
| <button id="adminLoginButton">๋ก๊ทธ์ธ</button> | |
| <button id="adminLoginClose">์ทจ์</button> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- ์ผํฐ ์ ๋ ฌ๋ ํ์ดํ --> | |
| <div class="library-header"> | |
| <div class="title">AI FlipBook Maker</div> | |
| </div> | |
| <section id="home" class="fade-in"> | |
| <div class="upload-container"> | |
| <button class="upload" id="pdfUploadBtn"> | |
| <i class="fas fa-file-pdf"></i> PDF Upload | |
| </button> | |
| <button class="upload" id="textToAIBookBtn"> | |
| <i class="fas fa-file-alt"></i> Text to AI-Book | |
| </button> | |
| <input id="pdfInput" type="file" accept="application/pdf" style="display:none"> | |
| <input id="textInput" type="file" accept=".txt,.docx,.doc" style="display:none"> | |
| </div> | |
| <div class="section-title">Projects</div> | |
| <div class="grid" id="grid"> | |
| <!-- ์นด๋๊ฐ ์ฌ๊ธฐ์ ๋์ ์ผ๋ก ์ถ๊ฐ๋ฉ๋๋ค --> | |
| </div> | |
| <div id="noProjects" class="no-projects" style="display: none;"> | |
| ํ๋ก์ ํธ๊ฐ ์์ต๋๋ค. PDF๋ฅผ ์ถ๊ฐํ์ฌ ์์ํ์ธ์. | |
| </div> | |
| </section> | |
| <section id="viewerPage" style="display:none"> | |
| <div id="viewer"></div> | |
| <div id="loadingPages" class="loading-pages" style="display:none;">ํ์ด์ง ๋ก๋ฉ ์ค... <span id="loadingPagesCount">0/0</span></div> | |
| </section> | |
| <!-- ๊ด๋ฆฌ์ ํ์ด์ง --> | |
| <section id="adminPage" style="display:none" class="fade-in"> | |
| <h1>๊ด๋ฆฌ์ ํ์ด์ง</h1> | |
| <button id="adminBackButton"><i class="fas fa-arrow-left"></i> ๋ค๋ก ๊ฐ๊ธฐ</button> | |
| <div class="section-title">์ ์ฅ๋ PDF ๋ชฉ๋ก</div> | |
| <div class="grid" id="adminGrid"> | |
| <!-- ๊ด๋ฆฌ์ PDF ์นด๋๊ฐ ์ฌ๊ธฐ์ ๋์ ์ผ๋ก ์ถ๊ฐ๋ฉ๋๋ค --> | |
| </div> | |
| <div id="noAdminProjects" class="no-projects" style="display: none;"> | |
| ์ ์ฅ๋ PDF๊ฐ ์์ต๋๋ค. PDF๋ฅผ ์ ๋ก๋ํ์ฌ ์์ํ์ธ์. | |
| </div> | |
| </section> | |
| <script> | |
| let projects=[], fb=null; | |
| const grid=document.getElementById('grid'), viewer=document.getElementById('viewer'); | |
| pdfjsLib.GlobalWorkerOptions.workerSrc='/static/pdf.worker.js'; | |
| // ์๋ฒ์์ ๋ฏธ๋ฆฌ ๋ก๋๋ PDF ํ๋ก์ ํธ | |
| let serverProjects = []; | |
| // ํ์ฌ ํ์ด์ง ๋ก๋ฉ ์ํ | |
| let currentLoadingPdfPath = null; | |
| let pageLoadingInterval = null; | |
| // ํ์ฌ ์ด๋ฆฐ PDF์ ID | |
| let currentPdfId = null; | |
| // ์ค๋์ค ์ปจํ ์คํธ์ ์ด๊ธฐํ ์ํ ๊ด๋ฆฌ | |
| let audioInitialized = false; | |
| let audioContext = null; | |
| // AI ์ฑ๋ด ๊ด๋ จ ๋ณ์ | |
| let isAiChatActive = false; | |
| let isAiProcessing = false; | |
| let hasLoadedSummary = false; | |
| // ์ค๋์ค ์ด๊ธฐํ ํจ์ | |
| function initializeAudio() { | |
| if (audioInitialized) return Promise.resolve(); | |
| return new Promise((resolve) => { | |
| // ์ค๋์ค ์ปจํ ์คํธ ์์ฑ (์ฌ์ฉ์ ์ํธ์์ฉ์ด ํ์ ์๋ ์ด๊ธฐํ) | |
| audioContext = new (window.AudioContext || window.webkitAudioContext)(); | |
| // MP3 ๋ก๋ ๋ฐ ์ด๊ธฐํ | |
| const audio = new Audio('/static/turnPage2.mp3'); | |
| audio.volume = 0.01; // ์ต์ ๋ณผ๋ฅจ์ผ๋ก ์ค์ | |
| // ๋ก๋๋ ์ค๋์ค ์ฌ์ ์๋ (์ฌ์ฉ์ ์ํธ์์ฉ ์๊ตฌ๋ ์ ์์) | |
| const playPromise = audio.play(); | |
| if (playPromise !== undefined) { | |
| playPromise | |
| .then(() => { | |
| // ์ฑ๊ณต์ ์ผ๋ก ์ฌ์๋จ - ์ฆ์ ์ผ์์ ์ง | |
| audio.pause(); | |
| audioInitialized = true; | |
| console.log('์ค๋์ค ์ด๊ธฐํ ์ฑ๊ณต'); | |
| resolve(); | |
| }) | |
| .catch((error) => { | |
| console.log('์๋ ์ค๋์ค ์ด๊ธฐํ ์คํจ, ์ฌ์ฉ์ ์ํธ์์ฉ ํ์:', error); | |
| // ์ฌ์ฉ์ ์ํธ์์ฉ์ด ํ์ํ ๊ฒฝ์ฐ, ์ด๋ฒคํธ ๋ฆฌ์ค๋ ์ถ๊ฐ | |
| const initOnUserAction = function() { | |
| const tempAudio = new Audio('/static/turnPage2.mp3'); | |
| tempAudio.volume = 0.01; | |
| tempAudio.play() | |
| .then(() => { | |
| tempAudio.pause(); | |
| audioInitialized = true; | |
| console.log('์ฌ์ฉ์ ์ํธ์์ฉ์ผ๋ก ์ค๋์ค ์ด๊ธฐํ ์ฑ๊ณต'); | |
| resolve(); | |
| // ์ด๋ฒคํธ ๋ฆฌ์ค๋ ์ ๊ฑฐ | |
| ['click', 'touchstart', 'keydown'].forEach(event => { | |
| document.removeEventListener(event, initOnUserAction, { capture: true }); | |
| }); | |
| }) | |
| .catch(e => console.error('์ค๋์ค ์ด๊ธฐํ ์คํจ:', e)); | |
| }; | |
| // ์ฌ์ฉ์ ์ํธ์์ฉ ์ด๋ฒคํธ์ ๋ฆฌ์ค๋ ์ถ๊ฐ | |
| ['click', 'touchstart', 'keydown'].forEach(event => { | |
| document.addEventListener(event, initOnUserAction, { once: true, capture: true }); | |
| }); | |
| // ํ์ด์ง ๋ก๋ ์งํ ์ฌ์ฉ์์๊ฒ ์ค๋์ค ํ์ฑํ ์์ฒญ | |
| if (window.location.pathname.startsWith('/view/')) { | |
| // ์ค๋์ค ํ์ฑํ ์๋ด ๋ฉ์์ง ํ์ (๋ฐ๋ก๊ฐ๊ธฐ ๋งํฌ๋ก ์ ์ํ ๊ฒฝ์ฐ) | |
| setTimeout(() => { | |
| const audioPrompt = document.createElement('div'); | |
| audioPrompt.style.position = 'fixed'; | |
| audioPrompt.style.bottom = '80px'; | |
| audioPrompt.style.left = '50%'; | |
| audioPrompt.style.transform = 'translateX(-50%)'; | |
| audioPrompt.style.backgroundColor = 'rgba(0,0,0,0.7)'; | |
| audioPrompt.style.color = 'white'; | |
| audioPrompt.style.padding = '10px 20px'; | |
| audioPrompt.style.borderRadius = '20px'; | |
| audioPrompt.style.zIndex = '10000'; | |
| audioPrompt.style.cursor = 'pointer'; | |
| audioPrompt.innerHTML = 'ํ์ด์ง ์ด๋๋ ํด๋ฆญํ์ฌ ์๋ฆฌ ํจ๊ณผ ํ์ฑํ <i class="fas fa-volume-up"></i>'; | |
| audioPrompt.id = 'audioPrompt'; | |
| // ํด๋ฆญ ์ ์๋ฆฌ ํ์ฑํ ๋ฐ ๋ฉ์์ง ์ ๊ฑฐ | |
| audioPrompt.addEventListener('click', function() { | |
| initOnUserAction(); | |
| audioPrompt.remove(); | |
| }); | |
| document.body.appendChild(audioPrompt); | |
| // 10์ด ํ ์๋์ผ๋ก ์จ๊น | |
| setTimeout(() => { | |
| if (document.getElementById('audioPrompt')) { | |
| document.getElementById('audioPrompt').remove(); | |
| } | |
| }, 10000); | |
| }, 2000); | |
| } | |
| }); | |
| } else { | |
| // ๋ธ๋ผ์ฐ์ ๊ฐ Promise ๊ธฐ๋ฐ ์ฌ์์ ์ง์ํ์ง ์๋ ๊ฒฝ์ฐ | |
| audioInitialized = true; | |
| resolve(); | |
| } | |
| }); | |
| } | |
| /* โโ ์ ํธ โโ */ | |
| function $id(id){return document.getElementById(id)} | |
| // ํ์ฌ ์๊ฐ์ ํฌ๋งทํ ํ๋ ํจ์ | |
| function formatTime() { | |
| const now = new Date(); | |
| const hours = now.getHours().toString().padStart(2, '0'); | |
| const minutes = now.getMinutes().toString().padStart(2, '0'); | |
| return `${hours}:${minutes}`; | |
| } | |
| // AI ์ฑ๋ด ๋ฉ์์ง ์ถ๊ฐ ํจ์ | |
| function addChatMessage(content, isUser = false) { | |
| const messagesContainer = $id('aiChatMessages'); | |
| const messageElement = document.createElement('div'); | |
| messageElement.className = `chat-message ${isUser ? 'user' : 'ai'}`; | |
| const currentTime = formatTime(); | |
| messageElement.innerHTML = ` | |
| <div class="chat-avatar"> | |
| <i class="fas ${isUser ? 'fa-user' : 'fa-robot'}"></i> | |
| </div> | |
| <div class="chat-bubble"> | |
| <div class="chat-content">${content}</div> | |
| <div class="chat-time">${currentTime}</div> | |
| </div> | |
| `; | |
| messagesContainer.appendChild(messageElement); | |
| messagesContainer.scrollTop = messagesContainer.scrollHeight; | |
| return messageElement; | |
| } | |
| // ๋ก๋ฉ ํ์๊ธฐ ์ถ๊ฐ ํจ์ | |
| function addTypingIndicator() { | |
| const messagesContainer = $id('aiChatMessages'); | |
| const indicatorElement = document.createElement('div'); | |
| indicatorElement.className = 'typing-indicator'; | |
| indicatorElement.innerHTML = ` | |
| <div class="chat-avatar"> | |
| <i class="fas fa-robot"></i> | |
| </div> | |
| <div> | |
| <span></span> | |
| <span></span> | |
| <span></span> | |
| </div> | |
| `; | |
| messagesContainer.appendChild(indicatorElement); | |
| messagesContainer.scrollTop = messagesContainer.scrollHeight; | |
| return indicatorElement; | |
| } | |
| // AI ์ฑ๋ด ํ ๊ธ ํจ์ | |
| function toggleAiChat(show = true) { | |
| const aiChatContainer = $id('aiChatContainer'); | |
| if (show) { | |
| // ์ฑ๋ด ํ์ | |
| aiChatContainer.style.display = 'flex'; | |
| setTimeout(() => { | |
| aiChatContainer.classList.add('active'); | |
| }, 10); | |
| isAiChatActive = true; | |
| // ์ฒ์ ์ด ๋ ์๋ ์์ฝ ๋ก๋ | |
| if (!hasLoadedSummary && currentPdfId) { | |
| loadPdfSummary(); | |
| } | |
| } else { | |
| // ์ฑ๋ด ์จ๊ธฐ๊ธฐ | |
| aiChatContainer.classList.remove('active'); | |
| setTimeout(() => { | |
| aiChatContainer.style.display = 'none'; | |
| }, 300); | |
| isAiChatActive = false; | |
| } | |
| } | |
| // PDF ์์ฝ ๋ก๋ ํจ์ | |
| // PDF ์์ฝ ๋ก๋ ํจ์ | |
| async function loadPdfSummary() { | |
| if (!currentPdfId || isAiProcessing || hasLoadedSummary) return; | |
| try { | |
| isAiProcessing = true; | |
| const typingIndicator = addTypingIndicator(); | |
| // ์๋ฒ์ ์์ฝ ์์ฒญ | |
| const response = await fetch(`/api/ai/summarize-pdf/${currentPdfId}`); | |
| const data = await response.json(); | |
| // ๋ก๋ฉ ํ์๊ธฐ ์ ๊ฑฐ | |
| typingIndicator.remove(); | |
| if (data.error) { | |
| // ์ค๋ฅ ๋ฉ์์ง ํ์ | |
| addChatMessage(`PDF ์์ฝ์ ์์ฑํ๋ ์ค ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ต๋๋ค: ${data.error}<br><br>๊ณ์ ์ง๋ฌธ์ ์ ๋ ฅํ์๋ฉด PDF ๋ด์ฉ์ ๊ธฐ๋ฐ์ผ๋ก ๋ต๋ณ์ ์๋ํ๊ฒ ์ต๋๋ค.`); | |
| // ์์ฝ์ด ์คํจํด๋ ํน์ ๊ฒฝ์ฐ์๋ ์ฌ์ฉ์์๊ฒ ์๋ฆฌ๊ณ ๊ณ์ ์ฌ์ฉ ๊ฐ๋ฅํ๋๋ก ์ค์ | |
| if (data.summary) { | |
| addChatMessage(`<strong>PDF์์ ์ถ์ถํ ์ ๋ณด:</strong><br>${data.summary}`); | |
| hasLoadedSummary = true; | |
| } | |
| } else { | |
| // ํ์ ๋ฉ์์ง์ ์์ฝ ์ถ๊ฐ | |
| addChatMessage(`์๋ ํ์ธ์! ์ด PDF์ ๋ํด ์ด๋ค ๊ฒ์ด๋ ์ง๋ฌธํด์ฃผ์ธ์. ์ ๊ฐ ๋์๋๋ฆฌ๊ฒ ์ต๋๋ค.<br><br><strong>PDF ์์ฝ:</strong><br>${data.summary}`); | |
| hasLoadedSummary = true; | |
| } | |
| } catch (error) { | |
| console.error("PDF ์์ฝ ๋ก๋ ์ค๋ฅ:", error); | |
| addChatMessage(`PDF ์์ฝ์ ๋ก๋ํ๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. ์๋ฒ ์ฐ๊ฒฐ์ ํ์ธํด์ฃผ์ธ์.<br><br>์ด๋ค ์ง๋ฌธ์ด๋ ์ ๋ ฅํ์๋ฉด ์ต์ ์ ๋คํด ๋ต๋ณํ๊ฒ ์ต๋๋ค.`); | |
| } finally { | |
| isAiProcessing = false; | |
| } | |
| } | |
| // ์ง๋ฌธ ์ ์ถ ํจ์ | |
| async function submitQuestion(question) { | |
| if (!currentPdfId || isAiProcessing || !question.trim()) return; | |
| try { | |
| isAiProcessing = true; | |
| $id('aiChatSubmit').disabled = true; | |
| // ์ฌ์ฉ์ ๋ฉ์์ง ์ถ๊ฐ | |
| addChatMessage(question, true); | |
| // ๋ก๋ฉ ํ์๊ธฐ ์ถ๊ฐ | |
| const typingIndicator = addTypingIndicator(); | |
| // ์๋ฒ์ ์ง์ ์์ฒญ | |
| const response = await fetch(`/api/ai/query-pdf/${currentPdfId}`, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify({ query: question }), | |
| // ํ์์์ ์ค์ ์ถ๊ฐ | |
| signal: AbortSignal.timeout(60000) // 60์ด ํ์์์ | |
| }); | |
| const data = await response.json(); | |
| // ๋ก๋ฉ ํ์๊ธฐ ์ ๊ฑฐ | |
| typingIndicator.remove(); | |
| if (data.error) { | |
| // ์ค๋ฅ ๋ฉ์์ง์ ๋ฐ๋ผ ๋ค๋ฅธ ์น์ ํ ์๋ด ์ ๊ณต | |
| if (data.error.includes("API ํค")) { | |
| addChatMessage("์ฃ์กํฉ๋๋ค. ํ์ฌ AI ์๋น์ค์ ์ฐ๊ฒฐํ ์ ์์ต๋๋ค. ์์คํ ๊ด๋ฆฌ์์๊ฒ API ํค ์ค์ ์ ํ์ธํด๋ฌ๋ผ๊ณ ์์ฒญํด์ฃผ์ธ์."); | |
| } else if (data.error.includes("์ฐ๊ฒฐ")) { | |
| addChatMessage("์ฃ์กํฉ๋๋ค. AI ์๋น์ค์ ์ฐ๊ฒฐํ ์ ์์ต๋๋ค. ์ธํฐ๋ท ์ฐ๊ฒฐ์ ํ์ธํ๊ฑฐ๋ ์ ์ ํ ๋ค์ ์๋ํด์ฃผ์ธ์."); | |
| } else { | |
| addChatMessage(`์ฃ์กํฉ๋๋ค. ์ง๋ฌธ์ ๋ต๋ณํ๋ ์ค ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ต๋๋ค: ${data.error}`); | |
| } | |
| } else { | |
| // AI ์๋ต ์ถ๊ฐ | |
| addChatMessage(data.answer); | |
| } | |
| } catch (error) { | |
| console.error("์ง๋ฌธ ์ ์ถ ์ค๋ฅ:", error); | |
| if (error.name === 'AbortError') { | |
| addChatMessage("์ฃ์กํฉ๋๋ค. ์๋ต ์๊ฐ์ด ๋๋ฌด ์ค๋ ๊ฑธ๋ ค ์์ฒญ์ด ์ทจ์๋์์ต๋๋ค. ์ธํฐ๋ท ์ฐ๊ฒฐ์ ํ์ธํ๊ฑฐ๋ ๋ ์งง์ ์ง๋ฌธ์ผ๋ก ๋ค์ ์๋ํด๋ณด์ธ์."); | |
| } else { | |
| addChatMessage("์ฃ์กํฉ๋๋ค. ์๋ฒ์ ํต์ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. ์ ์ ํ ๋ค์ ์๋ํด์ฃผ์ธ์."); | |
| } | |
| } finally { | |
| isAiProcessing = false; | |
| $id('aiChatSubmit').disabled = false; | |
| $id('aiChatInput').value = ''; | |
| $id('aiChatInput').focus(); | |
| } | |
| } | |
| // DOM์ด ๋ก๋๋๋ฉด ์คํ | |
| document.addEventListener('DOMContentLoaded', function() { | |
| console.log("DOM ๋ก๋ ์๋ฃ, ์ด๋ฒคํธ ์ค์ ์์"); | |
| // ์ค๋์ค ์ด๊ธฐํ ์๋ | |
| initializeAudio().catch(e => console.warn('์ค๋์ค ์ด๊ธฐํ ์คํจ:', e)); | |
| // PDF ์ ๋ก๋ ๋ฒํผ | |
| const pdfBtn = document.getElementById('pdfUploadBtn'); | |
| const pdfInput = document.getElementById('pdfInput'); | |
| if (pdfBtn && pdfInput) { | |
| console.log("PDF ์ ๋ก๋ ๋ฒํผ ์ฐพ์"); | |
| // ๋ฒํผ ํด๋ฆญ ์ ํ์ผ ์ ๋ ฅ ํธ๋ฆฌ๊ฑฐ | |
| pdfBtn.addEventListener('click', function() { | |
| console.log("PDF ๋ฒํผ ํด๋ฆญ๋จ"); | |
| pdfInput.click(); | |
| }); | |
| // ํ์ผ ์ ํ ์ ์ฒ๋ฆฌ | |
| pdfInput.addEventListener('change', function(e) { | |
| console.log("PDF ํ์ผ ์ ํ๋จ:", e.target.files.length); | |
| const file = e.target.files[0]; | |
| if (!file) return; | |
| // ์๋ฒ์ PDF ์ ๋ก๋ (์๊ตฌ ์ ์ฅ์์ ์ ์ฅ) | |
| uploadPdfToServer(file); | |
| }); | |
| } else { | |
| console.error("PDF ์ ๋ก๋ ์์๋ฅผ ์ฐพ์ ์ ์์"); | |
| } | |
| // ํ ์คํธ ์ ๋ก๋ ๋ฒํผ | |
| const textBtn = document.getElementById('textToAIBookBtn'); | |
| const textInput = document.getElementById('textInput'); | |
| if (textBtn && textInput) { | |
| // ๋ฒํผ ํด๋ฆญ ์ ํ์ผ ์ ๋ ฅ ํธ๋ฆฌ๊ฑฐ | |
| textBtn.addEventListener('click', function() { | |
| textInput.click(); | |
| }); | |
| // ํ์ผ ์ ํ ์ ์ฒ๋ฆฌ | |
| textInput.addEventListener('change', function(e) { | |
| const file = e.target.files[0]; | |
| if (!file) return; | |
| // ์๋ฒ์ ํ ์คํธ ํ์ผ ์ ๋ก๋ (์๊ตฌ ์ ์ฅ์์ PDF๋ก ๋ณํํ์ฌ ์ ์ฅ) | |
| uploadTextToServer(file); | |
| }); | |
| } | |
| // ์๋ฒ PDF ๋ก๋ ๋ฐ ์บ์ ์ํ ํ์ธ | |
| loadServerPDFs(); | |
| // ์บ์ ์ํ๋ฅผ ์ฃผ๊ธฐ์ ์ผ๋ก ํ์ธ | |
| setInterval(checkCacheStatus, 3000); | |
| // ๊ด๋ฆฌ์ ๋ฒํผ ์ด๋ฒคํธ ์ค์ | |
| setupAdminFunctions(); | |
| // ํ ๋ฒํผ ์ด๋ฒคํธ ์ค์ | |
| const homeButton = document.getElementById('homeButton'); | |
| if (homeButton) { | |
| homeButton.addEventListener('click', function() { | |
| if(fb) { | |
| fb.destroy(); | |
| viewer.innerHTML = ''; | |
| fb = null; | |
| } | |
| toggle(true); | |
| // ๋ก๋ฉ ์ธ๋์ผ์ดํฐ ์ ๋ฆฌ | |
| if (pageLoadingInterval) { | |
| clearInterval(pageLoadingInterval); | |
| pageLoadingInterval = null; | |
| } | |
| $id('loadingPages').style.display = 'none'; | |
| currentLoadingPdfPath = null; | |
| currentPdfId = null; | |
| // AI ์ฑ๋ด ๋ซ๊ธฐ | |
| toggleAiChat(false); | |
| hasLoadedSummary = false; // ์์ฝ ๋ก๋ ์ํ ์ด๊ธฐํ | |
| }); | |
| } | |
| // AI ๋ฒํผ ์ด๋ฒคํธ ์ค์ | |
| const aiButton = document.getElementById('aiButton'); | |
| if (aiButton) { | |
| aiButton.addEventListener('click', function() { | |
| toggleAiChat(!isAiChatActive); | |
| }); | |
| } | |
| // AI ์ฑ๋ด ๋ซ๊ธฐ ๋ฒํผ | |
| const aiChatClose = document.getElementById('aiChatClose'); | |
| if (aiChatClose) { | |
| aiChatClose.addEventListener('click', function() { | |
| toggleAiChat(false); | |
| }); | |
| } | |
| // AI ์ฑ๋ด ํผ ์ ์ถ | |
| const aiChatForm = document.getElementById('aiChatForm'); | |
| if (aiChatForm) { | |
| aiChatForm.addEventListener('submit', function(e) { | |
| e.preventDefault(); | |
| const inputField = document.getElementById('aiChatInput'); | |
| const question = inputField.value.trim(); | |
| if (question && !isAiProcessing) { | |
| submitQuestion(question); | |
| } | |
| }); | |
| } | |
| }); | |
| // ์๋ฒ์ PDF ์ ๋ก๋ ํจ์ | |
| async function uploadPdfToServer(file) { | |
| try { | |
| showLoading("PDF ์ ๋ก๋ ์ค..."); | |
| const formData = new FormData(); | |
| formData.append('file', file); | |
| const response = await fetch('/api/upload-pdf', { | |
| method: 'POST', | |
| body: formData | |
| }); | |
| const result = await response.json(); | |
| if (result.success) { | |
| hideLoading(); | |
| // ์ ๋ก๋ ์ฑ๊ณต ์ ์๋ฒ PDF ๋ฆฌ์คํธ ๋ฆฌ๋ก๋ | |
| await loadServerPDFs(); | |
| // ์ฑ๊ณต ๋ฉ์์ง | |
| showMessage("PDF๊ฐ ์ฑ๊ณต์ ์ผ๋ก ์ ๋ก๋๋์์ต๋๋ค! ๊ณต์ URL: " + result.viewUrl); | |
| } else { | |
| hideLoading(); | |
| showError("์ ๋ก๋ ์คํจ: " + (result.message || "์ ์ ์๋ ์ค๋ฅ")); | |
| } | |
| } catch (error) { | |
| console.error("PDF ์ ๋ก๋ ์ค๋ฅ:", error); | |
| hideLoading(); | |
| showError("PDF ์ ๋ก๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| } | |
| } | |
| // ์๋ฒ์ ํ ์คํธ ํ์ผ์ ์ ๋ก๋ํ์ฌ PDF๋ก ๋ณํํ๋ ํจ์ | |
| async function uploadTextToServer(file) { | |
| try { | |
| showLoading("ํ ์คํธ ๋ถ์ ๋ฐ PDF ๋ณํ ์ค..."); | |
| const formData = new FormData(); | |
| formData.append('file', file); | |
| const response = await fetch('/api/text-to-pdf', { | |
| method: 'POST', | |
| body: formData | |
| }); | |
| const result = await response.json(); | |
| if (result.success) { | |
| hideLoading(); | |
| // ์ ๋ก๋ ์ฑ๊ณต ์ ์๋ฒ PDF ๋ฆฌ์คํธ ๋ฆฌ๋ก๋ | |
| await loadServerPDFs(); | |
| // ์ฑ๊ณต ๋ฉ์์ง | |
| showMessage("ํ ์คํธ๊ฐ ์ฑ๊ณต์ ์ผ๋ก PDF๋ก ๋ณํ๋์์ต๋๋ค! ๊ณต์ URL: " + result.viewUrl); | |
| } else { | |
| hideLoading(); | |
| showError("๋ณํ ์คํจ: " + (result.message || "์ ์ ์๋ ์ค๋ฅ")); | |
| } | |
| } catch (error) { | |
| console.error("ํ ์คํธ ๋ณํ ์ค๋ฅ:", error); | |
| hideLoading(); | |
| showError("ํ ์คํธ๋ฅผ PDF๋ก ๋ณํํ๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| } | |
| } | |
| function addCard(i, thumb, title, isCached = false, pdfId = null) { | |
| const d = document.createElement('div'); | |
| d.className = 'card fade-in'; | |
| d.onclick = () => open(i); | |
| // PDF ID๊ฐ ์์ผ๋ฉด ๋ฐ์ดํฐ ์์ฑ์ผ๋ก ์ ์ฅ | |
| if (pdfId) { | |
| d.dataset.pdfId = pdfId; | |
| } | |
| // ์ ๋ชฉ ์ฒ๋ฆฌ | |
| const displayTitle = title ? | |
| (title.length > 15 ? title.substring(0, 15) + '...' : title) : | |
| 'ํ๋ก์ ํธ ' + (i+1); | |
| // ์บ์ ์ํ ๋ฑ์ง ์ถ๊ฐ | |
| const cachedBadge = isCached ? | |
| '<div class="cached-status">์บ์๋จ</div>' : ''; | |
| // ๋ฐ๋ก๊ฐ๊ธฐ ๋งํฌ ์ถ๊ฐ (PDF ID๊ฐ ์๋ ๊ฒฝ์ฐ์๋ง) | |
| const linkHtml = pdfId ? | |
| `<div style="position: absolute; bottom: 55px; left: 50%; transform: translateX(-50%); z-index:5;"> | |
| <a href="/view/${pdfId}" target="_blank" style="color:#4a6ee0; font-size:11px;">Share Link</a> | |
| </div>` : ''; | |
| d.innerHTML = ` | |
| <div class="card-inner"> | |
| ${cachedBadge} | |
| <img src="${thumb}" alt="${displayTitle}" loading="lazy"> | |
| ${linkHtml} | |
| <p title="${title || 'ํ๋ก์ ํธ ' + (i+1)}">${displayTitle}</p> | |
| </div> | |
| `; | |
| grid.appendChild(d); | |
| // ํ๋ก์ ํธ๊ฐ ์์ผ๋ฉด 'ํ๋ก์ ํธ ์์' ๋ฉ์์ง ์จ๊ธฐ๊ธฐ | |
| $id('noProjects').style.display = 'none'; | |
| } | |
| /* โโ ํ๋ก์ ํธ ์ ์ฅ โโ */ | |
| function save(pages, title, isCached = false, pdfId = null) { | |
| const id = projects.push(pages) - 1; | |
| addCard(id, pages[0].thumb, title, isCached, pdfId); | |
| } | |
| /* โโ ์๋ฒ PDF ๋ก๋ ๋ฐ ์บ์ ์ํ ํ์ธ โโ */ | |
| async function loadServerPDFs() { | |
| try { | |
| // ๋ก๋ฉ ํ์ ์ถ๊ฐ | |
| if (document.querySelectorAll('.card').length === 0) { | |
| showLoading("๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ก๋ฉ ์ค..."); | |
| } | |
| // ๋จผ์ ์บ์ ์ํ ํ์ธ | |
| const cacheStatusRes = await fetch('/api/cache-status'); | |
| const cacheStatus = await cacheStatusRes.json(); | |
| // PDF ํ๋ก์ ํธ ๋ชฉ๋ก ๊ฐ์ ธ์ค๊ธฐ | |
| const response = await fetch('/api/pdf-projects'); | |
| serverProjects = await response.json(); | |
| // ๊ธฐ์กด ๊ทธ๋ฆฌ๋ ์ด๊ธฐํ | |
| grid.innerHTML = ''; | |
| projects = []; | |
| if (serverProjects.length === 0) { | |
| hideLoading(); | |
| $id('noProjects').style.display = 'block'; | |
| return; | |
| } | |
| // ์๋ฒ PDF ๋ก๋ ๋ฐ ์ธ๋ค์ผ ์์ฑ (๋ณ๋ ฌ ์ฒ๋ฆฌ๋ก ์ต์ ํ) | |
| const thumbnailPromises = serverProjects.map(async (project, index) => { | |
| updateLoading(`PDF ํ๋ก์ ํธ ๋ก๋ฉ ์ค... (${index+1}/${serverProjects.length})`); | |
| const pdfName = project.name; | |
| const isCached = cacheStatus[pdfName] && cacheStatus[pdfName].status === "completed"; | |
| try { | |
| // ์ธ๋ค์ผ ๊ฐ์ ธ์ค๊ธฐ | |
| 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, | |
| cached: isCached | |
| }]; | |
| return { | |
| pages, | |
| name: project.name, | |
| isCached, | |
| id: project.id | |
| }; | |
| } | |
| } catch (err) { | |
| console.error(`์ธ๋ค์ผ ๋ก๋ ์ค๋ฅ (${project.name}):`, err); | |
| } | |
| return null; | |
| }); | |
| // ๋ชจ๋ ์ธ๋ค์ผ ์์ฒญ ๊ธฐ๋ค๋ฆฌ๊ธฐ | |
| const results = await Promise.all(thumbnailPromises); | |
| // ์ฑ๊ณต์ ์ผ๋ก ๊ฐ์ ธ์จ ๊ฒฐ๊ณผ๋ง ํ์ | |
| results.filter(result => result !== null).forEach(result => { | |
| save(result.pages, result.name, result.isCached, result.id); | |
| }); | |
| hideLoading(); | |
| // ํ๋ก์ ํธ๊ฐ ์์ ๊ฒฝ์ฐ ๋ฉ์์ง ํ์ | |
| if (document.querySelectorAll('.card').length === 0) { | |
| $id('noProjects').style.display = 'block'; | |
| } | |
| } catch(error) { | |
| console.error('์๋ฒ PDF ๋ก๋ ์คํจ:', error); | |
| hideLoading(); | |
| showError("๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ก๋ฉ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| } | |
| } | |
| /* โโ ์บ์ ์ํ ์ ๊ธฐ์ ์ผ๋ก ํ์ธ โโ */ | |
| async function checkCacheStatus() { | |
| try { | |
| const response = await fetch('/api/cache-status'); | |
| const cacheStatus = await response.json(); | |
| // ํ์ฌ ์นด๋ ์ํ ์ ๋ฐ์ดํธ | |
| const cards = document.querySelectorAll('.card'); | |
| for(let i = 0; i < cards.length; i++) { | |
| if(projects[i] && projects[i][0] && projects[i][0].path) { | |
| const pdfPath = projects[i][0].path; | |
| const pdfName = pdfPath.split('/').pop().replace('.pdf', ''); | |
| // ์บ์ ์ํ ๋ฑ์ง ์ ๋ฐ์ดํธ | |
| let badgeEl = cards[i].querySelector('.cached-status'); | |
| if(cacheStatus[pdfName] && cacheStatus[pdfName].status === "completed") { | |
| if(!badgeEl) { | |
| badgeEl = document.createElement('div'); | |
| badgeEl.className = 'cached-status'; | |
| badgeEl.textContent = '์บ์๋จ'; | |
| cards[i].querySelector('.card-inner')?.appendChild(badgeEl); | |
| } else if (badgeEl.textContent !== '์บ์๋จ') { | |
| badgeEl.textContent = '์บ์๋จ'; | |
| badgeEl.style.background = 'var(--accent-color)'; | |
| } | |
| projects[i][0].cached = true; | |
| } else if(cacheStatus[pdfName] && cacheStatus[pdfName].status === "processing") { | |
| if(!badgeEl) { | |
| badgeEl = document.createElement('div'); | |
| badgeEl.className = 'cached-status'; | |
| cards[i].querySelector('.card-inner')?.appendChild(badgeEl); | |
| } | |
| badgeEl.textContent = `${cacheStatus[pdfName].progress}%`; | |
| badgeEl.style.background = 'var(--secondary-color)'; | |
| } | |
| } | |
| } | |
| // ํ์ฌ ๋ก๋ฉ ์ค์ธ PDF๊ฐ ์์ผ๋ฉด ์ํ ํ์ธ | |
| if (currentLoadingPdfPath && pageLoadingInterval) { | |
| const pdfName = currentLoadingPdfPath.split('/').pop().replace('.pdf', ''); | |
| if (cacheStatus[pdfName]) { | |
| const status = cacheStatus[pdfName].status; | |
| const progress = cacheStatus[pdfName].progress || 0; | |
| if (status === "completed") { | |
| // ์บ์ฑ ์๋ฃ ์ | |
| clearInterval(pageLoadingInterval); | |
| $id('loadingPages').style.display = 'none'; | |
| currentLoadingPdfPath = null; | |
| // ์๋ฃ๋ ์บ์๋ก ํ๋ฆฝ๋ถ ๋ค์ ๋ก๋ | |
| refreshFlipBook(); | |
| } else if (status === "processing") { | |
| // ์งํ ์ค์ผ ๋ ํ์ ์ ๋ฐ์ดํธ | |
| $id('loadingPages').style.display = 'block'; | |
| $id('loadingPagesCount').textContent = `${progress}%`; | |
| } | |
| } | |
| } | |
| } catch(error) { | |
| console.error('์บ์ ์ํ ํ์ธ ์ค๋ฅ:', error); | |
| } | |
| } | |
| /* โโ PDF ID๋ก PDF ์ด๊ธฐ โโ */ | |
| async function openPdfById(pdfId, pdfPath, isCached = false) { | |
| try { | |
| // ์ค๋์ค ์ด๊ธฐํ ์๋ | |
| await initializeAudio().catch(e => console.warn('PDF ์ด๊ธฐ ์ ์ค๋์ค ์ด๊ธฐํ ์คํจ:', e)); | |
| // ๋จผ์ ํ ํ๋ฉด์์ ์นด๋๋ฅผ ์ฐพ์์ ํด๋ฆญํ๋ ๋ฐฉ๋ฒ ์๋ | |
| let foundCard = false; | |
| const cards = document.querySelectorAll('.card'); | |
| for (let i = 0; i < cards.length; i++) { | |
| if (cards[i].dataset.pdfId === pdfId) { | |
| cards[i].click(); | |
| foundCard = true; | |
| break; | |
| } | |
| } | |
| // ์นด๋๋ฅผ ์ฐพ์ง ๋ชปํ ๊ฒฝ์ฐ ์ง์ ์คํ | |
| if (!foundCard) { | |
| toggle(false); | |
| showLoading("PDF ์ค๋น ์ค..."); | |
| let pages = []; | |
| // ์ด๋ฏธ ์บ์๋ ๊ฒฝ์ฐ ์บ์๋ ๋ฐ์ดํฐ ์ฌ์ฉ | |
| if (isCached) { | |
| try { | |
| const response = await fetch(`/api/cached-pdf?path=${encodeURIComponent(pdfPath)}`); | |
| const cachedData = await response.json(); | |
| if (cachedData.status === "completed" && cachedData.pages) { | |
| hideLoading(); | |
| createFlipBook(cachedData.pages); | |
| // ํ์ฌ ์ด๋ฆฐ PDF์ ID ์ ์ฅ | |
| currentPdfId = pdfId; | |
| // AI ๋ฒํผ ํ์ | |
| $id('aiButton').style.display = 'block'; | |
| return; | |
| } | |
| } catch (error) { | |
| console.error("์บ์ ๋ฐ์ดํฐ ๋ก๋ ์คํจ:", error); | |
| } | |
| } | |
| // ์ธ๋ค์ผ ๊ฐ์ ธ์ค๊ธฐ | |
| try { | |
| const thumbResponse = await fetch(`/api/pdf-thumbnail?path=${encodeURIComponent(pdfPath)}`); | |
| const thumbData = await thumbResponse.json(); | |
| if (thumbData.thumbnail) { | |
| pages = [{ | |
| src: thumbData.thumbnail, | |
| thumb: thumbData.thumbnail, | |
| path: pdfPath, | |
| cached: isCached | |
| }]; | |
| } | |
| } catch (error) { | |
| console.error("์ธ๋ค์ผ ๋ก๋ ์คํจ:", error); | |
| } | |
| // ์ผ๋จ ๊ธฐ๋ณธ ํ์ด์ง ์ถ๊ฐ | |
| if (pages.length === 0) { | |
| pages = [{ | |
| path: pdfPath, | |
| cached: isCached | |
| }]; | |
| } | |
| // ํ๋ก์ ํธ์ ์ถ๊ฐํ๊ณ ๋ทฐ์ด ์คํ | |
| const projectId = projects.push(pages) - 1; | |
| hideLoading(); | |
| open(projectId); | |
| // ํ์ฌ ์ด๋ฆฐ PDF์ ID ์ ์ฅ | |
| currentPdfId = pdfId; | |
| // AI ๋ฒํผ ํ์ | |
| $id('aiButton').style.display = 'block'; | |
| } | |
| } catch (error) { | |
| console.error("PDF ID๋ก ์ด๊ธฐ ์คํจ:", error); | |
| hideLoading(); | |
| showError("PDF๋ฅผ ์ด ์ ์์ต๋๋ค. ๋ค์ ์๋ํด์ฃผ์ธ์."); | |
| } | |
| } | |
| /* โโ ํ์ฌ PDF์ ๊ณ ์ URL ์์ฑ ๋ฐ ๋ณต์ฌ โโ */ | |
| function copyPdfShareUrl() { | |
| if (!currentPdfId) { | |
| showError("๊ณต์ ํ PDF๊ฐ ์์ต๋๋ค."); | |
| return; | |
| } | |
| // ํ์ฌ ๋๋ฉ์ธ ๊ธฐ๋ฐ ์ ์ฒด URL ์์ฑ | |
| const shareUrl = `${window.location.origin}/view/${currentPdfId}`; | |
| // ํด๋ฆฝ๋ณด๋์ ๋ณต์ฌ | |
| navigator.clipboard.writeText(shareUrl) | |
| .then(() => { | |
| showMessage("PDF ๋งํฌ๊ฐ ๋ณต์ฌ๋์์ต๋๋ค!"); | |
| }) | |
| .catch(err => { | |
| console.error("ํด๋ฆฝ๋ณด๋ ๋ณต์ฌ ์คํจ:", err); | |
| showError("๋งํฌ ๋ณต์ฌ์ ์คํจํ์ต๋๋ค."); | |
| }); | |
| } | |
| /* โโ ์นด๋ โ FlipBook โโ */ | |
| async function open(i) { | |
| toggle(false); | |
| const pages = projects[i]; | |
| // PDF ID ์ฐพ๊ธฐ ๋ฐ ์ ์ฅ | |
| const card = document.querySelectorAll('.card')[i]; | |
| if (card && card.dataset.pdfId) { | |
| currentPdfId = card.dataset.pdfId; | |
| // AI ๋ฒํผ ํ์ | |
| $id('aiButton').style.display = 'block'; | |
| } else { | |
| currentPdfId = null; | |
| // AI ๋ฒํผ ์จ๊น | |
| $id('aiButton').style.display = 'none'; | |
| } | |
| // AI ์ฑ๋ด ์ด๊ธฐํ | |
| toggleAiChat(false); | |
| hasLoadedSummary = false; | |
| $id('aiChatMessages').innerHTML = ''; | |
| // ๊ธฐ์กด FlipBook ์ ๋ฆฌ | |
| if(fb) { | |
| fb.destroy(); | |
| viewer.innerHTML = ''; | |
| } | |
| // ์๋ฒ PDF ๋๋ ๋ก์ปฌ ํ๋ก์ ํธ ์ฒ๋ฆฌ | |
| if(pages[0].path) { | |
| const pdfPath = pages[0].path; | |
| // ์ ์ง์ ๋ก๋ฉ ํ๋๊ทธ ์ด๊ธฐํ | |
| let progressiveLoading = false; | |
| currentLoadingPdfPath = pdfPath; | |
| // ์บ์ ์ฌ๋ถ ํ์ธ | |
| if(pages[0].cached) { | |
| // ์บ์๋ PDF ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ | |
| showLoading("์บ์๋ PDF ๋ก๋ฉ ์ค..."); | |
| try { | |
| const response = await fetch(`/api/cached-pdf?path=${encodeURIComponent(pdfPath)}`); | |
| const cachedData = await response.json(); | |
| if(cachedData.status === "completed" && cachedData.pages) { | |
| hideLoading(); | |
| createFlipBook(cachedData.pages); | |
| currentLoadingPdfPath = null; | |
| return; | |
| } else if(cachedData.status === "processing" && cachedData.pages && cachedData.pages.length > 0) { | |
| // ์ผ๋ถ ํ์ด์ง๊ฐ ์ด๋ฏธ ์ฒ๋ฆฌ๋ ๊ฒฝ์ฐ ์ ์ง์ ๋ก๋ฉ ์ฌ์ฉ | |
| hideLoading(); | |
| createFlipBook(cachedData.pages); | |
| progressiveLoading = true; | |
| // ์ ์ง์ ๋ก๋ฉ ์ค์์ ํ์ | |
| startProgressiveLoadingIndicator(cachedData.progress, cachedData.total_pages); | |
| } | |
| } catch(error) { | |
| console.error("์บ์ ๋ฐ์ดํฐ ๋ก๋ ์ค๋ฅ:", error); | |
| // ์บ์ ๋ก๋ฉ ์คํจ ์ ์๋ณธ PDF๋ก ๋์ฒด | |
| } | |
| } | |
| if (!progressiveLoading) { | |
| // ์บ์๊ฐ ์๊ฑฐ๋ ๋ก๋ฉ ์คํจ ์ ์๋ฒ PDF ๋ก๋ | |
| showLoading("PDF ์ค๋น ์ค..."); | |
| try { | |
| const response = await fetch(`/api/pdf-content?path=${encodeURIComponent(pdfPath)}`); | |
| const data = await response.json(); | |
| // ์บ์๋ก ๋ฆฌ๋ค์ด๋ ํธ๋ ๊ฒฝ์ฐ | |
| if(data.redirect) { | |
| const redirectRes = await fetch(data.redirect); | |
| const cachedData = await redirectRes.json(); | |
| if(cachedData.status === "completed" && cachedData.pages) { | |
| hideLoading(); | |
| createFlipBook(cachedData.pages); | |
| currentLoadingPdfPath = null; | |
| return; | |
| } else if(cachedData.status === "processing" && cachedData.pages && cachedData.pages.length > 0) { | |
| // ์ผ๋ถ ํ์ด์ง๊ฐ ์ด๋ฏธ ์ฒ๋ฆฌ๋ ๊ฒฝ์ฐ ์ ์ง์ ๋ก๋ฉ ์ฌ์ฉ | |
| hideLoading(); | |
| createFlipBook(cachedData.pages); | |
| // ์ ์ง์ ๋ก๋ฉ ์ค์์ ํ์ | |
| startProgressiveLoadingIndicator(cachedData.progress, cachedData.total_pages); | |
| return; | |
| } | |
| } | |
| // ์๋ณธ PDF ๋ก๋ (ArrayBuffer ํํ) | |
| const pdfResponse = await fetch(`/api/pdf-content?path=${encodeURIComponent(pdfPath)}`); | |
| // JSON ์๋ต์ธ ๊ฒฝ์ฐ (๋ฆฌ๋ค์ด๋ ํธ ๋ฑ) | |
| try { | |
| const jsonData = await pdfResponse.clone().json(); | |
| if (jsonData.redirect) { | |
| const redirectRes = await fetch(jsonData.redirect); | |
| const cachedData = await redirectRes.json(); | |
| if(cachedData.pages && cachedData.pages.length > 0) { | |
| hideLoading(); | |
| createFlipBook(cachedData.pages); | |
| if(cachedData.status === "processing") { | |
| startProgressiveLoadingIndicator(cachedData.progress, cachedData.total_pages); | |
| } else { | |
| currentLoadingPdfPath = null; | |
| } | |
| return; | |
| } | |
| } | |
| } catch (e) { | |
| // JSON ํ์ฑ ์คํจ ์ ์๋ณธ PDF ๋ฐ์ดํฐ๋ก ์ฒ๋ฆฌ | |
| } | |
| // ArrayBuffer ํํ์ PDF ๋ฐ์ดํฐ | |
| const pdfData = await pdfResponse.arrayBuffer(); | |
| // PDF ๋ก๋ ๋ฐ ํ์ด์ง ๋ ๋๋ง | |
| const pdf = await pdfjsLib.getDocument({data: pdfData}).promise; | |
| const pdfPages = []; | |
| for(let p = 1; p <= pdf.numPages; p++) { | |
| updateLoading(`ํ์ด์ง ์ค๋น ์ค... (${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()}); | |
| } | |
| hideLoading(); | |
| createFlipBook(pdfPages); | |
| currentLoadingPdfPath = null; | |
| } catch(error) { | |
| console.error('PDF ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์:', error); | |
| hideLoading(); | |
| showError("PDF๋ฅผ ๋ก๋ํ๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| currentLoadingPdfPath = null; | |
| } | |
| } | |
| } else { | |
| // ๋ก์ปฌ ์ ๋ก๋๋ ํ๋ก์ ํธ ์คํ | |
| createFlipBook(pages); | |
| currentLoadingPdfPath = null; | |
| } | |
| } | |
| /* โโ ์ ์ง์ ๋ก๋ฉ ์ธ๋์ผ์ดํฐ ์์ โโ */ | |
| function startProgressiveLoadingIndicator(progress, totalPages) { | |
| // ์งํ ์ํ ํ์ ํ์ฑํ | |
| $id('loadingPages').style.display = 'block'; | |
| $id('loadingPagesCount').textContent = `${progress}%`; | |
| // ๊ธฐ์กด ์ธํฐ๋ฒ ์ ๊ฑฐ | |
| if (pageLoadingInterval) { | |
| clearInterval(pageLoadingInterval); | |
| } | |
| // ์ฃผ๊ธฐ์ ์ผ๋ก ์บ์ ์ํ ํ์ธ (2์ด๋ง๋ค) | |
| pageLoadingInterval = setInterval(async () => { | |
| if (!currentLoadingPdfPath) { | |
| clearInterval(pageLoadingInterval); | |
| $id('loadingPages').style.display = 'none'; | |
| return; | |
| } | |
| try { | |
| const response = await fetch(`/api/cache-status?path=${encodeURIComponent(currentLoadingPdfPath)}`); | |
| const status = await response.json(); | |
| // ์ํ ์ ๋ฐ์ดํธ | |
| if (status.status === "completed") { | |
| clearInterval(pageLoadingInterval); | |
| $id('loadingPages').style.display = 'none'; | |
| refreshFlipBook(); // ์๋ฃ๋ ๋ฐ์ดํฐ๋ก ์๋ก๊ณ ์นจ | |
| currentLoadingPdfPath = null; | |
| } else if (status.status === "processing") { | |
| $id('loadingPagesCount').textContent = `${status.progress}%`; | |
| } | |
| } catch (e) { | |
| console.error("์บ์ ์ํ ํ์ธ ์ค๋ฅ:", e); | |
| } | |
| }, 1000); | |
| } | |
| /* โโ ํ๋ฆฝ๋ถ ์๋ก๊ณ ์นจ โโ */ | |
| async function refreshFlipBook() { | |
| if (!currentLoadingPdfPath || !fb) return; | |
| try { | |
| const response = await fetch(`/api/cached-pdf?path=${encodeURIComponent(currentLoadingPdfPath)}`); | |
| const cachedData = await response.json(); | |
| if(cachedData.status === "completed" && cachedData.pages) { | |
| // ๊ธฐ์กด ํ๋ฆฝ๋ถ ์ ๋ฆฌ | |
| fb.destroy(); | |
| viewer.innerHTML = ''; | |
| // ์ ๋ฐ์ดํฐ๋ก ์ฌ์์ฑ | |
| createFlipBook(cachedData.pages); | |
| currentLoadingPdfPath = null; | |
| } | |
| } catch (e) { | |
| console.error("ํ๋ฆฝ๋ถ ์๋ก๊ณ ์นจ ์ค๋ฅ:", e); | |
| } | |
| } | |
| 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'; | |
| // ์ฌ์ด๋ ์ด๊ธฐํ ์ฌ๋ถ ํ์ธ | |
| if (!audioInitialized) { | |
| initializeAudio() | |
| .then(() => console.log('FlipBook ์์ฑ ์ ์ค๋์ค ์ด๊ธฐํ ์๋ฃ')) | |
| .catch(e => console.warn('FlipBook ์์ฑ ์ ์ค๋์ค ์ด๊ธฐํ ์คํจ:', e)); | |
| } | |
| // ํ์ด์ง ๋ฐ์ดํฐ ์ ์ (๋น ํ์ด์ง ์ฒ๋ฆฌ) | |
| const validPages = pages.map(page => { | |
| // src๊ฐ ์๋ ํ์ด์ง๋ ๋ก๋ฉ ์ค ์ด๋ฏธ์ง๋ก ๋์ฒด | |
| if (!page || !page.src) { | |
| return { | |
| src: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjVmNWY1Ii8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxMiIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iIGZpbGw9IiM1NTUiPkxvYWRpbmcuLi48L3RleHQ+PC9zdmc+', | |
| thumb: page && page.thumb ? page.thumb : '' | |
| }; | |
| } | |
| return page; | |
| }); | |
| fb = new FlipBook(viewer, { | |
| pages: validPages, | |
| 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: true, // ๊ณต์ ๋ฒํผ ํ์ฑํ | |
| 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, // ์ปจํธ๋กค ํ์ ์๊ฐ ์ฐ์ฅ | |
| shareHandler: copyPdfShareUrl // ๊ณต์ ํธ๋ค๋ฌ ์ค์ | |
| } | |
| }); | |
| // ํ๋ฉด ํฌ๊ธฐ ๋ณ๊ฒฝ ์ 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); | |
| showError("FlipBook์ ์์ฑํ๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| } | |
| } | |
| /* โโ ๋ค๋น๊ฒ์ด์ โโ */ | |
| function toggle(showHome){ | |
| $id('home').style.display=showHome?'block':'none'; | |
| $id('viewerPage').style.display=showHome?'none':'block'; | |
| $id('homeButton').style.display=showHome?'none':'block'; | |
| $id('adminPage').style.display='none'; | |
| // AI ๋ฒํผ ๊ด๋ฆฌ | |
| $id('aiButton').style.display = (!showHome && currentPdfId) ? 'block' : 'none'; | |
| // AI ์ฑ๋ด์ด ์ด๋ ค์์ผ๋ฉด ๋ซ๊ธฐ | |
| if (isAiChatActive) { | |
| toggleAiChat(false); | |
| } | |
| // ๋ทฐ์ด ๋ชจ๋์ผ ๋ ์คํ์ผ ๋ณ๊ฒฝ | |
| if(!showHome) { | |
| document.body.classList.add('viewer-mode'); | |
| } else { | |
| document.body.classList.remove('viewer-mode'); | |
| } | |
| } | |
| /* -- ๊ด๋ฆฌ์ ๊ธฐ๋ฅ -- */ | |
| function setupAdminFunctions() { | |
| // ๊ด๋ฆฌ์ ๋ฒํผ ํด๋ฆญ - ๋ชจ๋ฌ ํ์ | |
| const adminButton = document.getElementById('adminButton'); | |
| const adminLoginModal = document.getElementById('adminLoginModal'); | |
| const adminLoginClose = document.getElementById('adminLoginClose'); | |
| const adminLoginButton = document.getElementById('adminLoginButton'); | |
| const adminPasswordInput = document.getElementById('adminPasswordInput'); | |
| const adminBackButton = document.getElementById('adminBackButton'); | |
| if (adminButton) { | |
| adminButton.addEventListener('click', function() { | |
| if (adminLoginModal) { | |
| adminLoginModal.style.display = 'flex'; | |
| if (adminPasswordInput) { | |
| adminPasswordInput.value = ''; | |
| adminPasswordInput.focus(); | |
| } | |
| } | |
| }); | |
| } | |
| // ๋ชจ๋ฌ ๋ซ๊ธฐ ๋ฒํผ | |
| if (adminLoginClose) { | |
| adminLoginClose.addEventListener('click', function() { | |
| if (adminLoginModal) { | |
| adminLoginModal.style.display = 'none'; | |
| } | |
| }); | |
| } | |
| // ์ํฐ ํค๋ก ๋ก๊ทธ์ธ | |
| if (adminPasswordInput) { | |
| adminPasswordInput.addEventListener('keyup', function(e) { | |
| if (e.key === 'Enter' && adminLoginButton) { | |
| adminLoginButton.click(); | |
| } | |
| }); | |
| } | |
| // ๋ก๊ทธ์ธ ๋ฒํผ | |
| if (adminLoginButton) { | |
| adminLoginButton.addEventListener('click', async function() { | |
| if (!adminPasswordInput) return; | |
| const password = adminPasswordInput.value; | |
| try { | |
| showLoading("๋ก๊ทธ์ธ ์ค..."); | |
| const formData = new FormData(); | |
| formData.append('password', password); | |
| const response = await fetch('/api/admin-login', { | |
| method: 'POST', | |
| body: formData | |
| }); | |
| const data = await response.json(); | |
| hideLoading(); | |
| if (data.success) { | |
| // ๋ก๊ทธ์ธ ์ฑ๊ณต - ๊ด๋ฆฌ์ ํ์ด์ง ํ์ | |
| if (adminLoginModal) { | |
| adminLoginModal.style.display = 'none'; | |
| } | |
| showAdminPage(); | |
| } else { | |
| // ๋ก๊ทธ์ธ ์คํจ | |
| showError("๊ด๋ฆฌ์ ์ธ์ฆ ์คํจ: ๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค."); | |
| } | |
| } catch (error) { | |
| console.error("๊ด๋ฆฌ์ ๋ก๊ทธ์ธ ์ค๋ฅ:", error); | |
| hideLoading(); | |
| showError("๋ก๊ทธ์ธ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| } | |
| }); | |
| } | |
| // ๊ด๋ฆฌ์ ํ์ด์ง ๋ค๋ก๊ฐ๊ธฐ | |
| if (adminBackButton) { | |
| adminBackButton.addEventListener('click', function() { | |
| document.getElementById('adminPage').style.display = 'none'; | |
| document.getElementById('home').style.display = 'block'; | |
| }); | |
| } | |
| } | |
| // ๊ด๋ฆฌ์ ํ์ด์ง ํ์ | |
| async function showAdminPage() { | |
| showLoading("๊ด๋ฆฌ์ ํ์ด์ง ๋ก๋ฉ ์ค..."); | |
| // ๋ค๋ฅธ ํ์ด์ง ์จ๊ธฐ๊ธฐ | |
| $id('home').style.display = 'none'; | |
| $id('viewerPage').style.display = 'none'; | |
| // ๊ด๋ฆฌ์ ํ์ด์ง์ PDF ๋ชฉ๋ก ๋ก๋ | |
| try { | |
| const response = await fetch('/api/permanent-pdf-projects'); | |
| const data = await response.json(); | |
| const adminGrid = $id('adminGrid'); | |
| adminGrid.innerHTML = ''; // ๊ธฐ์กด ๋ด์ฉ ์ง์ฐ๊ธฐ | |
| if (data.length === 0) { | |
| $id('noAdminProjects').style.display = 'block'; | |
| } else { | |
| $id('noAdminProjects').style.display = 'none'; | |
| // ๊ฐ PDF ํ์ผ์ ๋ํ ์นด๋ ์์ฑ | |
| const thumbnailPromises = data.map(async (pdf) => { | |
| try { | |
| // ์ธ๋ค์ผ ๊ฐ์ ธ์ค๊ธฐ | |
| const thumbResponse = await fetch(`/api/pdf-thumbnail?path=${encodeURIComponent(pdf.path)}`); | |
| const thumbData = await thumbResponse.json(); | |
| // ํ์ ์ฌ๋ถ ํ์ธ (๋ฉ์ธ ํ์ด์ง์ ํ์๋๋์ง) | |
| const mainPdfPath = pdf.path.split('/').pop(); | |
| const isMainDisplayed = serverProjects.some(p => p.path.includes(mainPdfPath)); | |
| // ๊ด๋ฆฌ์ ์นด๋ ์์ฑ | |
| const card = document.createElement('div'); | |
| card.className = 'admin-card card fade-in'; | |
| // ๊ณ ์ URL ์์ฑ | |
| const viewUrl = `${window.location.origin}/view/${pdf.id}`; | |
| // ์ธ๋ค์ผ ๋ฐ ์ ๋ณด | |
| card.innerHTML = ` | |
| <div class="card-inner"> | |
| ${pdf.cached ? '<div class="cached-status">์บ์๋จ</div>' : ''} | |
| <img src="${thumbData.thumbnail || ''}" alt="${pdf.name}" loading="lazy"> | |
| <p title="${pdf.name}">${pdf.name.length > 15 ? pdf.name.substring(0, 15) + '...' : pdf.name}</p> | |
| <div style="position: absolute; bottom: 130px; left: 50%; transform: translateX(-50%); z-index:10;"> | |
| <a href="${viewUrl}" target="_blank" style="color:#4a6ee0; font-size:12px;">๋ฐ๋ก๊ฐ๊ธฐ ๋งํฌ</a> | |
| </div> | |
| ${isMainDisplayed ? | |
| `<button class="unfeature-btn" data-path="${pdf.path}">๋ฉ์ธ์์ ์ ๊ฑฐ</button>` : | |
| `<button class="feature-btn" data-path="${pdf.path}">๋ฉ์ธ์ ํ์</button>`} | |
| <button class="delete-btn" data-path="${pdf.path}">์ญ์ </button> | |
| </div> | |
| `; | |
| adminGrid.appendChild(card); | |
| // ์ญ์ ๋ฒํผ ์ด๋ฒคํธ | |
| const deleteBtn = card.querySelector('.delete-btn'); | |
| if (deleteBtn) { | |
| deleteBtn.addEventListener('click', async function(e) { | |
| e.stopPropagation(); // ์นด๋ ํด๋ฆญ ์ด๋ฒคํธ ์ ํ ๋ฐฉ์ง | |
| if (confirm(`์ ๋ง "${pdf.name}" PDF๋ฅผ ์ญ์ ํ์๊ฒ ์ต๋๊น?`)) { | |
| try { | |
| showLoading("PDF ์ญ์ ์ค..."); | |
| const response = await fetch(`/api/admin/delete-pdf?path=${encodeURIComponent(pdf.path)}`, { | |
| method: 'DELETE' | |
| }); | |
| const result = await response.json(); | |
| hideLoading(); | |
| if (result.success) { | |
| card.remove(); | |
| showMessage("PDF๊ฐ ์ฑ๊ณต์ ์ผ๋ก ์ญ์ ๋์์ต๋๋ค."); | |
| // ๋ฉ์ธ PDF ๋ชฉ๋ก ์๋ก๊ณ ์นจ | |
| loadServerPDFs(); | |
| } else { | |
| showError("์ญ์ ์คํจ: " + (result.message || "์ ์ ์๋ ์ค๋ฅ")); | |
| } | |
| } catch (error) { | |
| console.error("PDF ์ญ์ ์ค๋ฅ:", error); | |
| hideLoading(); | |
| showError("PDF ์ญ์ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| } | |
| } | |
| }); | |
| } | |
| // ๋ฉ์ธ์ ํ์ ๋ฒํผ ์ด๋ฒคํธ | |
| const featureBtn = card.querySelector('.feature-btn'); | |
| if (featureBtn) { | |
| featureBtn.addEventListener('click', async function(e) { | |
| e.stopPropagation(); // ์นด๋ ํด๋ฆญ ์ด๋ฒคํธ ์ ํ ๋ฐฉ์ง | |
| try { | |
| showLoading("์ฒ๋ฆฌ ์ค..."); | |
| const response = await fetch(`/api/admin/feature-pdf?path=${encodeURIComponent(pdf.path)}`, { | |
| method: 'POST' | |
| }); | |
| const result = await response.json(); | |
| hideLoading(); | |
| if (result.success) { | |
| showMessage("PDF๊ฐ ๋ฉ์ธ ํ์ด์ง์ ํ์๋ฉ๋๋ค."); | |
| // ๊ด๋ฆฌ์ ํ์ด์ง ์๋ก๊ณ ์นจ | |
| showAdminPage(); | |
| // ๋ฉ์ธ PDF ๋ชฉ๋ก ์๋ก๊ณ ์นจ | |
| loadServerPDFs(); | |
| } else { | |
| showError("์ฒ๋ฆฌ ์คํจ: " + (result.message || "์ ์ ์๋ ์ค๋ฅ")); | |
| } | |
| } catch (error) { | |
| console.error("PDF ํ์ ์ค์ ์ค๋ฅ:", error); | |
| hideLoading(); | |
| showError("์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| } | |
| }); | |
| } | |
| // ๋ฉ์ธ์์ ์ ๊ฑฐ ๋ฒํผ ์ด๋ฒคํธ | |
| const unfeatureBtn = card.querySelector('.unfeature-btn'); | |
| if (unfeatureBtn) { | |
| unfeatureBtn.addEventListener('click', async function(e) { | |
| e.stopPropagation(); // ์นด๋ ํด๋ฆญ ์ด๋ฒคํธ ์ ํ ๋ฐฉ์ง | |
| try { | |
| showLoading("์ฒ๋ฆฌ ์ค..."); | |
| const response = await fetch(`/api/admin/unfeature-pdf?path=${encodeURIComponent(pdf.path)}`, { | |
| method: 'DELETE' | |
| }); | |
| const result = await response.json(); | |
| hideLoading(); | |
| if (result.success) { | |
| showMessage("PDF๊ฐ ๋ฉ์ธ ํ์ด์ง์์ ์ ๊ฑฐ๋์์ต๋๋ค."); | |
| // ๊ด๋ฆฌ์ ํ์ด์ง ์๋ก๊ณ ์นจ | |
| showAdminPage(); | |
| // ๋ฉ์ธ PDF ๋ชฉ๋ก ์๋ก๊ณ ์นจ | |
| loadServerPDFs(); | |
| } else { | |
| showError("์ฒ๋ฆฌ ์คํจ: " + (result.message || "์ ์ ์๋ ์ค๋ฅ")); | |
| } | |
| } catch (error) { | |
| console.error("PDF ํ์ ํด์ ์ค๋ฅ:", error); | |
| hideLoading(); | |
| showError("์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| } | |
| }); | |
| } | |
| } catch (error) { | |
| console.error(`PDF ${pdf.name} ์ฒ๋ฆฌ ์ค๋ฅ:`, error); | |
| } | |
| }); | |
| await Promise.all(thumbnailPromises); | |
| } | |
| // ๊ด๋ฆฌ์ ํ์ด์ง ํ์ | |
| hideLoading(); | |
| $id('adminPage').style.display = 'block'; | |
| } catch (error) { | |
| console.error("๊ด๋ฆฌ์ ํ์ด์ง ๋ก๋ ์ค๋ฅ:", error); | |
| hideLoading(); | |
| showError("๊ด๋ฆฌ์ ํ์ด์ง ๋ก๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."); | |
| $id('home').style.display = 'block'; // ์ค๋ฅ ์ ํ์ผ๋ก ๋ณต๊ท | |
| } | |
| } | |
| /* -- ๋ก๋ฉ ๋ฐ ์ค๋ฅ ํ์ -- */ | |
| function showLoading(message, progress = -1) { | |
| // ๊ธฐ์กด ๋ก๋ฉ ์ปจํ ์ด๋๊ฐ ์๋ค๋ฉด ์ ๊ฑฐ | |
| hideLoading(); | |
| const loadingContainer = document.createElement('div'); | |
| loadingContainer.className = 'loading-container fade-in'; | |
| loadingContainer.id = 'loadingContainer'; | |
| let progressBarHtml = ''; | |
| if (progress >= 0) { | |
| progressBarHtml = ` | |
| <div class="progress-bar-container"> | |
| <div id="progressBar" class="progress-bar" style="width: ${progress}%;"></div> | |
| </div> | |
| `; | |
| } | |
| loadingContainer.innerHTML = ` | |
| <div class="loading-spinner"></div> | |
| <p class="loading-text" id="loadingText">${message || '๋ก๋ฉ ์ค...'}</p> | |
| ${progressBarHtml} | |
| `; | |
| document.body.appendChild(loadingContainer); | |
| } | |
| function updateLoading(message, progress = -1) { | |
| const loadingText = $id('loadingText'); | |
| if (loadingText) { | |
| loadingText.textContent = message; | |
| } | |
| if (progress >= 0) { | |
| let progressBar = $id('progressBar'); | |
| if (!progressBar) { | |
| const loadingContainer = $id('loadingContainer'); | |
| if (loadingContainer) { | |
| const progressContainer = document.createElement('div'); | |
| progressContainer.className = 'progress-bar-container'; | |
| progressContainer.innerHTML = `<div id="progressBar" class="progress-bar" style="width: ${progress}%;"></div>`; | |
| loadingContainer.appendChild(progressContainer); | |
| progressBar = $id('progressBar'); | |
| } | |
| } else { | |
| progressBar.style.width = `${progress}%`; | |
| } | |
| } | |
| } | |
| function hideLoading() { | |
| const loadingContainer = $id('loadingContainer'); | |
| if (loadingContainer) { | |
| loadingContainer.remove(); | |
| } | |
| } | |
| function showError(message) { | |
| // ๊ธฐ์กด ์ค๋ฅ ๋ฉ์์ง๊ฐ ์๋ค๋ฉด ์ ๊ฑฐ | |
| const existingError = $id('errorContainer'); | |
| if (existingError) { | |
| existingError.remove(); | |
| } | |
| const errorContainer = document.createElement('div'); | |
| errorContainer.className = 'loading-container fade-in'; | |
| errorContainer.id = 'errorContainer'; | |
| errorContainer.innerHTML = ` | |
| <p class="loading-text" style="color: #e74c3c;">${message}</p> | |
| <button id="errorCloseBtn" style="margin-top: 15px; padding: 8px 16px; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer;">ํ์ธ</button> | |
| `; | |
| document.body.appendChild(errorContainer); | |
| // ํ์ธ ๋ฒํผ ํด๋ฆญ ์ด๋ฒคํธ | |
| $id('errorCloseBtn').onclick = () => { | |
| errorContainer.remove(); | |
| }; | |
| // 5์ด ํ ์๋์ผ๋ก ๋ซ๊ธฐ | |
| setTimeout(() => { | |
| if ($id('errorContainer')) { | |
| $id('errorContainer').remove(); | |
| } | |
| }, 5000); | |
| } | |
| function showMessage(message) { | |
| // ๊ธฐ์กด ๋ฉ์์ง๊ฐ ์๋ค๋ฉด ์ ๊ฑฐ | |
| const existingMessage = $id('messageContainer'); | |
| if (existingMessage) { | |
| existingMessage.remove(); | |
| } | |
| const messageContainer = document.createElement('div'); | |
| messageContainer.className = 'loading-container fade-in'; | |
| messageContainer.id = 'messageContainer'; | |
| messageContainer.innerHTML = ` | |
| <p class="loading-text" style="color: #2ecc71;">${message}</p> | |
| <button id="messageCloseBtn" style="margin-top: 15px; padding: 8px 16px; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer;">ํ์ธ</button> | |
| `; | |
| document.body.appendChild(messageContainer); | |
| // ํ์ธ ๋ฒํผ ํด๋ฆญ ์ด๋ฒคํธ | |
| $id('messageCloseBtn').onclick = () => { | |
| messageContainer.remove(); | |
| }; | |
| // 3์ด ํ ์๋์ผ๋ก ๋ซ๊ธฐ | |
| setTimeout(() => { | |
| if ($id('messageContainer')) { | |
| $id('messageContainer').remove(); | |
| } | |
| }, 3000); | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| if __name__ == "__main__": | |
| uvicorn.run("app:app", host="0.0.0.0", port=int(os.getenv("PORT", 7860))) |