From cb009f7393a7b3105f7bcbd7cfedac66b6b76a77 Mon Sep 17 00:00:00 2001 From: hyungi Date: Thu, 14 Aug 2025 08:09:48 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=99=84=EC=A0=84=ED=95=9C=20=EC=9B=B9?= =?UTF-8?q?=20UI=20=EA=B5=AC=ED=98=84=20=EB=B0=8F=20=EB=AC=B8=EC=84=9C=20?= =?UTF-8?q?=EC=B2=98=EB=A6=AC=20=ED=8C=8C=EC=9D=B4=ED=94=84=EB=9D=BC?= =?UTF-8?q?=EC=9D=B8=20=EC=99=84=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✨ 새로운 기능: - FastAPI 기반 완전한 웹 UI 구현 - 반응형 디자인 (모바일/태블릿 지원) - 드래그앤드롭 파일 업로드 인터페이스 - 실시간 AI 챗봇 인터페이스 - 문서 관리 및 검색 시스템 - 진행률 표시 및 상태 알림 🎨 UI 구성: - 메인 대시보드: 서버 상태, 통계, 빠른 접근 - 파일 업로드: 드래그앤드롭, 처리 옵션, 진행률 - 문서 관리: 검색, 정렬, 미리보기, 다운로드 - AI 챗봇: 실시간 대화, 문서 기반 RAG, 빠른 질문 🔧 기술 스택: - FastAPI + Jinja2 템플릿 - 모던 CSS (그라디언트, 애니메이션) - Font Awesome 아이콘 - JavaScript (ES6+) 🚀 완성된 기능: - 파일 업로드 → 텍스트 추출 → 임베딩 → 번역 → HTML 생성 - 벡터 검색 및 RAG 기반 질의응답 - 다중 모델 지원 (기본/부스팅/영어 전용) - API 키 인증 및 CORS 설정 - NAS 연동 및 파일 내보내기 --- ...nd Health Management(7:ED)_0 Contents.html | 493 ++++++++++++++ outputs/html/test.html | 20 + outputs/html/ui-test.html | 20 + requirements.txt | 2 + server/main.py | 117 +++- server/pipeline.py | 10 +- static/css/style.css | 394 +++++++++++ static/js/main.js | 87 +++ templates/base.html | 39 ++ templates/chat.html | 631 ++++++++++++++++++ templates/documents.html | 348 ++++++++++ templates/index.html | 229 +++++++ templates/upload.html | 395 +++++++++++ 13 files changed, 2781 insertions(+), 4 deletions(-) create mode 100644 outputs/html/Industrial Safety and Health Management(7:ED)_0 Contents.html create mode 100644 outputs/html/test.html create mode 100644 outputs/html/ui-test.html create mode 100644 static/css/style.css create mode 100644 static/js/main.js create mode 100644 templates/base.html create mode 100644 templates/chat.html create mode 100644 templates/documents.html create mode 100644 templates/index.html create mode 100644 templates/upload.html diff --git a/outputs/html/Industrial Safety and Health Management(7:ED)_0 Contents.html b/outputs/html/Industrial Safety and Health Management(7:ED)_0 Contents.html new file mode 100644 index 0000000..67e5b4e --- /dev/null +++ b/outputs/html/Industrial Safety and Health Management(7:ED)_0 Contents.html @@ -0,0 +1,493 @@ + + + + + +문서 Industrial Safety and Health Management(7:ED)_0 Contents-2025-08-13 (원문) + + + +
+

문서 Industrial Safety and Health Management(7:ED)_0 Contents-2025-08-13 (원문)

+
Industrial Safety and Health +Management +Seventh Edition +C. Ray Asfahl +David W. Rieske +University of Arkansas +Pearson +33o Hudson Street, NY NY 10013
+
+Senior Vice President Courseware Portfolio Management: Marcia Horton +Director, Portfolio Management: Engineering, Computer Science & Global Editions: Julian Partridge +Specialist, Higher Ed Portfolio Management: Holly Stark +Portfolio Management Assistant: Emily Egan +Managing Content Producer: Scott Disanno +Content Producer: Carole Snyder +Web Developer: Steve Wright +Rights and Permissions Manager: Ben Ferrini +Manufacturing Buyer, Higher Ed, Lake Side Communications Inc (LSC): Maura Zaldivar-Garcia +Inventory Manager: Ann Lam +Product Marketing Manager: Yvonne Vannatta +Field Marketing Manager: Demetrius Hall +Marketing Assistant: Jon Bryant +Cover Designer: Black Horse Designs +Full-Service Project Manager: Billu Suresh, SPi Global +Composition: SPi Global +Copyright © 2019 Pearson Education, Inc. All rights reserved. Manufactured in the United States of America. This +publication is protected by copyright, and permission should be obtained from the publisher prior to any prohibited +reproduction, storage in a retrieval system, or transmissio
+
tates of America. This +publication is protected by copyright, and permission should be obtained from the publisher prior to any prohibited +reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, +photocopying, recording, or likewise. For information regarding permissions, request forms and the appropriate +contacts within the Pearson Education Global Rights & Permissions department, please visit http://www.pearsoned +.com∕permissions. +Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where +those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been +printed in initial caps or all caps. +The author and publisher of this book have used their best efforts in preparing this book. These efforts include the +development, research, and testing of theories and programs to determine their effectiveness. The author and publisher +make no warranty of any kind, expressed or implied, with regard to these programs or the documentation contained +in this book. The author and publisher shall not be liable in any event for
+
ublisher +make no warranty of any kind, expressed or implied, with regard to these programs or the documentation contained +in this book. The author and publisher shall not be liable in any event for incidental or consequential damages with, or +arising out of, the furnishing, performance, or use of these programs. +Library of Congress Cataioging in-Publication Data +Names: Asfahl, C. Ray, 1938- author. ∣ Rieske, David W., author. +Title: Industrial safety and health management ∕ C. Ray Asfahl, David W. +Rieske, University of Arkansas. +Description: Seventh edition. ∣ NY, NY : Pearson, [2019] ∣ +Includes bibliographical references and index. +Identifiers: LCCN 2017050947 ∣ ISBN 9780134630564 (alk. paper) ∣ +ISBN 0134630564 (alk. paper) +Subjects: LCSH: Industrial safety. ∣ Industrial hygiene. +Classification: LCC T55 .A83 2019 ∣ DDC 658.4∕08--dc23 LC record available at https://lccn.loc.gov/2017050947 +Pearson ISBN-13: 978-0-13-463056-4 +ISBN-10: 0-13-463056-4 +17 2024
+
+Contents +Preface ix +CHAPTER 1 The Safety and Health Manager 1 +A Reasonable Objective 2 +Safety versus Health 4 +Role in the Corporate Structure 5 +Resources at Hand 6 +Summary 12 +Exercises and Study Questions 12 +Research Exercises
+
1 The Safety and Health Manager 1 +A Reasonable Objective 2 +Safety versus Health 4 +Role in the Corporate Structure 5 +Resources at Hand 6 +Summary 12 +Exercises and Study Questions 12 +Research Exercises 13 +CHAPTER 2 Development of the Safety and Health Function 15 +Workers’ Compensation 16 +Recordkeeping 21 +Accident Cause Analysis 35 +Organization of Committees 36 +Safety and Health Economics 37 +Training 41 +Job Placement Testing 43 +The Smoke-Free Workplace 44 +Bloodborne Pathogens 45 +Workplace Violence 47 +Summary 48 +Exercises and Study Questions 49 +Research Exercises 53 +CHAPTER Z Concepts of Hazard Avoidance 54 +The Enforcement Approach 55 +The Psychological Approach 57 +The Engineering Approach 59 +The Analytical Approach 67 +Hazard-Classification Scale 76 +Summary 82 +Exercises and Study Questions 83 +Research Exercises 86 +Standards Research Questions 87 +iii
+
+iv Contents +CHAPTER 4 Impact of Federal Regulation 88 +Standards 88 +NIOSH 93 +Enforcement 94 +Public Uproar IOO +Role of the States 102 +Political Trends 104 +Immigrant Workers 111 +Summary 111 +Exercises and Study Questions 112 +Research Exercises 113 +Standards Research Questions 114 +CHAPTER 5 Information Systems 115 +Hazard Communication 116 +Inter
+
Trends 104 +Immigrant Workers 111 +Summary 111 +Exercises and Study Questions 112 +Research Exercises 113 +Standards Research Questions 114 +CHAPTER 5 Information Systems 115 +Hazard Communication 116 +International Standards 123 +Environmental Protection Agency 123 +Department of Homeland Security 128 +Computer Information Systems 129 +Summary 131 +Exercises and Study Questions 131 +Research Exercises 132 +Standards Research Questions 133 +CHAPTER 6 Process Safety and Disaster Preparedness 134 +Process Information 135 +Process Analysis 139 +Operating Procedures 140 +Training 141 +Contractor Personnel 142 +Acts of Terrorism 142 +Workplace Security 145 +Active Shooter Incidents 146 +Summary 146 +Exercises and Study Questions 147 +Research Exercises 148 +Standards Research Questions 148 +CHAPTER 7 Buildings and Facilities 150 +Walking and Working Surfaces 151 +Exits 162 +Illumination 164 +Miscellaneous Facilities 165 +Sanitation 169 +Summary 169
+
+Contents v +Exercises and Study Questions 170 +Research Exercises 171 +Standards Research Questions 171 +CHAPTER 8 Ergonomics 172 +Facets of Ergonomics 172 +Workplace Musculoskeletal Disorders 176 +Affected Industries 179 +Ergonomics Standards 179 +WMSD Management Programs 182 +Ergon
+
rds Research Questions 171 +CHAPTER 8 Ergonomics 172 +Facets of Ergonomics 172 +Workplace Musculoskeletal Disorders 176 +Affected Industries 179 +Ergonomics Standards 179 +WMSD Management Programs 182 +Ergonomic Risk Analysis 184 +NIOSH Lifting Equation 185 +Sources of Ergonomic Hazards 193 +Summary 202 +Exercises and Study Questions 203 +Research Exercises 204 +Standards Research Question 205 +CHAPTER 9 Health and Toxic Substances 206 +Baseline Examinations 206 +Toxic Substances 207 +Measures of Exposure 216 +Standards Completion Project 220 +Detecting Contaminants 222 +Summary 229 +Exercises and Study Questions 230 +Research Exercises 234 +Standards Research Questions 235 +CHAPTER 10 Environmental Control and Noise 236 +Ventilation 236 +ASHRAE Standards and Indoor Air Quality 242 +Industrial Noise 243 +Radiation 260 +Summary 260 +Exercises and Study Questions 261 +Research Exercises 265 +Standards Research Questions 265 +CHAPTER 11 Flammable and Explosive Materials 267 +Flammable Liquids 267 +Sources of Ignition 272 +Standards Compliance 274 +Combustible Liquids 276 +Spray Finishing 278
+
+vi Contents +Dip Tanks 281 +Explosives 281 +Liquefied Petroleum Gas 282 +Combustible Dust 284 +Conclusion 285 +Exercises and Study Quest
+
tandards Compliance 274 +Combustible Liquids 276 +Spray Finishing 278
+
+vi Contents +Dip Tanks 281 +Explosives 281 +Liquefied Petroleum Gas 282 +Combustible Dust 284 +Conclusion 285 +Exercises and Study Questions 285 +Research Exercises 287 +Standards Research Questions 288 +CHAPTER 12 Personal Protection and First Aid 289 +Protection Need Assessment 290 +Personal Protective Equipment (PPE) Training 291 +Hearing Protection 292 +Determining the Noise Reduction Rating 293 +Eye and Face Protection 294 +Respiratory Protection 296 +Confined Space Entry 309 +Head Protection 312 +Miscellaneous Personal Protective Equipment 313 +First Aid 315 +Summary 316 +Exercises and Study Questions 317 +Research Exercises 319 +Standards Research Questions 320 +CHAPTER 13 Fire Protection 321 +Mechanics of Fire 322 +Industrial Fires 322 +Fire Prevention 323 +Dust Explosions 323 +Emergency Evacuation 324 +Fire Brigades 326 +Fire Extinguishers 327 +Standpipe and Hose Systems 329 +Automatic Sprinkler Systems 330 +Fixed Extinguishing Systems 330 +Summary 331 +Exercises and Study Questions 332 +Research Exercises 334 +Standards Research Questions 334 +CHAPTER 14 Materials Handling and Storage 335 +Materials Storage 336 +Industrial Trucks 337 +Passenger
+
ummary 331 +Exercises and Study Questions 332 +Research Exercises 334 +Standards Research Questions 334 +CHAPTER 14 Materials Handling and Storage 335 +Materials Storage 336 +Industrial Trucks 337 +Passengers 343 +Cranes 344
+
+Contents vii +Slings 358 +Conveyors 362 +Lifting 363 +Summary 365 +Exercises and Study Questions 365 +Research Exercise 368 +CHAPTER 15 Machine Guarding 369 +General Machine Guarding 369 +Safeguarding the Point of Operation 379 +Power Presses 386 +Heat Processes 406 +Grinding Machines 406 +Saws 408 +Miscellaneous Machine Guarding 413 +Miscellaneous Machines and Processes 416 +Industrial Robots 417 +Evolution in Robotics and Intelligent Machines 420 +Summary 421 +Exercises and Study Questions 422 +Standards Research Questions 425 +CHAPTER 16 Welding 426 +Process Terminology 426 +Gas Welding Hazards 430 +Arc Welding Hazards 437 +Resistance Welding Hazards 438 +Fires and Explosions 439 +Eye Protection 441 +Protective Clothing 442 +Gases and Fumes 443 +Summary 446 +Exercises and Study Questions 447 +Research Exercises 449 +Standards Research Questions 450 +CHAPTER 17 Electrical Hazards 451 +Electrocution Hazards 451 +Fire Hazards 464 +Arc Flash 469 +Test Equipment 471 +Exposure to High-Voltage Power Lines 473
+
ch Exercises 449 +Standards Research Questions 450 +CHAPTER 17 Electrical Hazards 451 +Electrocution Hazards 451 +Fire Hazards 464 +Arc Flash 469 +Test Equipment 471 +Exposure to High-Voltage Power Lines 473 +Frequent Violations 473 +Summary 474 +Exercises and Study Questions 475
+
+viii Contents +Research Exercises 478 +Standards Research Questions 478 +CHAPTER 18 Construction 479 +General Facilities 480 +Personal Protective Equipment 482 +Fire Protection 486 +Tools 486 +Electrical 488 +Ladders and Scaffolds 490 +Floors and Stairways 493 +Cranes and Hoists 493 +Heavy Vehicles and Equipment 498 +ROPS 498 +Trenching and Excavations 501 +Concrete Work 505 +Steel Erection 507 +Demolition 508 +Explosive Blasting 509 +Electric Utilities 510 +Summary 511 +Exercises and Study Questions 512 +Research Exercises 515 +APPENDICES +A OSHA Permissible Exposure Limits 516 +B Medical Treatment 535 +C First-Aid Treatment 536 +D Classification of Medical Treatment 538 +E Highly Hazardous Chemicals, Toxics, and Reactives 540 +F North American Industry Classification System (NAICS) Code 544 +G States Having Federally Approved State Plans for +Occupational Safety and Health Standards and Enforcement 548 +Bibliography 549 +Glossary 560 +Index 568
+
Industry Classification System (NAICS) Code 544 +G States Having Federally Approved State Plans for +Occupational Safety and Health Standards and Enforcement 548 +Bibliography 549 +Glossary 560 +Index 568
+
+Preface +The seventh edition of Industrial Safety and Health Management remains true to +the purpose of engaging the reader in the common sense approaches to safety and +health from a concept, process, and compliance perspective. The book retains its +easy-to-read format while increasing the retention of the reader through additional +case studies and statistics, relevant topics, and additional explanation of difficult-to- +Understand concepts. +Much of the safety change we see comes on the heels of major disasters or +social trends and changes. The past decade has seen many. The explosion of a major +sugar processing plant has driven a renewed focus on combustible dust, an outbreak +of Ebola brought focus on contagious diseases, the sinking of a major oil derrick +initiated a discussion on regulatory oversight and process health, and numerous +acts of violence bring our attention to security in the workplace. Social trends such +as the rise of "gig" or "on-demand" employment have brou
+
n regulatory oversight and process health, and numerous +acts of violence bring our attention to security in the workplace. Social trends such +as the rise of "gig" or "on-demand" employment have brought about questions +of the definition of an "employee" and coverage for safety nets such as workers’ +compensation. Regulatory changes have even precipitated the complete removal of +workers’ compensation in some states. In other areas, the effectiveness of workers’ +compensation led to a robust dialog on whether or not a permanently injured em­ +ployee truly receives compensation commensurate to his or her injury. Meanwhile +rises in the number of states legalizing marijuana have caused companies to ques­ +tion current drug screening programs and medical treatment programs. +Regulation has changed as well. The adoption of the Globally Harmonized System +for Hazard Communication or GHS has completely changed the way we think about +hazard communication. The new system crosses language barriers and helps workers +who may not be able to read or may not be fluent in a given language with a series of +pictograms depicting the dangers of certain chemicals. Hazards are now categorized +in a st
+
rs and helps workers +who may not be able to read or may not be fluent in a given language with a series of +pictograms depicting the dangers of certain chemicals. Hazards are now categorized +in a standard way which drives increased consistency of approach. For the first time in +nearly 20 years, fines associated with citations have gone up considerably. Meanwhile, +record fines have been levied against corporations associated with major disasters. The +classification of companies has also been changed to the modernized North America +Industry Classification System (NAICS). +As the authors have used the text in their classrooms, a critical focus has been +on addressing the most common areas that students will be expected to apply in +an industrial setting. Additional explanation around the concepts of PELs has been +given to help students to understand the differences among PEL’S, Ceilings, and +other measures. Calculations around the Noise Reduction Rating (NRR) and how it +is practically used will help students address the prevalent danger of industrial noise +in their work environments. In addition, explained in more detail is sometimes the +confusing concept of applying workers
+
ally used will help students address the prevalent danger of industrial noise +in their work environments. In addition, explained in more detail is sometimes the +confusing concept of applying workers’ compensation and practical aspects of pro­ +tecting employees.
+
+X Preface +WHAT'S NEW IN THIS EDITION? +For easy reference, the authors have summarized the new features of this edition as +follows: +• Overhaul of hazard communication standard and incorporation of the Globally +Harmonized System +• Increased discussion on workers’ compensation rates and calculations +• Trends in workers’ compensation privatization and states “opting-out” +• Layers of coverage for permanent injuries +• Coverage of the trends in the gig economy and the changing nature of +employees +• OSHA usage of reporting in “Big Data” +• Changes in SIC to North American Industry Classification System (NAICS) +• Discussion of bloodborne pathogens and protecting workers from diseases such +as HIV and Ebola +• Increased coverage of workplace security +• Discussion of preparation and response techniques for active shooter scenarios +• Impact of medical marijuana +• Changes in OSHA citation penalty levels +• Increased coverage of Targe
+
orkplace security +• Discussion of preparation and response techniques for active shooter scenarios +• Impact of medical marijuana +• Changes in OSHA citation penalty levels +• Increased coverage of Target Industry programs +• Coverage of fatigue and worker safety +• Practical discussion of PELs, STELs, Ceiling Limits and how they interact +• Changes to flammable liquid classification +• Coverage of calculations and usage of Noise Reduction Rating (NRR) +• Coverage of long-term health impact to World Trade Center first responders +• OSHA s work against the dangers of combustible dust +• Additional practical and pragmatic assessment of penalty levels +• Additional review of OSHA programs such as SHARP and VPP as OSHA is +increasing its collaborative approach in recent years +• Additional case studies to bring home to readers about the concepts of safety and +health
+
+Preface xi +ACKNOWLEDGMENTS +Both authors wish to express their appreciation to companies and individuals who have +contributed ideas and support for the seventh edition. Special thanks to Richard +Wallace, Jimmy Baker, and the entire team at Pratt & Whitney for ideas, pictures, +and best practices from their world-class facility. And
+
d support for the seventh edition. Special thanks to Richard +Wallace, Jimmy Baker, and the entire team at Pratt & Whitney for ideas, pictures, +and best practices from their world-class facility. Andrew Hilliard, President of Safety +Maker, Inc. and E.C. Daven, President of Safety Services, Inc. provided valuable insights +and visual examples. Erica Asfahl provided mechanical engineering advice. David Trigg +and David Bryan answered questions and provided data on OSHA developments. +We are grateful to Ken Kolosh and the team at the National Safety Council for their +statistics provided in many areas of the text. Tara Mercer and the National Council on +Compensation Insurance shared valuable insights into trends and developments such +as the gig economy and the impact of medical marijuana. We learned from Alejandra +Nolibos about developments in state workers’ compensation changes. Finally, we +dedicate this edition to our patient and supportive families who have endured the +process of bringing forth this seventh edition. +C. Ray Asfahl +David W. Rieske
+
+ + diff --git a/outputs/html/test.html b/outputs/html/test.html new file mode 100644 index 0000000..e2c070e --- /dev/null +++ b/outputs/html/test.html @@ -0,0 +1,20 @@ + + + + + +문서 test-doc-001 (원문) + + + +
+

문서 test-doc-001 (원문)

+
테스트 문서입니다.
+
+ + diff --git a/outputs/html/ui-test.html b/outputs/html/ui-test.html new file mode 100644 index 0000000..c8a5891 --- /dev/null +++ b/outputs/html/ui-test.html @@ -0,0 +1,20 @@ + + + + + +문서 ui-test-001 (원문) + + + +
+

문서 ui-test-001 (원문)

+
UI 테스트용 문서입니다. 웹 인터페이스를 통한 업로드 테스트.
+
+ + diff --git a/requirements.txt b/requirements.txt index 25c7c6a..6ce7f8d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,3 +4,5 @@ requests==2.32.4 pydantic==2.8.2 pypdf==6.0.0 tiktoken==0.11.0 +python-multipart +jinja2 diff --git a/server/main.py b/server/main.py index 7ac1464..82db7f6 100644 --- a/server/main.py +++ b/server/main.py @@ -1,11 +1,16 @@ from __future__ import annotations -from fastapi import FastAPI, HTTPException, Depends, UploadFile, File, Form +from fastapi import FastAPI, HTTPException, Depends, UploadFile, File, Form, Request from fastapi.middleware.cors import CORSMiddleware +from fastapi.templating import Jinja2Templates +from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse from pydantic import BaseModel from typing import List, Dict, Any import shutil from pathlib import Path +import os +from datetime import datetime from .config import settings from .ollama_client import OllamaClient @@ -18,6 +23,14 @@ from .pipeline import DocumentPipeline app = FastAPI(title="Local AI Server", version="0.2.1") +# 템플릿과 정적 파일 설정 +templates = Jinja2Templates(directory="templates") +app.mount("/static", StaticFiles(directory="static"), name="static") + +# HTML 출력 디렉토리도 정적 파일로 서빙 +if Path("outputs/html").exists(): + app.mount("/html", StaticFiles(directory="outputs/html"), name="html") + # CORS import os cors_origins = os.getenv("CORS_ORIGINS", "*") @@ -68,6 +81,7 @@ class PipelineIngestRequest(BaseModel): summarize: bool = False summary_sentences: int = 5 summary_language: str | None = None + html_basename: str | None = None @app.get("/health") @@ -179,6 +193,7 @@ def pipeline_ingest(req: PipelineIngestRequest, _: None = Depends(require_api_ke summarize=req.summarize, summary_sentences=req.summary_sentences, summary_language=req.summary_language, + html_basename=req.html_basename, ) exported_html: str | None = None if result.html_path and settings.export_html_dir: @@ -233,6 +248,7 @@ async def pipeline_ingest_file( generate_html=generate_html, translate=translate, target_language=target_language, + html_basename=file.filename, ) exported_html: str | None = None if result.html_path and settings.export_html_dir: @@ -356,3 +372,102 @@ def chat_completions(req: ChatCompletionsRequest, _: None = Depends(require_api_ ], } + +# ============================================================================= +# UI 라우트들 +# ============================================================================= + +@app.get("/", response_class=HTMLResponse) +async def dashboard(request: Request): + """메인 대시보드 페이지""" + # 서버 상태 가져오기 + status = { + "base_model": settings.base_model, + "boost_model": settings.boost_model, + "embedding_model": settings.embedding_model, + "index_loaded": len(index.rows) if index else 0, + } + + # 최근 문서 (임시 데이터 - 실제로는 DB나 파일에서 가져올 것) + recent_documents = [] + + # 통계 (임시 데이터) + stats = { + "total_documents": len(index.rows) if index else 0, + "total_chunks": len(index.rows) if index else 0, + "today_processed": 0, + } + + return templates.TemplateResponse("index.html", { + "request": request, + "status": status, + "recent_documents": recent_documents, + "stats": stats, + }) + + +@app.get("/upload", response_class=HTMLResponse) +async def upload_page(request: Request): + """파일 업로드 페이지""" + return templates.TemplateResponse("upload.html", { + "request": request, + "api_key": os.getenv("API_KEY", "") + }) + + +def format_file_size(bytes_size): + """파일 크기 포맷팅 헬퍼 함수""" + if bytes_size == 0: + return "0 Bytes" + k = 1024 + sizes = ["Bytes", "KB", "MB", "GB"] + i = int(bytes_size / k) + if i >= len(sizes): + i = len(sizes) - 1 + return f"{bytes_size / (k ** i):.2f} {sizes[i]}" + + +@app.get("/documents", response_class=HTMLResponse) +async def documents_page(request: Request): + """문서 관리 페이지""" + # HTML 파일 목록 가져오기 + html_dir = Path("outputs/html") + html_files = [] + if html_dir.exists(): + for file in html_dir.glob("*.html"): + stat = file.stat() + html_files.append({ + "name": file.name, + "size": stat.st_size, + "created": datetime.fromtimestamp(stat.st_ctime).strftime("%Y-%m-%d %H:%M"), + "url": f"/html/{file.name}" + }) + + # 날짜순 정렬 (최신순) + html_files.sort(key=lambda x: x["created"], reverse=True) + + return templates.TemplateResponse("documents.html", { + "request": request, + "documents": html_files, + "formatFileSize": format_file_size, + }) + + +@app.get("/chat", response_class=HTMLResponse) +async def chat_page(request: Request): + """AI 챗봇 페이지""" + # 서버 상태 정보 + status = { + "base_model": settings.base_model, + "boost_model": settings.boost_model, + "embedding_model": settings.embedding_model, + "index_loaded": len(index.rows) if index else 0, + } + + return templates.TemplateResponse("chat.html", { + "request": request, + "status": status, + "current_time": datetime.now().strftime("%H:%M"), + "api_key": os.getenv("API_KEY", "") + }) + diff --git a/server/pipeline.py b/server/pipeline.py index 55f0f40..ed83f22 100644 --- a/server/pipeline.py +++ b/server/pipeline.py @@ -73,8 +73,10 @@ class DocumentPipeline: translated.append(content.strip()) return translated - def build_html(self, doc_id: str, title: str, ko_text: str) -> str: - html_path = self.output_dir / "html" / f"{doc_id}.html" + def build_html(self, basename: str, title: str, ko_text: str) -> str: + # Ensure .html suffix and sanitize basename + safe_base = Path(basename).stem + ".html" + html_path = self.output_dir / "html" / safe_base html = f""" \n\n\n{title}\n +{% endblock %} + +{% block scripts %} + +{% endblock %} \ No newline at end of file diff --git a/templates/documents.html b/templates/documents.html new file mode 100644 index 0000000..3959ccc --- /dev/null +++ b/templates/documents.html @@ -0,0 +1,348 @@ +{% extends "base.html" %} + +{% block title %}문서 관리 - AI 문서 처리 서버{% endblock %} + +{% block content %} +
+
+

+ 문서 관리 +

+

처리된 문서들을 확인하고 관리하세요

+
+ + +
+
+

총 문서 수

+
{{ documents|length }}
+
+
+

총 용량

+
계산 중...
+
+
+

최근 업로드

+
+ {% if documents %} + {{ documents[0].created.split(' ')[0] }} + {% else %} + 없음 + {% endif %} +
+
+
+ + +
+
+
+ +
+
+ +
+
+
+ + + {% if documents %} +
+ + + + + + + + + + + {% for doc in documents %} + + + + + + + {% endfor %} + +
파일명 생성일시 크기 액션
+
+ + {{ doc.name }} +
+ {{ formatFileSize(doc.size) }} +
+
{{ doc.created }} + {{ formatFileSize(doc.size) }} + +
+ + + + + + +
+
+
+ {% else %} +
+ +

처리된 문서가 없습니다

+

파일을 업로드하여 AI 처리를 시작하세요.

+ + 첫 문서 업로드하기 + +
+ {% endif %} +
+ + + + + +{% endblock %} + +{% block scripts %} + +{% endblock %} \ No newline at end of file diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..23d579e --- /dev/null +++ b/templates/index.html @@ -0,0 +1,229 @@ +{% extends "base.html" %} + +{% block title %}AI 문서 처리 서버 - 대시보드{% endblock %} + +{% block content %} +
+
+

+ 대시보드 +

+

AI 문서 처리 서버 현황을 확인하세요

+
+ + +
+
+

서버 상태

+
+ 정상 운영 +
+

+ 모델: {{ status.base_model }}
+ 임베딩: {{ status.embedding_model }}
+ 인덱스: {{ status.index_loaded }}개 문서 +

+
+ +
+

빠른 업로드

+
+ +

파일을 업로드하려면 클릭하세요

+
+
+ +
+

빠른 검색

+
+ + +
+
+
+
+ + +
+
+

+ 최근 처리된 문서 +

+ 모든 문서 보기 +
+ + {% if recent_documents %} +
+ + + + + + + + + + + + {% for doc in recent_documents %} + + + + + + + + {% endfor %} + +
문서 ID처리 시간청크 수상태액션
{{ doc.id }}{{ doc.created_at }}{{ doc.chunks }} + + 완료 + + + + 보기 + +
+
+ {% else %} +
+ +

아직 처리된 문서가 없습니다.

+ 첫 문서 업로드하기 +
+ {% endif %} +
+ + +
+
+

처리 통계

+
+
+ {{ stats.total_documents }} + 총 문서 수 +
+
+ {{ stats.total_chunks }} + 총 청크 수 +
+
+ {{ stats.today_processed }} + 오늘 처리 +
+
+
+ +
+

AI 챗봇

+

문서 기반 질의응답을 시작하세요.

+
+ + +
+ 전체 채팅 화면으로 +
+
+ + +{% endblock %} + +{% block scripts %} + +{% endblock %} \ No newline at end of file diff --git a/templates/upload.html b/templates/upload.html new file mode 100644 index 0000000..5f1118b --- /dev/null +++ b/templates/upload.html @@ -0,0 +1,395 @@ +{% extends "base.html" %} + +{% block title %}파일 업로드 - AI 문서 처리 서버{% endblock %} + +{% block content %} +
+
+

+ 파일 업로드 +

+

PDF 또는 TXT 파일을 업로드하여 AI 처리를 시작하세요

+
+ +
+
+ +
+

파일 선택

+ +
+ +

파일을 드래그하거나 클릭하여 선택

+

PDF, TXT 파일 지원 (최대 200MB)

+ + +
+ + +
+ + +
+

처리 옵션

+ +
+ + + 고유한 문서 식별자를 입력하세요 +
+ +
+
+ + 읽기 쉬운 HTML 형태로 변환합니다 +
+
+ +
+
+ + 영어 문서를 한국어로 번역합니다 +
+
+ + + +
+
+ + 긴 문서를 요약하여 처리합니다 +
+
+ + +
+
+ +
+ + +
+
+ + + + + + +
+ + +{% endblock %} + +{% block scripts %} + +{% endblock %} \ No newline at end of file