office-helper-api Fastapi w python będę potrzebował ciebie do pomocy przy tworzeniu…
- User
office-helper-api Fastapi w python
będę potrzebował ciebie do pomocy przy tworzeniu takiego api
posiadam już projekt i plik dockerfile
struktura projektu: api-office-helper/ │ ├── app/ │ ├── routes/ # Endpointy API │ │ ├── convert.py # Konwersje plików │ │ ├── pdf.py # Operacje na PDF │ │ ├── extract.py # Ekstrakcje z prezentacji │ │ └── init.py │ │ │ ├── services/ # Logika przetwarzania plików │ │ ├── convert_service.py │ │ ├── pdf_service.py │ │ ├── extract_service.py │ │ └── utils.py │ │ │ ├── main.py # Główny plik aplikacji FastAPI │ └── init.py │ ├── requirements.txt # Lista zależności Pythona
🚀 Funkcjonalności
📄 Konwersja plików
.docx→.pdf.xlsx→.pdf.pptx→.pdf.pptx→ obrazy (.png,.jpg).pptx→ Word / PDF (z tekstami i obrazami).pdf→.docx
🔐 Operacje na PDF
- Szyfrowanie PDF (hasłem)
- Odszyfrowywanie PDF
- Scalanie PDF-ów
- Rozdzielanie PDF na strony
- Dodawanie znaków wodnych
🖼️ Ekstrakcja zawartości
- Teksty i obrazy z prezentacji
.pptx - Teksty z prezentacji
.pptx - Obrazy z prezentacji
.pptx
📦 Obsługa wielu plików
- Wysyłka wielu plików przez
multipart/form-data - Obsługa archiwów
.zipjako wejście/wyjście
zacznijmy od stworzenia pliku main oraz plików route wraz z service ale pliki route i service na razie bez zawartosci tylko miejsca na uzupełnienie środków funkcji
na początku odpwoeidzi napisz mi jakieś wskazówki i rady
Assistant
Świetnie! Pomogę Ci stworzyć API do obsługi plików biurowych. Oto kilka wskazówek i rad przed rozpoczęciem:
🎯 Wskazówki i rady
1. Struktura i organizacja
- Trzymaj się zasady pojedynczej odpowiedzialności - każdy serwis powinien odpowiadać za jedną domenę
- Używaj dependency injection w FastAPI dla lepszej testowalności
- Rozważ dodanie warstwy modeli (Pydantic) dla walidacji danych wejściowych/wyjściowych
2. Obsługa plików
- Zawsze waliduj typy plików przed przetwarzaniem
- Ustaw limity rozmiaru plików w konfiguracji
- Używaj kontekstów (
withstatements) do obsługi plików - Rozważ użycie tymczasowych katalogów dla przetwarzania
3. Bezpieczeństwo
- Skanuj przesyłane pliki pod kątem zagrożeń
- Nie przechowuj plików dłużej niż to konieczne
- Używaj UUID dla nazw plików tymczasowych
4. Performance
- Rozważ użycie background tasks dla długotrwałych operacji
- Implementuj cache dla często używanych konwersji
- Używaj streaming response dla dużych plików
5. Error handling
- Stwórz własne klasy wyjątków
- Używaj middleware do globalnej obsługi błędów
- Loguj błędy z odpowiednim poziomem szczegółowości
Teraz przejdźmy do kodu:
📁 app/main.py
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from contextlib import asynccontextmanager import logging # Import routes from app.routes import convert, pdf, extract # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) @asynccontextmanager async def lifespan(app: FastAPI): # Startup logger.info("Starting Office Helper API...") yield # Shutdown logger.info("Shutting down Office Helper API...") # Create FastAPI instance app = FastAPI( title="Office Helper API", description="API for office file conversions and operations", version="1.0.0", lifespan=lifespan ) # Configure CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], # W produkcji ustaw konkretne domeny allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include routers app.include_router(convert.router, prefix="/api/v1/convert", tags=["convert"]) app.include_router(pdf.router, prefix="/api/v1/pdf", tags=["pdf"]) app.include_router(extract.router, prefix="/api/v1/extract", tags=["extract"]) @app.get("/") async def root(): return { "message": "Welcome to Office Helper API", "version": "1.0.0", "docs": "/docs" } @app.get("/health") async def health_check(): return {"status": "healthy"}📁 app/routes/convert.py
from fastapi import APIRouter, UploadFile, File, HTTPException from typing import List from fastapi.responses import FileResponse, StreamingResponse import logging from app.services import convert_service router = APIRouter() logger = logging.getLogger(__name__) @router.post("/docx-to-pdf") async def convert_docx_to_pdf(file: UploadFile = File(...)): """Convert DOCX file to PDF""" # TODO: Implement conversion logic pass @router.post("/xlsx-to-pdf") async def convert_xlsx_to_pdf(file: UploadFile = File(...)): """Convert XLSX file to PDF""" # TODO: Implement conversion logic pass @router.post("/pptx-to-pdf") async def convert_pptx_to_pdf(file: UploadFile = File(...)): """Convert PPTX file to PDF""" # TODO: Implement conversion logic pass @router.post("/pptx-to-images") async def convert_pptx_to_images( file: UploadFile = File(...), image_format: str = "png" ): """Convert PPTX file to images (PNG/JPG)""" # TODO: Implement conversion logic pass @router.post("/pptx-to-word") async def convert_pptx_to_word(file: UploadFile = File(...)): """Convert PPTX to Word document with texts and images""" # TODO: Implement conversion logic pass @router.post("/pdf-to-docx") async def convert_pdf_to_docx(file: UploadFile = File(...)): """Convert PDF file to DOCX""" # TODO: Implement conversion logic pass @router.post("/batch-convert") async def batch_convert( files: List[UploadFile] = File(...), target_format: str = "pdf" ): """Convert multiple files to specified format""" # TODO: Implement batch conversion logic pass📁 app/routes/pdf.py
from fastapi import APIRouter, UploadFile, File, HTTPException, Form from typing import List, Optional from fastapi.responses import FileResponse, StreamingResponse import logging from app.services import pdf_service router = APIRouter() logger = logging.getLogger(__name__) @router.post("/encrypt") async def encrypt_pdf( file: UploadFile = File(...), password: str = Form(...) ): """Encrypt PDF file with password""" # TODO: Implement encryption logic pass @router.post("/decrypt") async def decrypt_pdf( file: UploadFile = File(...), password: str = Form(...) ): """Decrypt password-protected PDF file""" # TODO: Implement decryption logic pass @router.post("/merge") async def merge_pdfs(files: List[UploadFile] = File(...)): """Merge multiple PDF files into one""" # TODO: Implement merge logic pass @router.post("/split") async def split_pdf( file: UploadFile = File(...), pages: Optional[str] = Form(None) ): """Split PDF into individual pages or specified ranges""" # TODO: Implement split logic pass @router.post("/watermark") async def add_watermark( file: UploadFile = File(...), watermark_text: Optional[str] = Form(None), watermark_image: Optional[UploadFile] = File(None) ): """Add text or image watermark to PDF""" # TODO: Implement watermark logic pass @router.post("/compress") async def compress_pdf(file: UploadFile = File(...)): """Compress PDF file to reduce size""" # TODO: Implement compression logic pass📁 app/routes/extract.py
from fastapi import APIRouter, UploadFile, File, HTTPException, Query from typing import Optional from fastapi.responses import JSONResponse, StreamingResponse import logging from app.services import extract_service router = APIRouter() logger = logging.getLogger(__name__) @router.post("/pptx-content") async def extract_pptx_content( file: UploadFile = File(...), include_text: bool = Query(True), include_images: bool = Query(True) ): """Extract text and/or images from PPTX presentation""" # TODO: Implement extraction logic pass @router.post("/pptx-text") async def extract_pptx_text(file: UploadFile = File(...)): """Extract only text from PPTX presentation""" # TODO: Implement text extraction logic pass @router.post("/pptx-images") async def extract_pptx_images( file: UploadFile = File(...), image_format: str = Query("png", regex="^(png|jpg|jpeg)$") ): """Extract only images from PPTX presentation""" # TODO: Implement image extraction logic pass @router.post("/pdf-text") async def extract_pdf_text(file: UploadFile = File(...)): """Extract text from PDF file""" # TODO: Implement PDF text extraction logic pass @router.post("/pdf-images") async def extract_pdf_images(file: UploadFile = File(...)): """Extract images from PDF file""" # TODO: Implement PDF image extraction logic pass📁 app/services/convert_service.py
import logging from pathlib import Path from typing import Optional, List import tempfile import uuid logger = logging.getLogger(__name__) async def convert_docx_to_pdf(file_path: Path) -> Path: """Convert DOCX file to PDF""" # TODO: Implement using python-docx and reportlab or LibreOffice pass async def convert_xlsx_to_pdf(file_path: Path) -> Path: """Convert XLSX file to PDF""" # TODO: Implement using openpyxl and reportlab or LibreOffice pass async def convert_pptx_to_pdf(file_path: Path) -> Path: """Convert PPTX file to PDF""" # TODO: Implement using python-pptx and reportlab or LibreOffice pass async def convert_pptx_to_images( file_path: Path, image_format: str = "png" ) -> List[Path]: """Convert PPTX slides to images""" # TODO: Implement using python-pptx and Pillow pass async def convert_pptx_to_word(file_path: Path) -> Path: """Convert PPTX to Word document""" # TODO: Implement using python-pptx and python-docx pass async def convert_pdf_to_docx(file_path: Path) -> Path: """Convert PDF to DOCX""" # TODO: Implement using pdf2docx or similar library pass async def batch_convert_files( file_paths: List[Path], target_format: str ) -> List[Path]: """Convert multiple files to target format""" # TODO: Implement batch processing pass📁 app/services/pdf_service.py
import logging from pathlib import Path from typing import Optional, List import tempfile logger = logging.getLogger(__name__) async def encrypt_pdf(file_path: Path, password: str) -> Path: """Encrypt PDF with password""" # TODO: Implement using PyPDF2 or pikepdf pass async def decrypt_pdf(file_path: Path, password: str) -> Path: """Decrypt password-protected PDF""" # TODO: Implement using PyPDF2 or pikepdf pass async def merge_pdf_files(file_paths: List[Path]) -> Path: """Merge multiple PDFs into one""" # TODO: Implement using PyPDF2 or pikepdf pass async def split_pdf( file_path: Path, pages: Optional[str] = None ) -> List[Path]: """Split PDF into individual pages or ranges""" # TODO: Implement using PyPDF2 or pikepdf pass async def add_watermark_to_pdf( file_path: Path, watermark_text: Optional[str] = None, watermark_image_path: Optional[Path] = None ) -> Path: """Add watermark to PDF""" # TODO: Implement using PyPDF2 or reportlab pass async def compress_pdf(file_path: Path) -> Path: """Compress PDF to reduce file size""" # TODO: Implement using PyPDF2 or ghostscript pass📁 app/services/extract_service.py
import logging from pathlib import Path from typing import Dict, List, Tuple import tempfile logger = logging.getLogger(__name__) async def extract_pptx_content( file_path: Path, include_text: bool = True, include_images: bool = True ) -> Dict: """Extract text and/or images from PPTX""" # TODO: Implement using python-pptx pass async def extract_pptx_text(file_path: Path) -> List[Dict]: """Extract only text from PPTX slides""" # TODO: Implement using python-pptx pass async def extract_pptx_images( file_path: Path, image_format: str = "png" ) -> List[Path]: """Extract images from PPTX""" # TODO: Implement using python-pptx pass async def extract_pdf_text(file_path: Path) -> str: """Extract text from PDF""" # TODO: Implement using PyPDF2 or pdfplumber pass async def extract_pdf_images(file_path: Path) -> List[Path]: """Extract images from PDF""" # TODO: Implement using PyPDF2 or pdf2image pass📁 app/services/utils.py
import logging from pathlib import Path from typing import Optional import tempfile import uuid import zipfile import os logger = logging.getLogger(__name__) def validate_file_type(filename: str, allowed_extensions: List[str]) -> bool: """Validate if file has allowed extension""" # TODO: Implement file validation pass def create_temp_file(suffix: str = "") -> Path: """Create temporary file with unique name""" # TODO: Implement temp file creation pass def create_temp_directory() -> Path: """Create temporary directory""" # TODO: Implement temp directory creation pass def cleanup_temp_files(paths: List[Path]) -> None: """Clean up temporary files""" # TODO: Implement cleanup logic pass def create_zip_archive(files: List[Path], output_name: str) -> Path: """Create ZIP archive from files""" # TODO: Implement ZIP creation pass def extract_zip_archive(zip_path: Path) -> List[Path]: """Extract files from ZIP archive""" # TODO: Implement ZIP extraction passTo podstawowa struktura Twojego API. Każdy plik ma przygotowane miejsca na implementację konkretnych funkcjonalności. Możesz teraz stopniowo implementować poszczególne funkcje, zaczynając od najprostszych.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.