import requests import os import gradio as gr # --- Hugging Face Spaces Deployment Specifics --- # Get API key from Spaces secrets API_KEY = os.environ.get("GOOGLE_API_KEY") if API_KEY is None: raise ValueError("API key not found. Set GOOGLE_API_KEY in Spaces secrets.") # --- Gemini Flash Summarization Function --- def summarize_text_with_gemini(text, temperature=0.2, max_decode_steps=1024): """Summarizes text using Gemini Flash API.""" api_url = "https://generativelanguage.googleapis.com/v1beta3/models/gemini-flash:generateText" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}" } request_body = { "prompt": { "text": f"Please provide a concise summary of the following text:\n\n{text}" }, "temperature": temperature, "maxDecodeSteps": max_decode_steps } try: response = requests.post(api_url, headers=headers, json=request_body) response.raise_for_status() json_response = response.json() if "candidates" in json_response and len(json_response["candidates"]) > 0: summary = json_response["candidates"][0]["output"] return summary else: print("No summary candidates found in the API response.") # Good for debugging in logs return "No summary could be generated." # More user-friendly except requests.exceptions.RequestException as e: print(f"Error during API call: {e}") # For logs/debugging return f"An error occurred: {e}" # User-facing message (be cautious about exposing too much detail) # --- Hugging Face Spaces Gradio App --- with gr.Blocks() as demo: # Use with statement for proper cleanup gr.Markdown("# Gemini Flash Text Summarizer") # Title with gr.Row(): # Arrange input and output side-by-side input_text = gr.Textbox(lines=8, label="Input Text") output_text = gr.Textbox(lines=8, label="Summary") temp_slider = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.2, label="Temperature") max_steps_slider = gr.Slider(minimum=64, maximum=2048, step=64, value=1024, label="Max Decode Steps") submit_btn = gr.Button("Summarize") submit_btn.click( fn=summarize_text_with_gemini, inputs=[input_text, temp_slider, max_steps_slider], # Pass temperature and max steps outputs=output_text, api_name="summarize" # Optional: for easily creating shareable links/embedding the demo. ) demo.launch()