Spaces:
Sleeping

mkhanumer's picture
Upload 2 files
d356fb3 verified
Raw History Blame Contribute Delete
3.22 kB
import os
import logging
import gradio as gr
import requests
import spaces
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"
MODEL_ID = "gemini-2.5-flash"
@spaces.GPU(duration=60)
def generate_reply(email_text):
if not email_text or not email_text.strip():
return "Please enter email text."
if not GEMINI_API_KEY:
return "Error: GEMINI_API_KEY not configured. Add it as a Space secret named GEMINI_API_KEY. Get a free key at https://aistudio.google.com/apikey"
email_text = email_text.strip()
system_prompt = (
"You are a professional email assistant. Given the text of an email someone received, "
"draft a short, polite, and contextually appropriate reply. "
"Keep the reply concise (2-5 sentences). "
"Do not include a subject line. "
"Do not include greetings like 'Dear' — start directly with the reply content. "
"Match the tone of the original email (formal if formal, casual if casual). "
"Only output the reply text, nothing else."
)
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"Draft a reply to this email:\n\n{email_text}"},
]
headers = {
"Authorization": f"Bearer {GEMINI_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": MODEL_ID,
"messages": messages,
"max_tokens": 256,
"temperature": 0.7,
}
try:
logger.info("Calling Gemini API")
response = requests.post(GEMINI_API_URL, headers=headers, json=payload, timeout=30)
if response.status_code == 429:
return "Error: Rate limited by Gemini API. Please try again in a moment."
if response.status_code != 200:
logger.error(f"Gemini API error {response.status_code}: {response.text[:500]}")
return f"Error: Gemini API returned status {response.status_code}"
data = response.json()
if "choices" not in data or len(data["choices"]) == 0:
return "Error: Gemini API returned unexpected response"
suggestion = data["choices"][0].get("message", {}).get("content", "").strip()
if not suggestion:
return "Error: Gemini API returned empty suggestion"
return suggestion
except requests.exceptions.Timeout:
return "Error: Gemini API request timed out. Please try again."
except requests.exceptions.ConnectionError:
return "Error: Could not connect to Gemini API. Please try again later."
except Exception as e:
logger.error(f"Unexpected error: {e}")
return f"Error: {str(e)}"
demo = gr.Interface(
fn=generate_reply,
inputs=gr.Textbox(label="Email Text", lines=6, placeholder="Paste the email text here..."),
outputs=gr.Textbox(label="Suggested Reply"),
title="Gmail Auto-Reply Assistant",
description="Enter email text to get an AI-generated reply suggestion.",
api_name="predict",
)
if __name__ == "__main__":
demo.launch()