Skip to content

Commit

Permalink
Refactor FastAPI application to correctly resolve Jinja2 templates an…
Browse files Browse the repository at this point in the history
…d static file paths. Replaced 'index.html' reference with 'upload_form.html' for the root route and consolidated path handling for static directories, templates, and model loading.

Refactor FastAPI application to correctly resolve Jinja2 templates and static file paths.
Replaced 'index.html' reference with 'upload_form.html' for the root route and consolidated
path handling for static directories, templates, and model loading.
  • Loading branch information
Solrikk committed Dec 31, 2024
1 parent b2499b1 commit 405c095
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 37 deletions.
55 changes: 23 additions & 32 deletions fastapi_app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,21 @@
from io import BytesIO
from PIL import Image, UnidentifiedImageError

app = FastAPI()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, "static")
TEMPLATES_DIR = os.path.join(BASE_DIR, "templates")
UPLOAD_FOLDER = os.path.join(BASE_DIR, "uploads")
ZIP_PATH = os.path.join(BASE_DIR, "photos.zip")
MODEL_PATH = os.path.join(BASE_DIR, "resnet50_local.h5")

model = load_model('resnet50_local.h5')
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

ZIP_PATH = 'photos.zip'
UPLOAD_FOLDER = 'uploads'
app = FastAPI()
model = load_model(MODEL_PATH)
templates = Jinja2Templates(directory=TEMPLATES_DIR)

os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
app.mount("/uploads", StaticFiles(directory=UPLOAD_FOLDER), name="uploads")

def preprocess_image(image: Image.Image):
image = image.resize((224, 224))
Expand All @@ -32,17 +36,14 @@ def preprocess_image(image: Image.Image):
return image_array

def get_image_features(image: Image.Image):
preprocessed_image = preprocess_image(image)
features = model.predict(preprocessed_image)
return features
return model.predict(preprocess_image(image))

def compare_images(image1_features, image2_features):
return np.linalg.norm(image1_features - image2_features)

def get_images_from_zip():
with zipfile.ZipFile(ZIP_PATH, 'r') as archive:
image_keys = [name for name in archive.namelist() if name.lower().endswith(('.jpg', '.jpeg', '.png'))]
return image_keys
with zipfile.ZipFile(ZIP_PATH, "r") as archive:
return [name for name in archive.namelist() if name.lower().endswith((".jpg", ".jpeg", ".png"))]

def extract_and_save_image(archive, image_key):
with archive.open(image_key) as image_file:
Expand All @@ -54,42 +55,32 @@ def extract_and_save_image(archive, image_key):

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
return templates.TemplateResponse("upload_form.html", {"request": request})

@app.post("/find_similar/")
async def find_similar_images(file: UploadFile = File(...)):
uploaded_image = Image.open(BytesIO(await file.read()))
uploaded_image_features = get_image_features(uploaded_image)
images = get_images_from_zip()
similarities = []

with zipfile.ZipFile(ZIP_PATH, 'r') as archive:
with zipfile.ZipFile(ZIP_PATH, "r") as archive:
for image_key in images:
try:
with archive.open(image_key) as image_file:
image = Image.open(image_file)
image = image.convert('RGB')
image_features = get_image_features(image)
similarity = compare_images(uploaded_image_features, image_features)
image = Image.open(image_file).convert("RGB")
similarity = compare_images(uploaded_image_features, get_image_features(image))
similarities.append((image_key, similarity))
except UnidentifiedImageError:
print(f"Cannot identify image file: {image_key}")
except Exception as e:
print(f"Error processing image {image_key}: {e}")

similarities.sort(key=lambda x: x[1])
similar_images = []

with zipfile.ZipFile(ZIP_PATH, 'r') as archive:
with zipfile.ZipFile(ZIP_PATH, "r") as archive:
for image_key, _ in similarities[:5]:
saved_image_name = extract_and_save_image(archive, image_key)
similar_images.append(saved_image_name)

return {
'filename': file.filename,
'similar_images': similar_images
}
similar_images.append(extract_and_save_image(archive, image_key))
return {"filename": file.filename, "similar_images": similar_images}

if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
uvicorn.run(app, host="127.0.0.1", port=8000)
6 changes: 1 addition & 5 deletions fastapi_app/templates/upload_form.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PicTrace</title>
<link rel="stylesheet" href="/static/styles.css">
</head>

<body>
<div class="container">
<h1>Hello!</h1>
<p>Please upload a photo to search for similar images.</p>
Expand All @@ -18,9 +17,6 @@ <h1>Hello!</h1>
</form>
<div id="results"></div>
</div>

<script src="/static/scripts.js"></script>

</body>

</html>

0 comments on commit 405c095

Please sign in to comment.