Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
brittnylapierre committed Nov 6, 2024
1 parent 65b2c78 commit 6736aa5
Showing 1 changed file with 128 additions and 113 deletions.
241 changes: 128 additions & 113 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import couchdb
from PIL import Image
from fastapi import FastAPI, HTTPException, Request, Response, Depends, Security, File
from fastapi.responses import RedirectResponse, StreamingResponse
from fastapi.responses import RedirectResponse, StreamingResponse, JSONResponse
from fastapi.security import APIKeyCookie
from fastapi_sso.sso.microsoft import MicrosoftSSO
from fastapi_sso.sso.base import OpenID
Expand Down Expand Up @@ -119,6 +119,78 @@ def get_file_from_swift(swift_filename, container):
except:
return None, None

# Helper function to process each file or URL
def process_file_or_url(file_or_url, is_url, manifest_noid):
if is_url:
response = requests.get(file_or_url)
if response.status_code != 200:
print("Failed to retrieve the image")
raise ValueError("Could not get file from URL")
source_file = io.BytesIO(response.content)
else:
source_file = io.BytesIO(file_or_url)

canvas_noid = mint_noid("canvas")
encoded_canvas_noid = canvas_noid.replace("/", "%2F")
swift_filename = f"{canvas_noid}.jpg"
local_filename = f"{encoded_canvas_noid}.jpg"

# Convert the image
convert_info = convert_image(source_file, local_filename)

# Save image to swift storage
swift_md5 = save_image_to_swift(local_filename, swift_filename, "access-files")
if swift_md5:
save_canvas(canvas_noid, encoded_canvas_noid, convert_info['width'], convert_info['height'], convert_info['size'], swift_md5)

# Prepare the canvas data to return
return {
"id": f"{presentation_api_url}/canvas/{canvas_noid}",
"width": convert_info["width"],
"height": convert_info["height"],
"thumbnail": [{
"id": f"{image_api_url}/iiif/2/{encoded_canvas_noid}/full/max/0/default.jpg",
"type": "Image",
"format": "image/jpeg"
}],
"items": [{
"id": f"{presentation_api_url}/{manifest_noid}/annotationpage/{canvas_noid}/main",
"type": "AnnotationPage",
"items": [{
"id": f"{presentation_api_url}/{manifest_noid}/annotation/{canvas_noid}/main/image",
"body": {
"id": f"{image_api_url}/iiif/2/{encoded_canvas_noid}/full/max/0/default.jpg",
"type": "Image",
"width": convert_info["width"],
"height": convert_info["height"],
"format": "image/jpeg",
"service": [{
"id": f"{image_api_url}/iiif/2/{encoded_canvas_noid}",
"type": "ImageService2",
"profile": "level2"
}]
},
"type": "Annotation",
"target": f"{presentation_api_url}/canvas/{canvas_noid}",
"motivation": "painting"
}]
}],
"seeAlso": [{
"id": f"{crkn_digirati_editor_api_url}/ocr/{canvas_noid}",
"type": "Dataset",
"label": {"en": ["Optical Character Recognition text in XML"]},
"format": "text/xml",
"profile": "http://www.loc.gov/standards/alto"
}],
"rendering": [{
"id": f"{crkn_digirati_editor_api_url}/pdf/{canvas_noid}",
"type": "Text",
"label": {"en": ["PDF version"]},
"format": "application/pdf"
}],
}
return None

# Microsoft SSO configuration
sso = MicrosoftSSO(
client_id=AAD_CLIENT_ID,
Expand Down Expand Up @@ -213,133 +285,76 @@ async def new_id():
@app.post("/savemanifest/{prefix}/{noid}")
async def create_files(prefix, noid, request: Request, authorized: bool = Depends(verify_token)):
if not authorized:
return {
"message" : "You are not authorized to make this request."
}
data = await request.json() # This will give you a Python dictionary
# Step 2: Write the map to a JSON file
json_filename = f"{prefix}%2F{noid}.json"
with open(json_filename, 'w', encoding='utf-8') as json_file:
json.dump(data, json_file, ensure_ascii=False, indent=4)

with open(json_filename, 'rb') as file:
timeout = httpx.Timeout(3000.0, read=3000.0)
with httpx.Client(timeout=timeout) as client:
expiration = datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(days=1)
token = jwt.encode(
{"pld": "editor-api-source", "exp": expiration},
key=AAD_CLIENT_SECRET,
algorithm="HS256",
)
print(token)
if token:
print("Access token successfully acquired.")
return JSONResponse(
content={"message": "You are not authorized to make this request."},
status_code=403
)
try:
data = await request.json()
json_filename = f"{prefix}%2F{noid}.json"
with open(json_filename, 'w', encoding='utf-8') as json_file:
json.dump(data, json_file, ensure_ascii=False, indent=4)
with open(json_filename, 'rb') as file:
# Set up the HTTP client with timeout
timeout = httpx.Timeout(3000.0, read=3000.0)
with httpx.Client(timeout=timeout) as client:
# Create the JWT token
expiration = datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(days=1)
token = jwt.encode(
{"pld": "editor-api-source", "exp": expiration},
key=AAD_CLIENT_SECRET,
algorithm="HS256",
)
if not token:
raise ValueError("No access token generated.")
# Send the file to the API
url = f"https://{PRES_API_HOST}/admin/file"
headers = {
"Authorization": f"Bearer {token}"
}
file = {'file': (json_filename, file, 'application/json')}
response = client.put(url, files=file, headers=headers)
print(response.text)
headers = {"Authorization": f"Bearer {token}"}
file_data = {'file': (json_filename, file, 'application/json')}
response = client.put(url, files=file_data, headers=headers)

if response.status_code == 200:
return {"success": True, "message": response.text}
return JSONResponse(
content={"success": True, "message": "File successfully uploaded."},
status_code=200
)
else:
return {"success": False, "message": response.text}
else:
return {
"success" : False,
"message" : "No access token in the response."
}
return {
"success" : False,
"message" : f"Error sending request to API."
}
return {
"success" : False,
"message" : f"Error compiling JSON data."
}
raise ValueError(f"API Error: {response.text}")
except Exception as e:
# Catch all errors and return a generic error message
return JSONResponse(
content={"success": False, "message": f"Error: {str(e)}"},
status_code=500
)


@app.post("/uploadfiles/{prefix}/{noid}")
async def upload_files(prefix, noid, files: Annotated[List[bytes], File()], authorized: bool = Depends(verify_token)):
async def upload_files(prefix, noid, files: List[bytes] = File(...), authorized: bool = Depends(verify_token)):
if not authorized:
return {"message": "You are not authorized to make this request."}
return JSONResponse(content={"message": "You are not authorized to make this request."}, status_code=403)
manifest_noid = f"{prefix}/{noid}"
canvases = []
for file in files:
source_file = io.BytesIO(file)
canvas_noid = mint_noid("canvas")
encoded_canvas_noid = canvas_noid.replace("/", "%2F")
swift_filename = f"{canvas_noid}.jpg"
local_filename = f"{encoded_canvas_noid}.jpg"
convert_info = convert_image(source_file, local_filename)
swift_md5 = save_image_to_swift(local_filename, swift_filename, "access-files")
if swift_md5:
save_canvas(canvas_noid, encoded_canvas_noid, convert_info['width'], convert_info['height'], convert_info['size'], swift_md5)
canvases.append({
"id": f"{presentation_api_url}/canvas/{canvas_noid}",
"width": convert_info["width"],
"height": convert_info["height"],
"thumbnail": [{"id": f"{image_api_url}/iiif/2/{encoded_canvas_noid}/full/max/0/default.jpg", "type": "Image", "format": "image/jpeg"}],
"items": [{"id": f"{presentation_api_url}/{manifest_noid}/annotationpage/{canvas_noid}/main",
"type": "AnnotationPage", "items": [{"id": f"{presentation_api_url}/{manifest_noid}/annotation/{canvas_noid}/main/image",
"body": {"id": f"{image_api_url}/iiif/2/{encoded_canvas_noid}/full/max/0/default.jpg",
"type": "Image",
"width": convert_info["width"],
"height": convert_info["height"],
"format": "image/jpeg",
"service": [{"id": f"{image_api_url}/iiif/2/{encoded_canvas_noid}",
"type": "ImageService2", "profile": "level2"}]},
"type": "Annotation", "target": f"{presentation_api_url}/canvas/{canvas_noid}",
"motivation": "painting"}]}],
"seeAlso": [{"id": f"{crkn_digirati_editor_api_url}/ocr/{canvas_noid}", "type": "Dataset",
"label": {"en": ["Optical Character Recognition text in XML"]},
"format": "text/xml", "profile": "http://www.loc.gov/standards/alto"}],
"rendering": [{"id": f"{crkn_digirati_editor_api_url}/pdf/{canvas_noid}",
"type": "Text", "label": {"en": ["PDF version"]}, "format": "application/pdf"}],
})
try:
canvas_data = process_file_or_url(file, is_url=False, manifest_noid=manifest_noid)
if canvas_data:
canvases.append(canvas_data)
except ValueError as e:
return JSONResponse(content={"message": str(e)}, status_code=400)
return {"canvases": canvases}

@app.post("/createfilesfromurl/{prefix}/{noid}")
async def upload_files(prefix, noid, request: Request, authorized: bool = Depends(verify_token)):
async def create_files_from_url(prefix, noid, request: Request, authorized: bool = Depends(verify_token)):
if not authorized:
return {"message": "You are not authorized to make this request."}
return JSONResponse(content={"message": "You are not authorized to make this request."}, status_code=403)
manifest_noid = f"{prefix}/{noid}"
data = await request.json() # This will give you a Python dictionary
canvases = []
for url in data['urls']:
canvas_noid = mint_noid("canvas")
encoded_canvas_noid = canvas_noid.replace("/", "%2F")
swift_filename = f"{canvas_noid}.jpg"
local_filename = f"{encoded_canvas_noid}.jpg"
response = requests.get(url)
if response.status_code != 200:
print("Failed to retrieve the image")
return {"message": "Could not get file"}
source_file = io.BytesIO((response.content))
convert_info = convert_image(source_file, local_filename)
swift_md5 = save_image_to_swift(local_filename, swift_filename, "access-files")
if swift_md5:
save_canvas(canvas_noid, encoded_canvas_noid, convert_info['width'], convert_info['height'], convert_info['size'], swift_md5)
canvases.append({
"id": f"{presentation_api_url}/canvas/{canvas_noid}",
"width": convert_info["width"],
"height": convert_info["height"],
"thumbnail": [{"id": f"{image_api_url}/iiif/2/{encoded_canvas_noid}/full/max/0/default.jpg", "type": "Image", "format": "image/jpeg"}],
"items": [{"id": f"{presentation_api_url}/{manifest_noid}/annotationpage/{canvas_noid}/main",
"type": "AnnotationPage", "items": [{"id": f"{presentation_api_url}/{manifest_noid}/annotation/{canvas_noid}/main/image",
"body": {"id": f"{image_api_url}/iiif/2/{encoded_canvas_noid}/full/max/0/default.jpg",
"type": "Image",
"width": convert_info["width"],
"height": convert_info["height"],
"format": "image/jpeg",
"service": [{"id": f"{image_api_url}/iiif/2/{encoded_canvas_noid}",
"type": "ImageService2", "profile": "level2"}]},
"type": "Annotation", "target": f"{presentation_api_url}/canvas/{canvas_noid}",
"motivation": "painting"}]}],
"seeAlso": [{"id": f"{crkn_digirati_editor_api_url}/ocr/{canvas_noid}", "type": "Dataset",
"label": {"en": ["Optical Character Recognition text in XML"]},
"format": "text/xml", "profile": "http://www.loc.gov/standards/alto"}],
"rendering": [{"id": f"{crkn_digirati_editor_api_url}/pdf/{canvas_noid}",
"type": "Text", "label": {"en": ["PDF version"]}, "format": "application/pdf"}],
})
try:
canvas_data = process_file_or_url(url, is_url=True, manifest_noid=manifest_noid)
if canvas_data:
canvases.append(canvas_data)
except ValueError as e:
return JSONResponse(content={"message": str(e)}, status_code=400)
return {"canvases": canvases}

0 comments on commit 6736aa5

Please sign in to comment.