from flask import Flask, request, jsonify, render_template import base64 import re import requests import os app = Flask(__name__) # Get API keys from environment variables api_key = os.getenv('OPENAI_API_KEY') huggingface_api_key = os.getenv('HUGGINGFACE_API_KEY') huggingface_url = "https://huggingface.co/api/spaces/devlim/supernova/upload" @app.route('/') def index(): return render_template('index.html') @app.route('/save_image', methods=['POST']) def save_image(): if 'image' not in request.files: return jsonify({'message': 'No image part in the request'}), 400 file = request.files['image'] if file.filename == '': return jsonify({'message': 'No selected file'}), 400 # Save the image to a temporary file temp_image_path = os.path.join("temp", file.filename) file.save(temp_image_path) # Upload the image to Hugging Face Space headers = { "Authorization": f"Bearer {huggingface_api_key}" } files = { 'file': (file.filename, open(temp_image_path, 'rb'), 'image/png') } response = requests.post(huggingface_url, headers=headers, files=files) if response.status_code != 200: os.remove(temp_image_path) return jsonify({'message': 'Error: 허깅페이스에 이미지를 업로드할 수 없습니다.'}), 500 # Get the uploaded image URL from Hugging Face response uploaded_image_url = response.json()['url'] # Prepare the payload for OpenAI API headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } payload = { "model": "gpt-4", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "이미지를 입력받으면 당류가 몇 g인지 예시와 같은 형식만 출력하시오.\n예) 당류 : 10g \n상품분석표가 아니라면 'error'를 출력하시오." }, { "type": "image_url", "image_url": { "url": uploaded_image_url } } ] } ], "max_tokens": 300 } response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload) os.remove(temp_image_path) if response.status_code == 200: result = response.json() analysis_result = result['choices'][0]['message']['content'] else: analysis_result = "Error: 당류를 찾을 수 없습니다." return jsonify({'message': '분석이 완료되었습니다.', 'analysis_result': analysis_result}) if __name__ == '__main__': os.makedirs('temp', exist_ok=True) app.run(host='0.0.0.0', port=7860, debug=True)