Spaces:
Sleeping

File size: 3,218 Bytes
09df99f
 
 
 
d356fb3
09df99f
 
 
 
8e39c7c
 
 
09df99f
 
d356fb3
09df99f
 
 
 
8e39c7c
 
09df99f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e39c7c
09df99f
 
 
 
 
 
 
 
 
 
 
8e39c7c
 
09df99f
 
8e39c7c
09df99f
 
8e39c7c
 
09df99f
 
 
8e39c7c
09df99f
 
 
8e39c7c
09df99f
 
 
 
8e39c7c
09df99f
8e39c7c
09df99f
 
 
 
 
 
 
 
 
 
 
41f1947
09df99f
 
 
 
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
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()