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.
Assistant
Sure! Below is a complete implementation of a FastAPI application that provides three APIs to upload a DOCX file, submit instructions, and retrieve a drafted DOCX file with comments based on the provided instructions. This implementation uses python-docx for manipulating DOCX files and lxml for handling the XML required to insert comments.
Overview
Endpoints:
POST /upload: Uploads a DOCX file and returns a unique file_id.
POST /instructions: Submits instructions for a specific file_id. Instructions specify which paragraphs to comment on and the comment text.
GET /drafted_document/{file_id}: Processes the DOCX file based on the instructions and returns the modified DOCX with comments.
Storage:
For simplicity, the uploaded files and instructions are stored in in-memory dictionaries. In a production environment, consider using persistent storage like a database or cloud storage.
Adding Comments:
DOCX comments are added by manipulating the underlying XML. This involves:
Adding a new comment to the comments.xml part of the DOCX.
Inserting commentRangeStart, commentRangeEnd, and commentReference elements around the target text in the paragraph.
Setup
Install Dependencies
Make sure you have Python 3.7 or higher installed. Then, install the required packages:
bash
pip install fastapi uvicorn python-docx lxml
Directory Structure
Ensure your project has the following structure:
code
.
├── main.py
Code Implementation
Create a file named main.py and add the following code:
python
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from uuid import uuid4
from typing import List, Dict
from io import BytesIO
from docx import Document
from docx.opc.constants import RELATIONSHIP_TYPE as RT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
import zipfile
import shutil
import tempfile
from lxml import etree
app = FastAPI()
# In-memory storage for uploaded files and instructions
uploaded_files: Dict[str, bytes] = {}
instructions_store: Dict[str, List[Dict]] = {}
class Instruction(BaseModel):
paragraph_number: int # 1-based index
comment_text: str
class Instructions(BaseModel):
file_id: str
instructions: List[Instruction]
def add_comments_to_docx(docx_bytes: bytes, instructions: List[Instruction]) -> bytes:
"""
Adds comments to the DOCX file based on the instructions.
Each instruction specifies a paragraph number and the comment text.
"""
with tempfile.TemporaryDirectory() as tmpdirname:
# Save the original docx bytes to a temporary file
original_docx_path = f"{tmpdirname}/original.docx"
with open(original_docx_path, "wb") as f:
f.write(docx_bytes)
# Open the zipfile
with zipfile.ZipFile(original_docx_path, 'r') as zin:
zin.extractall(tmpdirname)
# Parse comments.xml or create it if it doesn't exist
comments_path = f"{tmpdirname}/word/comments.xml"
if not zipfile.Path(original_docx_path, 'word/comments.xml').exists:
# Create a basic comments.xml structure
comments_xml = etree.Element('w:comments', nsmap={
'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
})
etree.SubElement(comments_xml, 'w:comment', {
'w:id': '0',
'w:author': 'Automated System',
'w:date': '2023-01-01T00:00:00Z'
})
tree = etree.ElementTree(comments_xml)
tree.write(comments_path, xml_declaration=True, encoding='UTF-8', standalone="yes")
# Parse existing comments.xml
parser = etree.XMLParser(ns_clean=True, recover=True)
tree = etree.parse(comments_path, parser)
root = tree.getroot()
# Find the next available comment id
existing_ids = [int(comment.get('w:id')) for comment in root.findall('w:comment', namespaces=root.nsmap)]
next_id = max(existing_ids, default=-1) + 1
# Load the document.xml
document_path = f"{tmpdirname}/word/document.xml"
doc_tree = etree.parse(document_path, parser)
doc_root = doc_tree.getroot()
# Namespace map
ns = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
for instr in instructions:
para_num = instr.paragraph_number
comment_text = instr.comment_text
# Find the paragraph (1-based index)
paragraphs = doc_root.findall('.//w:p', namespaces=ns)
if para_num < 1 or para_num > len(paragraphs):
continue # Skip invalid paragraph numbers
para = paragraphs[para_num - 1]
# Add commentRangeStart
comment_range_start = etree.Element(qn('w:commentRangeStart'))
comment_range_start.set(qn('w:id'), str(next_id))
para.insert(0, comment_range_start)
# Add commentRangeEnd
comment_range_end = etree.Element(qn('w:commentRangeEnd'))
comment_range_end.set(qn('w:id'), str(next_id))
para.append(comment_range_end)
# Add commentReference
run = etree.SubElement(para, qn('w:r'))
comment_ref = etree.SubElement(run, qn('w:commentReference'))
comment_ref.set(qn('w:id'), str(next_id))
# Add the actual comment
comment = etree.SubElement(root, 'w:comment', {
'w:id': str(next_id),
'w:author': 'Automated System',
'w:date': '2023-01-01T00:00:00Z'
})
# Add the comment text
comment_text_elem = etree.SubElement(comment, 'w:p')
comment_run = etree.SubElement(comment_text_elem, 'w:r')
comment_text_node = etree.SubElement(comment_run, 'w:t')
comment_text_node.text = comment_text
next_id += 1
# Write back the modified comments.xml
tree.write(comments_path, xml_declaration=True, encoding='UTF-8', standalone="yes")
# Write back the modified document.xml
doc_tree.write(document_path, xml_declaration=True, encoding='UTF-8', standalone="yes")
# Create a new zipfile with the modified contents
drafted_docx_path = f"{tmpdirname}/drafted.docx"
with zipfile.ZipFile(drafted_docx_path, 'w', zipfile.ZIP_DEFLATED) as zout:
for foldername, subfolders, filenames in os.walk(tmpdirname):
for filename in filenames:
filepath = os.path.join(foldername, filename)
relative_path = os.path.relpath(filepath, tmpdirname)
zout.write(filepath, relative_path)
# Read the drafted docx bytes
with open(drafted_docx_path, "rb") as f:
drafted_bytes = f.read()
return drafted_bytes
import os
@app.post("/upload")
async def upload_docx(file: UploadFile = File(...)):
if file.content_type != 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
raise HTTPException(status_code=400, detail="Invalid file type. Please upload a DOCX file.")
contents = await file.read()
file_id = str(uuid4())
uploaded_files[file_id] = contents
return {"file_id": file_id}
@app.post("/instructions")
def submit_instructions(instructions: Instructions):
file_id = instructions.file_id
if file_id not in uploaded_files:
raise HTTPException(status_code=404, detail="File ID not found.")
instructions_store[file_id] = [instr.dict() for instr in instructions.instructions]
return {"message": "Instructions received."}
@app.get("/drafted_document/{file_id}")
def get_drafted_document(file_id: str):
if file_id not in uploaded_files:
raise HTTPException(status_code=404, detail="File ID not found.")
if file_id not in instructions_store:
raise HTTPException(status_code=400, detail="No instructions found for this file.")
original_docx = uploaded_files[file_id]
instructions = instructions_store[file_id]
try:
drafted_docx = add_comments_to_docx(original_docx, instructions)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing document: {str(e)}")
return StreamingResponse(
BytesIO(drafted_docx),
media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document',
headers={
'Content-Disposition': f'attachment; filename="drafted_{file_id}.docx"'
}
)
Explanation
Data Models:
Instruction: Represents a single instruction containing the paragraph_number (1-based index) and the comment_text.
Instructions: Contains the file_id and a list of Instruction objects.
Endpoints:
/upload:
Accepts a DOCX file upload.
Validates the file type.
Stores the file in the uploaded_files dictionary with a unique file_id.
Returns the file_id to the user.
/instructions:
Accepts a JSON payload containing the file_id and a list of instructions.
Validates that the file_id exists.
Stores the instructions in the instructions_store dictionary.
Returns a confirmation message.
/drafted_document/{file_id}:
Accepts a file_id as a path parameter.
Validates that the file_id exists and that instructions have been provided.
Calls the add_comments_to_docx function to process the DOCX and add comments.
Returns the modified DOCX as a downloadable file.
Adding Comments (add_comments_to_docx function):
Extraction & Setup:
Extracts the contents of the uploaded DOCX file into a temporary directory.
Parses or creates the comments.xml file where comments are stored.
Processing Instructions:
Iterates over each instruction, identifying the target paragraph by its number.
Inserts commentRangeStart, commentRangeEnd, and commentReference elements around the paragraph to denote the comment's location.
Adds the actual comment text to the comments.xml file with a unique comment ID.
Repacking:
Writes the modified and back into the temporary directory.
Running the Application
Run the application using Uvicorn:
bash
uvicorn main:app --reload
This will start the server on http://127.0.0.1:8000.
Replace "your-unique-file-id" with the actual file_id received from the upload step.
bash
curl -X POST "http://127.0.0.1:8000/instructions" \
-H "Content-Type: application/json" \
-d '{
"file_id": "your-unique-file-id",
"instructions": [
{ "paragraph_number": 2, "comment_text": "Check the data accuracy." },
{ "paragraph_number": 5, "comment_text": "Consider rephrasing this sentence." }
]
}'
Response:
json
{
"message": "Instructions received."
}
Retrieve the Drafted Document with Comments:
bash
curl -X GET "http://127.0.0.1:8000/drafted_document/your-unique-file-id" --output drafted_document.docx
This will download the modified DOCX file with the specified comments.
Notes
Thread Safety & Scalability: The current implementation uses in-memory dictionaries to store files and instructions. This approach is suitable for demonstration purposes but not for production. For a scalable application, consider using persistent storage solutions.
Comment Positioning: This implementation adds comments to entire paragraphs. If you need to add comments to specific lines or runs within a paragraph, further enhancements to the add_comments_to_docx function are required.
Security: Always ensure that file uploads are handled securely to prevent vulnerabilities such as arbitrary file execution or storage issues.
Error Handling: The implementation includes basic error handling. Depending on your use case, you might want to expand on this to handle more edge cases and provide more detailed feedback.
I hope this helps! Let me know if you have any questions or need further assistance.
Not yet included in a published release.
comments.xml
document.xml
Repackages the directory into a new DOCX file.
Returns the bytes of the modified DOCX.
Error Handling:
The API includes error handling for invalid file types, missing file_id, missing instructions, and processing errors.