calorie-proxy / main.py
Ghotst's picture
Upload 5 files
d5e9133 verified
Raw History Blame Contribute Delete
2.57 kB
from flask import Flask, request, jsonify
import requests
import os
app = Flask(__name__)
GROQ_API_KEY = os.environ.get('GROQ_API_KEY', '')
GROQ_ENDPOINT = 'https://api.groq.com/openai/v1/chat/completions'
GROQ_MODEL = 'meta-llama/llama-4-scout-17b-16e-instruct'
@app.route('/health', methods=['GET'])
def health():
return jsonify({'status': 'ok'})
@app.route('/analyze', methods=['POST'])
def analyze():
data = request.get_json()
if not data or 'image_base64' not in data:
return jsonify({'error': 'Нет изображения'}), 400
image_b64 = data['image_base64']
payload = {
'model': GROQ_MODEL,
'messages': [
{
'role': 'user',
'content': [
{
'type': 'image_url',
'image_url': {'url': f'data:image/jpeg;base64,{image_b64}'}
},
{
'type': 'text',
'text': '''You are a nutrition expert. Analyze this food photo. Respond ONLY with valid JSON, no markdown:
{"dish_name":"название на русском","dish_name_en":"name in english","portion_weight_g":number,"calories":number,"protein_g":number,"fat_g":number,"carbs_g":number,"confidence":"high or medium or low","notes":"подсказка до 60 символов"}
If no food visible: {"error":"описание на русском"}'''
}
]
}
],
'max_tokens': 512,
'temperature': 0.2
}
try:
resp = requests.post(
GROQ_ENDPOINT,
json=payload,
headers={
'Authorization': f'Bearer {GROQ_API_KEY}',
'Content-Type': 'application/json'
},
timeout=55
)
if resp.status_code != 200:
return jsonify({'error': f'Ошибка Groq: {resp.status_code}'}), 502
result = resp.json()
raw = result['choices'][0]['message']['content']
raw = raw.replace('```json', '').replace('```', '').strip()
s, e = raw.find('{'), raw.rfind('}')
if s == -1 or e == -1:
return jsonify({'error': 'Неожиданный ответ ИИ'}), 502
import json
parsed = json.loads(raw[s:e+1])
return jsonify(parsed)
except Exception as ex:
return jsonify({'error': str(ex)}), 500
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)