File size: 3,561 Bytes
5099858
a5af311
 
 
 
5099858
a5af311
5099858
 
a5af311
 
 
 
 
 
5099858
a5af311
 
2740293
a5af311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e00f92a
2740293
e00f92a
a5af311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e00f92a
a5af311
 
 
e00f92a
a5af311
 
e00f92a
a5af311
e00f92a
102b1cc
a5af311
3d098ca
 
f3bb358
 
0891f1f
e00f92a
 
5e167c8
 
cab2c2f
3d098ca
5e167c8
 
102b1cc
 
2740293
a5af311
 
 
 
 
 
e00f92a
a5af311
2740293
a5af311
 
 
 
e00f92a
a5af311
 
 
 
 
 
 
 
 
 
 
 
9631de2
a5af311
5e167c8
f3bb358
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import os
import time
import json
from pathlib import Path
from dotenv import load_dotenv
import requests
from datetime import datetime
import gradio as gr

# Configuration
QUOTA_FILE = "api_quota.json"
RATE_LIMIT_DELAY = 1.0
DEFAULT_MODEL = "facebook/bart-large-cnn"
MAX_RETRIES = 3
RETRY_DELAY = 5

# --- Core Functions ---
def load_quota():
    try:
        if Path(QUOTA_FILE).exists():
            with open(QUOTA_FILE, "r") as f:
                return json.load(f)
    except:
        pass
    return {"remaining": 600, "last_updated": datetime.now().isoformat()}

def save_quota(quota):
    with open(QUOTA_FILE, "w") as f:
        json.dump(quota, f)

def summarize_text(text, model=DEFAULT_MODEL):
    try:
        load_dotenv()
        token = os.getenv("HF_API_TOKEN")
        if not token:
            return "⚠️ Add your Hugging Face token to .env file", "0/600"
    except Exception as e:
        return f"⚠️ Config error: {str(e)}", "0/600"

    api_url = f"https://api-inference.huggingface.co/models/{model}"
    headers = {"Authorization": f"Bearer {token}"}
    payload = {"inputs": text, "parameters": {"max_length": 50, "min_length": 20}}

    for attempt in range(MAX_RETRIES):
        try:
            time.sleep(RATE_LIMIT_DELAY)
            response = requests.post(api_url, headers=headers, json=payload, timeout=10)
            
            quota = load_quota()
            quota["remaining"] = max(0, quota.get("remaining", 600) - 1)
            save_quota(quota)

            if response.status_code == 200:
                result = response.json()
                if isinstance(result, list):
                    return result[0].get("summary_text", "⚠️ No summary generated"), f"{quota['remaining']}/600"
            if response.status_code == 503:
                time.sleep(RETRY_DELAY)
                continue
            return f"⚠️ API Error: {response.text[:200]}", f"{quota['remaining']}/600"
        except requests.exceptions.RequestException as e:
            if attempt == MAX_RETRIES - 1:
                return f"⚠️ Network error: {str(e)}", "0/600"
            time.sleep(RETRY_DELAY)
    return "⚠️ Failed after multiple attempts", "0/600"

# --- Gradio Interface ---
css = """
button {
    background: #A41F13 !important;
    color: white !important;
    border: none !important;
    border-radius: 8px !important;
    padding: 12px 24px !important;
    font-weight: bold !important;
    transition: transform 0.2s ease-in-out;
}
button:hover {
    transform: scale(1.05);
    cursor: pointer;
}
"""

with gr.Blocks(theme=gr.themes.Soft(), css=css, title="My AI Summarizer") as app:
    gr.Markdown("# ✨ My Text Summarizer")
    gr.Markdown("Paste any text and get a concise summary using AI!")

    with gr.Row():
        input_text = gr.Textbox(label="Input Text", lines=8, placeholder="Paste your article/story here...")
        output_text = gr.Textbox(label="Summary", lines=8, interactive=False)

    with gr.Row():
        submit_btn = gr.Button("Summarize", variant="primary")
        quota_display = gr.Textbox(label="API Status", interactive=False)

    submit_btn.click(
        fn=summarize_text,
        inputs=input_text,
        outputs=[output_text, quota_display]
    )

    gr.Examples(
        examples=[
            "He prayed Fajr half-asleep...",
            "Scientists discovered octopuses can edit their RNA...",
            "The quick brown fox jumps over the lazy dog."
        ],
        inputs=input_text
    )

if __name__ == "__main__":
    app.launch()