Spaces:
Build error
Build error
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import osimport ioimport gradio as grimport google.generativeai as genaifrom PIL import Image# Configure the Gemini API# Retrieve the API key from Hugging Face Spaces secretsapi_key = os.environ.get("GEMINI_API_KEY")if not api_key:raise ValueError("GEMINI_API_KEY not found in environment variables. Please set it in Hugging Face Spaces secrets.")genai.configure(api_key=api_key)def upload_to_gemini(image):"""Uploads the given image to Gemini."""if image is None:return Noneimage_byte_array = io.BytesIO()image.save(image_byte_array, format='JPEG')image_byte_array = image_byte_array.getvalue()return genai.upload_file(image_byte_array, mime_type="image/jpeg")# Create the modelgeneration_config = {"temperature": 0.9,"top_p": 0.95,"top_k": 64,"max_output_tokens": 1024,"response_mime_type": "text/plain",}model = genai.GenerativeModel(model_name="gemini-1.5-flash",generation_config=generation_config,)def chat_with_gemini(history, user_message, image):history = history or []try:uploaded_image = upload_to_gemini(image) if image else Noneif not history:# Start a new chat sessionchat_session = model.start_chat(history=[{"role": "user","parts": [uploaded_image,user_message,] if uploaded_image else [user_message],},])else:# Continue existing chat sessionchat_session = model.start_chat(history=[{"role": "user" if i % 2 == 0 else "model", "parts": [msg]}for i, (msg, _) in enumerate(history)])# Send the new messageif uploaded_image:chat_session.send_message([uploaded_image, user_message])else:chat_session.send_message(user_message)# Get the responseresponse = chat_session.lastresponse_text = response.texthistory.append((user_message, response_text))except Exception as e:error_message = f"An error occurred: {str(e)}"history.append((user_message, error_message))return history, historydef clear_conversation():return None# Define the Gradio interfacewith gr.Blocks() as demo:chatbot = gr.Chatbot(label="Chat with Gemini 1.5 Flash")msg = gr.Textbox(label="Type your message here")clear = gr.Button("Clear")image_upload = gr.Image(type="pil", label="Upload an image (optional)")msg.submit(chat_with_gemini, [chatbot, msg, image_upload], [chatbot, chatbot])clear.click(clear_conversation, outputs=[chatbot])# Launch the appif __name__ == "__main__":1234567891011121314151617181920212223242526272829303132333435363738394041424344import osimport gradio as grimport google.generativeai as genai# Configure the Gemini APIapi_key = os.environ.get("GEMINI_API_KEY")if not api_key:raise ValueError("GEMINI_API_KEY not found in environment variables. Please set it in Hugging Face Spaces secrets.")genai.configure(api_key=api_key)# Create the modelmodel = genai.GenerativeModel('gemini-pro')# Initialize chat historychat = model.start_chat(history=[])def respond(message, history):history = history or []try:# Send user message and get responseresponse = chat.send_message(message)bot_message = response.text# Append to history and returnhistory.append((message, bot_message))return history, historyexcept Exception as e:error_message = f"An error occurred: {str(e)}"history.append((message, error_message))return history, history# Define the Gradio interfacewith gr.Blocks() as demo:chatbot = gr.Chatbot(label="Chat with Gemini")msg = gr.Textbox(label="Type your message here")clear = gr.Button("Clear")msg.submit(respond, [msg, chatbot], [chatbot, chatbot])clear.click(lambda: None, outputs=[chatbot])# Launch the appif __name__ == "__main__":
app.py+15-66