Give me code with 3 APIs where I upload a docx file and then in second API the user will provide instructions and in third API it should return us drafted document. In the output docx file there should be comments in the documents on some lines in the document based on the instructions provided in the second API. And I want code with rest APIs.
Assistant
Certainly! Below is a complete example of a RESTful API service built using Python's FastAPI framework. This service includes three endpoints:
Upload DOCX File API (/upload): Allows users to upload a .docx file.
Provide Instructions API (/instructions/{file_id}): Users can provide instructions related to the uploaded document.
Generate Draft Document API (/draft/{file_id}): Returns a modified .docx file with comments based on the provided instructions.
Prerequisites
Python 3.7+: Ensure you have Python installed.
Required Python Packages: Install the necessary packages using pip:
Note: As of my knowledge cutoff in September 2021, the python-docx library does not support adding comments directly. However, the python-docx-comments library (a hypothetical extension) is assumed here for demonstration purposes. If such a library does not exist, you might need to handle XML manipulation directly or use a different library that supports comments.
Directory Structure
For simplicity, the files will be stored in a temporary directory. Ensure that the server has write permissions to this directory.
code
.
├── main.py
└── storage
Complete Code (main.py)
python
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import Dict
from uuid import uuid4
from pathlib import Path
from docx import Document
# from docx_comments import add_comment # Hypothetical library
import shutil
import os
app = FastAPI(title="DOCX Comment API")
# In-memory stores (for demonstration; use persistent storage in production)
uploaded_files: Dict[str, Path] = {}
instructions_store: Dict[str, list] = {}
# Directory to store uploaded and processed files
STORAGE_DIR = Path("./storage")
STORAGE_DIR.mkdir(exist_ok=True)
class Instruction(BaseModel):
paragraph_number: int
comment: str
@app.post("/upload")
async def upload_docx(file: UploadFile = File(...)):
"""Endpoint to upload a .docx file."""
if not file.filename.endswith(".docx"):
raise HTTPException(status_code=400, detail="File must be a .docx document")
file_id = str(uuid4())
file_path = STORAGE_DIR / f"{file_id}.docx"
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
uploaded_files[file_id] = file_path
instructions_store[file_id] = []
return {"file_id": file_id, "filename": file.filename}
@app.post("/instructions/{file_id}")
async def add_instructions(file_id: str, instruction: Instruction):
"""Endpoint to add instructions for a specific uploaded document."""
if file_id not in uploaded_files:
raise HTTPException(status_code=404, detail="File ID not found")
instructions_store[file_id].append(instruction.dict())
return {"status": "Instruction added", "instruction": instruction}
@app.get("/draft/{file_id}")
async def generate_draft(file_id: str):
"""Endpoint to generate the draft document with comments based on instructions."""
if file_id not in uploaded_files:
raise HTTPException(status_code=404, detail="File ID not found")
original_path = uploaded_files[file_id]
instructions = instructions_store.get(file_id, [])
# Load the document
try:
doc = Document(original_path)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error loading document: {e}")
# Apply comments based on instructions
for instr in instructions:
para_num = instr.get("paragraph_number")
comment_text = instr.get("comment")
if para_num < 1 or para_num > len(doc.paragraphs):
continue # Skip invalid paragraph numbers
paragraph = doc.paragraphs[para_num - 1]
# Hypothetical function to add comments
# add_comment(paragraph, comment_text)
# Since python-docx doesn't support comments, we'll simulate by adding a comment as a run
run = paragraph.add_run(f"\n[Comment: {comment_text}]")
run.italic = True
run.font.color.rgb = RGBColor(255, 0, 0) # Red color to denote comment
# Save the modified document
draft_path = STORAGE_DIR / f"{file_id}_draft.docx"
try:
doc.save(draft_path)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error saving draft document: {e}")
return FileResponse(
path=draft_path,
filename=f"draft_{original_path.name}",
media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)
Explanation of the Code
Imports:
FastAPI: For building the REST API.
python-docx: To manipulate .docx files.
uuid4: To generate unique file identifiers.
Pydantic: For request validation.
FileResponse: To send files as responses.
In-Memory Stores:
uploaded_files: Maps file_id to the file path.
instructions_store: Maps file_id to a list of instructions.
Note: In a production environment, consider using a database or persistent storage instead of in-memory dictionaries.
Upload Endpoint (/upload):
Accepts a .docx file.
Validates the file extension.
Generates a unique file_id and saves the file in the storage directory.
Initializes an empty list for instructions related to this file.
Accepts JSON data with paragraph_number and comment.
Validates the file_id.
Appends the instruction to the instructions_store.
Instruction Schema:
json
{
"paragraph_number": 2,
"comment": "This section needs more details."
}
Generate Draft Endpoint (/draft/{file_id}):
Validates the file_id.
Loads the original document using python-docx.
Iterates over the instructions and adds comments to the specified paragraphs.
Adding Comments:
Note: Since python-docx does not support adding official Word comments, this example simulates comments by appending italicized red text at the end of the specified paragraphs. For actual comment functionality, additional XML handling or a different library would be required.
Testing the API
You can test the API using tools like cURL, Postman, or via the interactive Swagger UI provided by FastAPI.
Start the Server:
bash
uvicorn main:app --reload
The API will be available at http://127.0.0.1:8000.
URL Parameter: file_id obtained from the previous step.
JSON Body:
json
{
"paragraph_number": 3,
"comment": "Please elaborate on this point."
}
cURL Example:
bash
curl -X POST "http://127.0.0.1:8000/instructions/some-unique-uuid" \
-H "Content-Type: application/json" \
-d '{"paragraph_number": 3, "comment": "Please elaborate on this point."}'
Response:
json
{
"status": "Instruction added",
"instruction": {
"paragraph_number": 3,
"comment": "Please elaborate on this point."
}
}
You can add multiple instructions by making multiple POST requests to the /instructions/{file_id} endpoint.
Generate and Download Draft Document:
Endpoint:
Handling Comments Properly
As mentioned earlier, python-docx does not support adding official Word comments (which appear in the margin). To properly add comments, you would need to manipulate the underlying XML or use another library that supports this feature. Here's a brief overview of how you might achieve this using lxml:
Understanding Word Document Structure: DOCX files are essentially ZIP archives containing XML files. Comments are stored in specific XML parts.
Using lxml to Modify XML: You can parse the document's XML, insert comment references in the main document, and add the actual comment text in the comments part.
Libraries or Tools: If handling XML directly is complex, consider using or contributing to libraries that extend python-docx to support comments.
For a production-ready solution, you might need to implement this additional functionality or use a different library that abstracts these details.
Conclusion
The above example provides a foundational REST API with three endpoints to upload a .docx file, add instructions, and generate a modified document with comments based on those instructions. While the comment-adding functionality is simulated due to library limitations, it demonstrates how to structure the APIs and handle document processing. For full comment functionality, further development or alternative libraries would be necessary.