Spaces:
Sleeping
Sleeping
| 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() | |