-
Notifications
You must be signed in to change notification settings - Fork 41
/
app.py
114 lines (88 loc) · 3.09 KB
/
app.py
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
from flask import (
Flask,
render_template,
request,
Response,
stream_with_context,
jsonify,
)
from werkzeug.utils import secure_filename
from PIL import Image
import io
from dotenv import load_dotenv
import os
import google.generativeai as genai
# Load environment variables from .env file
load_dotenv()
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"}
# WARNING: Do not share code with you API key hard coded in it.
# Get your Gemini API key from: https://aistudio.google.com/app/apikey
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
model = genai.GenerativeModel('gemini-1.5-flash')
app = Flask(__name__, static_folder='static', template_folder='templates')
chat_session = model.start_chat(history=[])
next_message = ""
next_image = ""
def allowed_file(filename):
"""Returns if a filename is supported via its extension"""
_, ext = os.path.splitext(filename)
return ext.lstrip('.').lower() in ALLOWED_EXTENSIONS
@app.route("/upload", methods=["POST"])
def upload_file():
"""Takes in a file, checks if it is valid,
and saves it for the next request to the API
"""
global next_image
if "file" not in request.files:
return jsonify(success=False, message="No file part")
file = request.files["file"]
if file.filename == "":
return jsonify(success=False, message="No selected file")
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
# Read the file stream into a BytesIO object
file_stream = io.BytesIO(file.read())
file_stream.seek(0)
next_image = Image.open(file_stream)
return jsonify(
success=True,
message="File uploaded successfully and added to the conversation",
filename=filename,
)
return jsonify(success=False, message="File type not allowed")
@app.route("/", methods=["GET"])
def index():
"""Renders the main homepage for the app"""
return render_template("index.html", chat_history=chat_session.history)
@app.route("/chat", methods=["POST"])
def chat():
"""
Takes in the message the user wants to send
to the Gemini API, saves it
"""
global next_message
next_message = request.json["message"]
print(chat_session.history)
return jsonify(success=True)
@app.route("/stream", methods=["GET"])
def stream():
"""
Streams the response from the server for
both multi-modal and plain text requests
"""
def generate():
global next_message
global next_image
assistant_response_content = ""
if next_image != "":
response = chat_session.send_message([next_message, next_image],
stream=True)
next_image = ""
else:
response = chat_session.send_message(next_message, stream=True)
next_message = ""
for chunk in response:
assistant_response_content += chunk.text
yield f"data: {chunk.text}\n\n"
return Response(stream_with_context(generate()),
mimetype="text/event-stream")