commit 0c4ceec22167ef9d963f6d51fa5f5e4670340f1f Author: HarshvardhanChandel Date: Fri Feb 28 12:36:45 2025 +0530 first commit diff --git a/groq_module.py b/groq_module.py new file mode 100644 index 0000000..00b31f4 --- /dev/null +++ b/groq_module.py @@ -0,0 +1,65 @@ +from dotenv import load_dotenv +import os +from groq import Groq +import json + +# Load environment variables +load_dotenv() + +# Initialize Groq client +client = Groq( + api_key=os.getenv("GROQ_API_KEY"), +) + + +def chat_with_groq(prompt: str, model: str = "llama-3.3-70b-versatile") -> str: + try: + # Create a chat completion + chat_completion = client.chat.completions.create( + messages=[ + { + "role": "system", + "content": "you are a helpful AI engineer assistant." + }, + { + "role": "user", + "content": prompt + } + ], + model=model, + ) + # Return the response content + return chat_completion.choices[0].message.content + except Exception as e: + return f"An error occurred: {e}" + +def groq_module_fun(resume_prompt, base64_image): + completion = client.chat.completions.create( + model="llama-3.2-90b-vision-preview", + messages=[ + { + "role": "user", + "content": [ + { + "type": "text", + "text": resume_prompt + }, + { + "type": "image_url", + "image_url": { + "url": f"data:image/jpeg;base64,{base64_image}", + }, + } + ] + } + ], + temperature=1, + max_completion_tokens=1024, + top_p=1, + stream=False, + response_format={"type": "json_object"}, + ) + + # Access the response here inside the function + api_response = completion.choices[0].message.content + return api_response diff --git a/helpers.py b/helpers.py new file mode 100644 index 0000000..5a5ae5c --- /dev/null +++ b/helpers.py @@ -0,0 +1,26 @@ +import base64 +import json +import re + +def jpeg_to_base64(file_path): + with open(file_path, "rb") as image_file: + encoded_string = base64.b64encode(image_file.read()) + return encoded_string.decode('utf-8') + +def extract_json_to_dict(input_string): + # Use regex to extract JSON content + json_pattern = re.compile(r"\{.*\}", re.DOTALL) # DOTALL allows matching across multiple lines + match = json_pattern.search(input_string) + + if match: + json_content = match.group(0) # Extract the matched JSON content + try: + # Convert the JSON string to a dictionary + json_dict = json.loads(json_content) + return json_dict + except json.JSONDecodeError: + print("Error: Extracted content is not valid JSON.") + return None + else: + print("No JSON content found.") + return None \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..c41c2ff --- /dev/null +++ b/main.py @@ -0,0 +1,200 @@ +from groq_module import groq_module_fun, chat_with_groq +from helpers import jpeg_to_base64, extract_json_to_dict +from flask import Flask, request, jsonify +import json +import os + +app = Flask(__name__) + +@app.route('/recipe-maker', methods=['POST']) +def recipe_maker(): + data = request.get_json() + if not data: + return jsonify({"error": "JSON body is required"}), 400 + + query = data.get('query') + + + prompt = f''' based on the following query: + query: {query} + generate the recipe of the best 5 dishes in the following JSON format: + + + {{ + "message": "" + "Recipe":{{ + "dish1": {{ + "name": "", + "ingredients": "", + "instructions": "" + }}, + "dish2": {{ + "name": "", + "ingredients": "", + "instructions": "" + }}, + "dish3": {{ + "name": "", + "ingredients": "", + "instructions": "" + }}, + "dish4": {{ + "name": "", + "ingredients": "", + "instructions": "" + }}, + "dish5": {{ + "name": "", + "ingredients": "", + "instructions": "" + }} + }} + + }} + ''' + + response = chat_with_groq(prompt) + print(response) + recipe = extract_json_to_dict(response) + + + + result = { + "recipe": recipe, + "query": query, + } + + return jsonify(result), 200 + +@app.route('/diet-plan', methods=['POST']) +def meal_diet_plan(): + data = request.get_json() + if not data: + return jsonify({"error": "JSON body is required"}), 400 + + weight = data.get('weight') + height = data.get('height') + target_weight = data.get('target_weight') + + if weight is None or height is None or target_weight is None: + return jsonify({"error": "Weight, height, and target weight are required"}), 400 + + prompt = f''' based on the following information: + weight: {weight} + height: {height} + target weight: {target_weight} + + Please provide a weekly diet plan for the user to achieve their target weight in the following JSON format: + {{ + "day1": {{ + "breakfast": "", + "lunch": "", + "snack": "", + "dinner": "" + }}, + "day2": {{ + "breakfast": "", + "lunch": "", + "snack": "", + "dinner": "" + }}, + "day3": {{ + "breakfast": "", + "lunch": "", + "snack": "", + "dinner": "" + }}, + "day4": {{ + "breakfast": "", + "lunch": "", + "snack": "", + "dinner": "" + }}, + "day5": {{ + "breakfast": "", + "lunch": "", + "snack": "", + "dinner": "" + }}, + "day6": {{ + "breakfast": "", + "lunch": "", + "snack": "", + "dinner": "" + }}, + "day7": {{ + "breakfast": "", + "lunch": "", + "snack": "", + "dinner": "" + }} + }} + ''' + + response = chat_with_groq(prompt) + print(response) + week_diet_plan = extract_json_to_dict(response) + + + + result = { + "meal_diet_plan": week_diet_plan, + "weight": weight, + "height": height, + "target_weight": target_weight, + } + + return jsonify(result), 200 + +@app.route('/food-scan', methods=['POST']) +def food_scan(): + if 'file' not in request.files: + return jsonify({"error": "File is required"}), 400 + + file = request.files['file'] + if file.filename == '': + return jsonify({"error": "Invalid file"}), 400 + + # Secure file saving + temp_dir = "/tmp" + os.makedirs(temp_dir, exist_ok=True) # Ensure temp directory exists + jpeg_file_path = os.path.join(temp_dir, file.filename) + + try: + file.save(jpeg_file_path) + except Exception as e: + return jsonify({"error": f"Failed to save file: {str(e)}"}), 500 + + # Convert image to Base64 + base64_string = jpeg_to_base64(jpeg_file_path) + if not base64_string: + return jsonify({"error": "Failed to encode image"}), 500 + + # Construct prompt correctly + prompt = """ + This is a food image. Classify the food name and category in the following JSON format: + { + "food_name": "", + "category": "", + "calories": , + "fat": , + "carbohydrates": , + "protein": , + "sugar": , + "fiber": + } + """ + + # Call the function (ensure this is implemented correctly) + response = groq_module_fun(prompt, base64_string) + food_data = json.loads(response) + result = { + "result": food_data + } + + return jsonify(result), 200 + + +if __name__ == '__main__': + app.run(host='0.0.0.0', port=5000, debug=True) +