Prathamesh Sable commited on
Commit
a1011ad
·
1 Parent(s): e3c16ea

added process image files and functions

Browse files
Files changed (4) hide show
  1. main.py +2 -0
  2. requirements.txt +1 -0
  3. routers/analysis.py +26 -1
  4. routers/product.py +50 -0
main.py CHANGED
@@ -2,11 +2,13 @@ from fastapi import FastAPI
2
  from routers.auth import router as auth_router
3
  from routers.analysis import router as analysis_router
4
  from routers.history import router as history_router
 
5
 
6
  app = FastAPI()
7
 
8
  app.include_router(analysis_router, prefix="/api/analyze")
9
  app.include_router(auth_router, prefix="/api/auth")
 
10
  app.include_router(history_router, prefix="/api/history")
11
 
12
  # To run the FastAPI app, use the command: uvicorn main:app --reload
 
2
  from routers.auth import router as auth_router
3
  from routers.analysis import router as analysis_router
4
  from routers.history import router as history_router
5
+ from routers.product import router as product_router
6
 
7
  app = FastAPI()
8
 
9
  app.include_router(analysis_router, prefix="/api/analyze")
10
  app.include_router(auth_router, prefix="/api/auth")
11
+ app.include_router(product_router, prefix="/api/product")
12
  app.include_router(history_router, prefix="/api/history")
13
 
14
  # To run the FastAPI app, use the command: uvicorn main:app --reload
requirements.txt CHANGED
@@ -140,3 +140,4 @@ xxhash==3.5.0
140
  yarl==1.19.0
141
  zope.interface==7.2
142
  zstandard==0.23.0
 
 
140
  yarl==1.19.0
141
  zope.interface==7.2
142
  zstandard==0.23.0
143
+ pillow
routers/analysis.py CHANGED
@@ -1,7 +1,8 @@
1
  import asyncio
2
  import os
3
  from datetime import datetime
4
- from fastapi import APIRouter, Depends, HTTPException
 
5
  import pytz
6
  from sqlalchemy.orm import Session
7
  from typing import List, Dict, Any
@@ -14,6 +15,10 @@ from db.database import get_db,SessionLocal
14
  from db.repositories import IngredientRepository
15
  from dotenv import load_dotenv
16
  from langsmith import traceable
 
 
 
 
17
 
18
  from services.ingredientFinderAgent import IngredientInfoAgentLangGraph
19
  from services.productAnalyzerAgent import analyze_product_ingredients
@@ -42,6 +47,26 @@ def ingredient_db_to_pydantic(db_ingredient):
42
  details_with_source=[source.data for source in db_ingredient.sources]
43
  )
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  # process single ingredient
47
  @router.post("/process_ingredient", response_model=IngredientAnalysisResult)
 
1
  import asyncio
2
  import os
3
  from datetime import datetime
4
+ from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
5
+ from fastapi.responses import JSONResponse
6
  import pytz
7
  from sqlalchemy.orm import Session
8
  from typing import List, Dict, Any
 
15
  from db.repositories import IngredientRepository
16
  from dotenv import load_dotenv
17
  from langsmith import traceable
18
+ from PIL import Image
19
+ import io
20
+ import base64
21
+ from fastapi.encoders import jsonable_encoder
22
 
23
  from services.ingredientFinderAgent import IngredientInfoAgentLangGraph
24
  from services.productAnalyzerAgent import analyze_product_ingredients
 
47
  details_with_source=[source.data for source in db_ingredient.sources]
48
  )
49
 
50
+ @router.post("/process_image")
51
+ async def process_image(file: UploadFile = File(...)):
52
+ try:
53
+ contents = await file.read()
54
+ image = Image.open(io.BytesIO(contents))
55
+
56
+ # Convert the image to JPEG format in memory
57
+ img_byte_arr = io.BytesIO()
58
+ image.save(img_byte_arr, format="JPEG")
59
+ img_byte_arr = img_byte_arr.getvalue()
60
+ # TODO add ML model to process the image and get the crop coordinates
61
+ # For testing frontend keeping same image and returning it
62
+
63
+ # Encode the JPEG image to base64
64
+ encoded_string = base64.b64encode(img_byte_arr).decode("utf-8")
65
+
66
+ return JSONResponse({"cropped_image": encoded_string})
67
+
68
+ except Exception as e:
69
+ return JSONResponse({"error": str(e)}, status_code=500)
70
 
71
  # process single ingredient
72
  @router.post("/process_ingredient", response_model=IngredientAnalysisResult)
routers/product.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from fastapi import APIRouter, File, Request, UploadFile
3
+ from fastapi.responses import JSONResponse
4
+ from typing import List, Dict
5
+ from logger_manager import log_info, log_error
6
+ from fastapi.encoders import jsonable_encoder
7
+ from PIL import Image
8
+ import os
9
+ import uuid
10
+
11
+ UPLOADED_IMAGES_DIR = "uploaded_images"
12
+ if not os.path.exists(UPLOADED_IMAGES_DIR):
13
+ os.makedirs(UPLOADED_IMAGES_DIR)
14
+
15
+ router = APIRouter()
16
+
17
+ @router.post("/add")
18
+ async def create_product(request: Request, image: UploadFile = File(...)):
19
+ log_info("Create product endpoint called")
20
+ try:
21
+ data = await request.json()
22
+ print("Received data:", data)
23
+
24
+ # dummy code below save image target to Vuforia and other details with id from vuforia
25
+ # TODO: Implement Vuforia integration to save image target and retrieve ID
26
+ # For now, we will just print the data and save the image locally
27
+ # Extract product details from the request body
28
+
29
+ name = data.get("name")
30
+ ingredients: List[str] = data.get("ingredients")
31
+
32
+ print("Product Name:", name)
33
+ print("Ingredients:", ingredients)
34
+
35
+ # Save the uploaded image
36
+ image_filename = f"{uuid.uuid4()}.jpg" # Generate a unique filename
37
+ image_path = os.path.join(UPLOADED_IMAGES_DIR, image_filename)
38
+
39
+
40
+ contents = await image.read()
41
+ img = Image.open(io.BytesIO(contents))
42
+ img.save(image_path, "JPEG")
43
+
44
+ print("Image saved to:", image_path)
45
+
46
+ return JSONResponse({"message": "Product data and image received and processed successfully"})
47
+
48
+ except Exception as e:
49
+ print("Error:", e)
50
+ return JSONResponse({"error": str(e)}, status_code=500)