uumerrr684 commited on
Commit
a5af311
·
verified ·
1 Parent(s): 3d098ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -20
app.py CHANGED
@@ -1,41 +1,107 @@
1
  import os
 
 
 
 
2
  import requests
 
3
  import gradio as gr
4
 
5
- TOKEN = os.getenv("HF_API_TOKEN", "").strip()
 
 
 
 
 
6
 
7
- def summarize(text):
8
- if not text.strip(): return "Please enter text", ""
9
  try:
10
- response = requests.post(
11
- "https://api-inference.huggingface.co/models/facebook/bart-large-cnn",
12
- headers={"Authorization": f"Bearer {TOKEN}"},
13
- json={"inputs": text[:2000], "parameters": {"max_length": 100}},
14
- timeout=20
15
- )
16
- return (response.json()[0]['summary_text'], "✅ Success") if response.ok else (f"⚠️ Error {response.status_code}", "")
 
 
 
 
 
 
 
 
 
 
17
  except Exception as e:
18
- return f"🚨 {str(e)}", ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
 
20
  css = """
21
  button {
22
  background: #6A0DAD !important;
23
  color: white !important;
24
  border: none !important;
25
- border-radius: 8px !important;
26
  }
27
  button:hover {
28
  background: #8A2BE2 !important;
29
  }
30
  """
31
 
32
- with gr.Blocks(css=css) as app:
33
- gr.Markdown("##SUMMIFY PRO")
 
 
 
 
 
 
34
  with gr.Row():
35
- input_txt = gr.Textbox(label="Your Text", placeholder="Type here...", lines=5)
36
- output_txt = gr.Textbox(label="Summary", interactive=False, lines=5)
37
- status = gr.Textbox(label="Status", interactive=False)
38
- gr.Button("Summarize").click(summarize, input_txt, [output_txt, status])
39
- gr.Button("Clear").click(lambda: ["", "", ""], [input_txt, output_txt, status])
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- app.launch(server_name="0.0.0.0")
 
 
1
  import os
2
+ import time
3
+ import json
4
+ from pathlib import Path
5
+ from dotenv import load_dotenv
6
  import requests
7
+ from datetime import datetime
8
  import gradio as gr
9
 
10
+ # Configuration
11
+ QUOTA_FILE = "api_quota.json"
12
+ RATE_LIMIT_DELAY = 1.0
13
+ DEFAULT_MODEL = "facebook/bart-large-cnn"
14
+ MAX_RETRIES = 3
15
+ RETRY_DELAY = 5
16
 
17
+ # --- Core Functions ---
18
+ def load_quota():
19
  try:
20
+ if Path(QUOTA_FILE).exists():
21
+ with open(QUOTA_FILE, "r") as f:
22
+ return json.load(f)
23
+ except:
24
+ pass
25
+ return {"remaining": 600, "last_updated": datetime.now().isoformat()}
26
+
27
+ def save_quota(quota):
28
+ with open(QUOTA_FILE, "w") as f:
29
+ json.dump(quota, f)
30
+
31
+ def summarize_text(text, model=DEFAULT_MODEL):
32
+ try:
33
+ load_dotenv()
34
+ token = os.getenv("HF_API_TOKEN")
35
+ if not token:
36
+ return "⚠️ Add your Hugging Face token to .env file"
37
  except Exception as e:
38
+ return f"⚠️ Config error: {str(e)}"
39
+
40
+ api_url = f"https://api-inference.huggingface.co/models/{model}"
41
+ headers = {"Authorization": f"Bearer {token}"}
42
+ payload = {"inputs": text, "parameters": {"max_length": 50, "min_length": 20}}
43
+
44
+ for attempt in range(MAX_RETRIES):
45
+ try:
46
+ time.sleep(RATE_LIMIT_DELAY)
47
+ response = requests.post(api_url, headers=headers, json=payload, timeout=10)
48
+
49
+ quota = load_quota()
50
+ quota["remaining"] = max(0, quota.get("remaining", 600) - 1)
51
+ save_quota(quota)
52
+
53
+ if response.status_code == 200:
54
+ result = response.json()
55
+ if isinstance(result, list):
56
+ return result[0].get("summary_text", "⚠️ No summary generated")
57
+ if response.status_code == 503:
58
+ time.sleep(RETRY_DELAY)
59
+ continue
60
+ return f"⚠️ API Error: {response.text[:200]}"
61
+ except requests.exceptions.RequestException as e:
62
+ if attempt == MAX_RETRIES - 1:
63
+ return f"⚠️ Network error: {str(e)}"
64
+ time.sleep(RETRY_DELAY)
65
+ return "⚠️ Failed after multiple attempts"
66
 
67
+ # --- Gradio Interface ---
68
  css = """
69
  button {
70
  background: #6A0DAD !important;
71
  color: white !important;
72
  border: none !important;
 
73
  }
74
  button:hover {
75
  background: #8A2BE2 !important;
76
  }
77
  """
78
 
79
+ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="My AI Summarizer") as app:
80
+ gr.Markdown("#My Text Summarizer")
81
+ gr.Markdown("Paste any text and get a concise summary using AI!")
82
+
83
+ with gr.Row():
84
+ input_text = gr.Textbox(label="Input Text", lines=8, placeholder="Paste your article/story here...")
85
+ output_text = gr.Textbox(label="Summary", lines=8)
86
+
87
  with gr.Row():
88
+ submit_btn = gr.Button("Summarize", variant="primary")
89
+ quota_display = gr.Textbox(label="API Status", interactive=False)
90
+
91
+ submit_btn.click(
92
+ fn=lambda x: (summarize_text(x),
93
+ inputs=input_text,
94
+ outputs=[output_text, quota_display]
95
+ )
96
+
97
+ gr.Examples(
98
+ examples=[
99
+ "He prayed Fajr half-asleep...",
100
+ "Scientists discovered octopuses can edit their RNA...",
101
+ "The quick brown fox jumps over the lazy dog."
102
+ ],
103
+ inputs=input_text
104
+ )
105
 
106
+ if __name__ == "__main__":
107
+ app.launch()