Spaces:
Sleeping
Sleeping
File size: 11,846 Bytes
b02ebf7 a488b5b b02ebf7 e42e910 a488b5b b02ebf7 a488b5b b02ebf7 a488b5b b02ebf7 a488b5b b02ebf7 a488b5b 6222689 b02ebf7 a488b5b b02ebf7 6222689 b02ebf7 481ebb9 b02ebf7 6222689 b02ebf7 b2c3d9b b02ebf7 b2c3d9b b02ebf7 b2c3d9b b02ebf7 6222689 b02ebf7 a488b5b b02ebf7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from pymongo import MongoClient
from urllib.parse import quote_plus
import uuid
from typing import List, Optional
import json
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import HTMLResponse
import os
import base64
from groq import Groq
# Initialize Groq client
client = Groq(api_key='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')
# MongoDB connection setup
def get_mongo_client():
password = quote_plus("momimaad@123") # Change this to your MongoDB password
mongo_uri = f"mongodb+srv://hammad:{password}@cluster0.2a9yu.mongodb.net/"
return MongoClient(mongo_uri)
db_client = get_mongo_client()
db = db_client["recipe"]
user_collection = db["user_info"]
# Pydantic models for user data
class User(BaseModel):
first_name: str
last_name: str
email: str
password: str
class UserData(BaseModel):
email: str
password: str
class UserToken(BaseModel):
token: str
class RecipeData(BaseModel):
name: str
class AltrecipeData(BaseModel):
recipe_name: str
dietary_restrictions: str
allergies: List
class Ingredient(BaseModel):
name: str
quantity: str
class Recipe(BaseModel):
recipe_name: str
ingredients: List[Ingredient]
directions: List[str]
# Data model for LLM to generate
class Alternative_Ingredient(BaseModel):
name: str
quantity: str
class Alternative_Recipe(BaseModel):
recipe_name: str
alternative_ingredients: List[Alternative_Ingredient]
alternative_directions: List[str]
def get_recipe(recipe_name: str) -> Recipe:
chat_completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": f"""Your are an expert agent to generate a recipes with proper and corrected ingredients and direction. Your directions should be concise and to the point and dont explain any irrelevant text.
You are a recipe database that outputs recipes in JSON.\n
The JSON object must use the schema: {json.dumps(Recipe.model_json_schema(), indent=2)}""",
},
{
"role": "user",
"content": f"Fetch a recipe for {recipe_name}",
},
],
model="llama-3.2-90b-text-preview",
temperature=0,
# Streaming is not supported in JSON mode
stream=False,
# Enable JSON mode by setting the response format
response_format={"type": "json_object"},
)
return Recipe.model_validate_json(chat_completion.choices[0].message.content)
def Suggest_ingredient_alternatives(recipe_name: str, dietary_restrictions: str, allergies: List) -> Alternative_Recipe:
chat_completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": f"""
You are an expert agent to suggest alternatives for specific allergies ingredients for the provided recipe {recipe_name}.
Please take the following into account:
- If the user has dietary restrictions, suggest substitutes that align with their needs (e.g., vegan, gluten-free, etc.) in alternative_directions and your alternative_directions should be concise and to the point.
-In ingredient you will recommend the safe ingredient for avoid any allergy and dietary restriction.
- Consider the following allergies {allergies} and recommend the safe ingredient to avoid this allergies.
recipe_name: {recipe_name}
Dietary Restrictions: {dietary_restrictions}
Allergies: {', '.join(allergies)}
You are a recipe database that outputs alternative recipes to avoid allergy and dietary_restrictions in JSON.\n
The JSON object must use the schema: {json.dumps(Alternative_Recipe.model_json_schema(), indent=2)}""",
},
{
"role": "user",
"content": f"""Fetch a alternative recipe for recipe_name: {recipe_name}
Dietary Restrictions: {dietary_restrictions}
Allergies: {', '.join(allergies)}""",
},
],
model="llama-3.2-90b-text-preview",
temperature=0,
# Streaming is not supported in JSON mode
stream=False,
# Enable JSON mode by setting the response format
response_format={"type": "json_object"},
)
return Alternative_Recipe.model_validate_json(chat_completion.choices[0].message.content)
def get_status(content):
chat_completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": """Your are an expert agent to status yes if any kind of recipe dish present in explanation other no
Json output format:
{'status':return'yes' if any dish present in expalantion return 'no' if not dish present in image}
""",
},
{
"role": "user",
"content": f"Image Explanation {content}",
},
],
model="llama3-groq-70b-8192-tool-use-preview",
temperature=0,
# Streaming is not supported in JSON mode
stream=False,
# Enable JSON mode by setting the response format
response_format={"type": "json_object"},
)
return chat_completion.choices[0].message.content
# Function to encode the image
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def explain_image(base64_image):
text_query = '''
explain the image.
'''
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": text_query},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}",
},
},
],
}
],
model="llama-3.2-90b-vision-preview")
return chat_completion.choices[0].message.content
class get_recipe_name(BaseModel):
recipe_name: List[str]
ingredients: List[List[str]]
def generate_recipe_name(base64_image):
# Example of how the JSON should look to make it clearer
example_json_structure = {
"recipe_name": "Chicken Karhai",
"ingredients": [
"chicken",
"tomatoes",
"onions",
"ginger",
"garlic",
"green chilies",
"yogurt",
"cumin seeds",
"coriander powder",
"red chili powder",
"turmeric powder",
"garam masala",
"fresh coriander leaves",
"oil",
"salt"
]
}
# Generating the query prompt to ask for ingredients
text_query = f'''What are the ingredients used in these dishes? Do not add any explanation, just write the names of the ingredients in proper JSON according to the following format:
The JSON object must follow this schema:
{json.dumps(get_recipe_name.model_json_schema(), indent=2)}
Example format:
{json.dumps(example_json_structure, indent=2)}
Write the name of the dish and then list the ingredients used for each recipe, focusing on traditional Pakistani ingredients and terminology.
'''
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": text_query},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}",
},
},
],
}
],
response_format={"type": "json_object"},
model="llama-3.2-90b-vision-preview")
return json.loads(chat_completion.choices[0].message.content)
app = FastAPI()
@app.post("/get_recipe/{token}")
async def get_recipe_response(token: str, recipe_user: RecipeData):
user = user_collection.find_one({"token": token})
if not user:
raise HTTPException(status_code=401, detail="Invalid token")
# Find user by email
recipe_name = recipe_user.name
response = get_recipe(recipe_name)
return {
"Response": response
}
@app.post("/get_recipe_alternative/{token}")
async def get_alternative_recipe_response(token: str, altrecipe_user: AltrecipeData):
user = user_collection.find_one({"token": token})
if not user:
raise HTTPException(status_code=401, detail="Invalid token")
response = Suggest_ingredient_alternatives(altrecipe_user.recipe_name, altrecipe_user.dietary_restrictions, altrecipe_user.allergies)
return {
"Response": response
}
# Directory to save uploaded images
UPLOAD_DIR = "uploads"
# Ensure the upload directory exists
os.makedirs(UPLOAD_DIR, exist_ok=True)
# Endpoint to upload an image
@app.post("/upload-image/{token}")
async def upload_image(token: str, file: UploadFile = File(...)):
user = user_collection.find_one({"token": token})
if not user:
raise HTTPException(status_code=401, detail="Invalid token")
# Validate the file type
if not file.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
raise HTTPException(status_code=400, detail="Invalid file type. Only PNG, JPG, and JPEG are allowed.")
# Create a file path for saving the uploaded file
file_path = os.path.join(UPLOAD_DIR, file.filename)
# Save the file
with open(file_path, "wb") as buffer:
buffer.write(await file.read())
# Getting the base64 string
base64_image = encode_image(file_path)
status = get_status(explain_image(base64_image))
status_json = json.loads(status)
if status_json['status'].lower() == 'no':
response = {"recipe_name": [], 'ingredients': []}
else:
response = generate_recipe_name(base64_image)
return {
"Response": response
}
# Endpoint to register a new user
@app.post("/register")
async def register_user(user: User):
# Check if user already exists
existing_user = user_collection.find_one({"email": user.email})
if existing_user:
raise HTTPException(status_code=400, detail="Email already registered")
# Create user data
user_data = {
"first_name": user.first_name,
"last_name": user.last_name,
"email": user.email,
"password": user.password, # Store plaintext password (not recommended in production)
}
# Insert the user data into the user_info collection
result = user_collection.insert_one(user_data)
return {"msg": "User registered successfully", "user_id": str(result.inserted_id)}
# Endpoint to check user credentials and generate a token
@app.post("/get_token")
async def check_credentials(user: UserData):
# Find user by email
existing_user = user_collection.find_one({"email": user.email})
# Check if user exists and password matches
if not existing_user or existing_user["password"] != user.password:
raise HTTPException(status_code=401, detail="Invalid email or password")
# Generate a UUID token
token = str(uuid.uuid4())
# Update the user document with the token
user_collection.update_one({"email": user.email}, {"$set": {"token": token}})
return {
"first_name": existing_user["first_name"],
"last_name": existing_user["last_name"],
"token": token,
}
|