Spaces:
Running
Running
import os | |
import gradio as gr | |
import google.generativeai as genai | |
# Initialize the Gemini API | |
def initialize_gemini(): | |
api_key = os.getenv("GOOGLE_API_KEY") | |
if not api_key: | |
raise ValueError("GOOGLE_API_KEY is not set in environment variables.") | |
genai.configure(api_key=api_key) | |
return genai.GenerativeModel("gemini-2.0-flash-exp") # Assuming gemini-2.0-flash-exp is the correct model name | |
# Handle file inputs and text to generate a response | |
def generate_response(text_input, files): | |
contents = [] | |
if text_input: | |
contents.append({"text": text_input}) # Add text input to the contents | |
for file in files: | |
with open(file.name, "rb") as f: | |
data = f.read() | |
# Guess the MIME type from the file input | |
mime_type = gr.io.utils.guess_mime_type(file.name) | |
if mime_type: | |
contents.append({ | |
"mime_type": mime_type, | |
"data": data | |
}) | |
model = initialize_gemini() | |
response = model.generate_content(contents) | |
response.resolve() | |
return response.text | |
# Gradio Interface | |
def setup_interface(): | |
with gr.Blocks() as app: | |
with gr.Row(): | |
text_input = gr.Textbox(label="Enter any text:", placeholder="Type your question or comment here...") | |
file_input = gr.File(label="Upload your files", file_types=["image", "video", "audio", "pdf"]) | |
submit_button = gr.Button("Generate Response") | |
response_output = gr.Textbox(label="Response from Gemini", placeholder="Response will appear here...") | |
submit_button.click( | |
fn=generate_response, | |
inputs=[text_input, file_input], | |
outputs=[response_output] | |
) | |
return app | |
# Run the interface | |
if __name__ == "__main__": | |
app = setup_interface() | |
app.launch(share=True) # Set `share=True` for Hugging Face Spaces or public deployment |