File size: 9,534 Bytes
055c32c
 
 
 
 
 
 
 
 
 
 
0f078bd
055c32c
 
 
 
 
 
 
 
 
 
 
 
 
 
0f078bd
055c32c
 
0f078bd
055c32c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f078bd
 
 
 
055c32c
 
0f078bd
055c32c
 
0f078bd
055c32c
 
0f078bd
055c32c
 
 
371916d
 
055c32c
 
0f078bd
055c32c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f078bd
055c32c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import os
import uuid
import tempfile
from datetime import datetime
from pathlib import Path
from typing import Optional

from fastapi import FastAPI, HTTPException, File, UploadFile
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from playwright.async_api import async_playwright
from huggingface_hub import HfApi, upload_file


class HTMLRequest(BaseModel):
    html_content: str


class PDFResponse(BaseModel):
    pdf_url: str
    filename: str
    message: str
    repository_url: str


async def html_to_pdf_api(html_content: str) -> tuple[str, str]:
    """
    HTMLコンテンツをPDFに変換してHugging Faceデータセットリポジトリにアップロード
    knowledge.txtのPlaywright手法を使用(Async版)
    """
    try:
        # 環境変数からリポジトリ情報を取得
        hf_repo_id = os.getenv("HF_DATASET_REPO_ID")
        hf_token = os.getenv("HF_TOKEN")
        
        if not hf_repo_id:
            raise HTTPException(status_code=500, detail="HF_DATASET_REPO_ID環境変数が設定されていません")
        if not hf_token:
            raise HTTPException(status_code=500, detail="HF_TOKEN環境変数が設定されていません")
        
        # 一意のファイル名を生成
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        unique_id = str(uuid.uuid4())[:8]
        filename = f"document_{timestamp}_{unique_id}.pdf"
        
        # 一時ファイルでPDFを生成
        with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_file:
            temp_path = temp_file.name
            
            # Playwrightでヘッドレスブラウザを起動(Async版)
            async with async_playwright() as pw:
                browser = await pw.chromium.launch(headless=True)
                page = await browser.new_page()
                
                # HTMLコンテンツを設定(外部リソース読み込み待機)
                await page.set_content(html_content, wait_until="networkidle")
                
                # 印刷メディアを有効にする
                await page.emulate_media(media="print")
                
                # PDFを生成(test.htmlの設定に準拠)
                await page.pdf(
                    path=temp_path,
                    format="A4",
                    print_background=True,
                    margin={"top":"15mm","bottom":"15mm","left":"15mm","right":"15mm"},
                    scale=0.9  # 90%に縮小してA4 2ページに収める
                )
                
                await browser.close()
            
            # Hugging Face リポジトリにアップロード
            api = HfApi(token=hf_token)
            
            upload_file(
                path_or_fileobj=temp_path,
                path_in_repo=f"pdfs/{filename}",
                repo_id=hf_repo_id,
                repo_type="dataset",
                token=hf_token,
                commit_message=f"Add PDF: {filename}"
            )
            
            # 一時ファイルを削除
            os.unlink(temp_path)
            
            # ダウンロードURLを生成
            pdf_url = f"https://huggingface.co/datasets/{hf_repo_id}/resolve/main/pdfs/{filename}"
            
            return filename, pdf_url
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"PDF生成中にエラーが発生しました: {str(e)}")


# FastAPIアプリケーションの初期化
app = FastAPI(
    title="HTML to PDF Converter API",
    description="日本語対応のHTML→PDF変換API。複雑なレイアウトやWebフォントを含むHTMLコンテンツを、正確にA4サイズのPDFに変換します。",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# CORS設定
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root():
    """
    API情報を返すルートエンドポイント
    """
    hf_repo_id = os.getenv("HF_DATASET_REPO_ID", "未設定")
    return {
        "message": "HTML to PDF Converter API",
        "description": "HTMLコンテンツをA4サイズのPDFに変換し、Hugging Faceデータセットリポジトリに保存するAPI",
        "version": "1.0.0",
        "storage": f"Hugging Face Dataset Repository: {hf_repo_id}",
        "endpoints": {
            "convert": "/convert - HTMLをPDFに変換してHFリポジトリに保存",
            "files": "/files - HFリポジトリ内のPDFファイル一覧",
            "docs": "/docs - API仕様書",
            "health": "/health - ヘルスチェック"
        }
    }


@app.post("/convert", response_model=PDFResponse)
async def convert_html_to_pdf(request: HTMLRequest):
    """
    HTMLコンテンツをPDFに変換してHugging Faceデータセットリポジトリに保存するエンドポイント
    
    - **html_content**: 変換するHTMLコンテンツ
    
    Returns:
    - **pdf_url**: 生成されたPDFのダウンロードURL(Hugging Face上)
    - **filename**: PDFファイル名
    - **message**: 処理結果メッセージ
    - **repository_url**: リポジトリURL
    """
    if not request.html_content or not request.html_content.strip():
        raise HTTPException(status_code=400, detail="HTMLコンテンツが空です")
    
    try:
        filename, pdf_url = await html_to_pdf_api(request.html_content)
        hf_repo_id = os.getenv("HF_DATASET_REPO_ID")
        repository_url = f"https://huggingface.co/datasets/{hf_repo_id}"
        
        return PDFResponse(
            pdf_url=pdf_url,
            filename=filename,
            message=f"✅ PDFが正常に生成され、Hugging Faceリポジトリに保存されました: {filename}",
            repository_url=repository_url
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"処理中にエラーが発生しました: {str(e)}")


@app.get("/download/{filename}")
async def download_pdf(filename: str):
    """
    Hugging FaceリポジトリのPDFファイルへリダイレクトするエンドポイント
    
    - **filename**: ダウンロードするPDFファイル名
    """
    hf_repo_id = os.getenv("HF_DATASET_REPO_ID")
    if not hf_repo_id:
        raise HTTPException(status_code=500, detail="HF_DATASET_REPO_ID環境変数が設定されていません")
    
    # Hugging Face上のファイルURLにリダイレクト
    pdf_url = f"https://huggingface.co/datasets/{hf_repo_id}/resolve/main/pdfs/{filename}"
    return RedirectResponse(url=pdf_url)


@app.get("/health")
async def health_check():
    """
    ヘルスチェックエンドポイント
    """
    return {"status": "healthy", "timestamp": datetime.now().isoformat()}


@app.get("/files")
async def list_files():
    """
    Hugging Faceリポジトリ内のPDFファイル一覧を取得するエンドポイント
    """
    try:
        hf_repo_id = os.getenv("HF_DATASET_REPO_ID")
        hf_token = os.getenv("HF_TOKEN")
        
        if not hf_repo_id:
            raise HTTPException(status_code=500, detail="HF_DATASET_REPO_ID環境変数が設定されていません")
        if not hf_token:
            raise HTTPException(status_code=500, detail="HF_TOKEN環境変数が設定されていません")
        
        api = HfApi(token=hf_token)
        
        # リポジトリ内のファイル一覧を取得
        try:
            repo_files = api.list_repo_files(repo_id=hf_repo_id, repo_type="dataset")
            pdf_files = [f for f in repo_files if f.startswith("pdfs/") and f.endswith(".pdf")]
            
            files = []
            for file_path in pdf_files:
                filename = Path(file_path).name
                file_info = api.get_paths_info(repo_id=hf_repo_id, paths=[file_path], repo_type="dataset")[0]
                
                files.append({
                    "filename": filename,
                    "path": file_path,
                    "size": file_info.size if hasattr(file_info, 'size') else 0,
                    "last_modified": file_info.last_commit.date.isoformat() if hasattr(file_info, 'last_commit') and file_info.last_commit else None,
                    "download_url": f"https://huggingface.co/datasets/{hf_repo_id}/resolve/main/{file_path}",
                    "api_download_url": f"/download/{filename}"
                })
            
            return {
                "repository": hf_repo_id,
                "total_files": len(files),
                "files": files
            }
            
        except Exception as e:
            # リポジトリが空の場合やpdfsフォルダが存在しない場合
            return {
                "repository": hf_repo_id,
                "total_files": 0,
                "files": [],
                "note": "No PDF files found or repository is empty"
            }
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"ファイル一覧取得中にエラーが発生しました: {str(e)}")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)