File size: 5,472 Bytes
a9dc537
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Patent upload and management endpoints
"""

from fastapi import APIRouter, UploadFile, File, HTTPException
from fastapi.responses import FileResponse
from pathlib import Path
import uuid
import shutil
from datetime import datetime
from typing import List, Dict
from loguru import logger

router = APIRouter()

UPLOAD_DIR = Path("uploads/patents")
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)

@router.post("/upload", response_model=Dict)
async def upload_patent(file: UploadFile = File(...)):
    """
    Upload a patent PDF for analysis.

    Args:
        file: PDF file to upload

    Returns:
        Patent metadata including unique ID
    """
    logger.info(f"Received upload request for: {file.filename}")

    # Validate file type
    if not file.filename.endswith('.pdf'):
        raise HTTPException(
            status_code=400,
            detail="Only PDF files are supported. Please upload a .pdf file."
        )

    # Validate file size (max 50MB)
    file.file.seek(0, 2)  # Seek to end
    file_size = file.file.tell()
    file.file.seek(0)  # Reset to beginning

    if file_size > 50 * 1024 * 1024:  # 50MB
        raise HTTPException(
            status_code=400,
            detail="File too large. Maximum size is 50MB."
        )

    try:
        # Generate unique ID
        patent_id = str(uuid.uuid4())

        # Save file
        file_path = UPLOAD_DIR / f"{patent_id}.pdf"
        with file_path.open("wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Store metadata in app state
        from api.main import app_state

        metadata = {
            "id": patent_id,
            "filename": file.filename,
            "path": str(file_path),
            "size": file_size,
            "uploaded_at": datetime.utcnow().isoformat(),
            "status": "uploaded",
            "workflow_id": None
        }

        app_state["patents"][patent_id] = metadata

        logger.success(f"✅ Patent uploaded: {patent_id} ({file.filename})")

        return {
            "patent_id": patent_id,
            "filename": file.filename,
            "size": file_size,
            "uploaded_at": metadata["uploaded_at"],
            "message": "Patent uploaded successfully"
        }

    except Exception as e:
        logger.error(f"❌ Upload failed: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Upload failed: {str(e)}"
        )

@router.get("/{patent_id}", response_model=Dict)
async def get_patent(patent_id: str):
    """
    Get patent metadata by ID.

    Args:
        patent_id: Unique patent identifier

    Returns:
        Patent metadata
    """
    from api.main import app_state

    if patent_id not in app_state["patents"]:
        raise HTTPException(
            status_code=404,
            detail=f"Patent not found: {patent_id}"
        )

    return app_state["patents"][patent_id]

@router.get("/", response_model=List[Dict])
async def list_patents(
    status: str = None,
    limit: int = 100,
    offset: int = 0
):
    """
    List all uploaded patents.

    Args:
        status: Filter by status (uploaded, analyzing, analyzed, failed)
        limit: Maximum number of results
        offset: Pagination offset

    Returns:
        List of patent metadata
    """
    from api.main import app_state

    patents = list(app_state["patents"].values())

    # Filter by status if provided
    if status:
        patents = [p for p in patents if p["status"] == status]

    # Sort by upload time (newest first)
    patents.sort(key=lambda x: x["uploaded_at"], reverse=True)

    # Pagination
    patents = patents[offset:offset + limit]

    return patents

@router.delete("/{patent_id}")
async def delete_patent(patent_id: str):
    """
    Delete a patent and its associated files.

    Args:
        patent_id: Unique patent identifier

    Returns:
        Success message
    """
    from api.main import app_state

    if patent_id not in app_state["patents"]:
        raise HTTPException(
            status_code=404,
            detail=f"Patent not found: {patent_id}"
        )

    try:
        patent = app_state["patents"][patent_id]

        # Delete file if exists
        file_path = Path(patent["path"])
        if file_path.exists():
            file_path.unlink()

        # Remove from state
        del app_state["patents"][patent_id]

        logger.info(f"Deleted patent: {patent_id}")

        return {"message": "Patent deleted successfully"}

    except Exception as e:
        logger.error(f"Delete failed: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Delete failed: {str(e)}"
        )

@router.get("/{patent_id}/download")
async def download_patent(patent_id: str):
    """
    Download the original patent PDF.

    Args:
        patent_id: Unique patent identifier

    Returns:
        PDF file
    """
    from api.main import app_state

    if patent_id not in app_state["patents"]:
        raise HTTPException(
            status_code=404,
            detail=f"Patent not found: {patent_id}"
        )

    patent = app_state["patents"][patent_id]
    file_path = Path(patent["path"])

    if not file_path.exists():
        raise HTTPException(
            status_code=404,
            detail="Patent file not found on disk"
        )

    return FileResponse(
        path=file_path,
        media_type="application/pdf",
        filename=patent["filename"]
    )