uumerrr684 commited on
Commit
2740293
·
verified ·
1 Parent(s): 2616610

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -126
app.py CHANGED
@@ -1,135 +1,50 @@
1
  import os
2
  import requests
3
  import gradio as gr
4
- from dotenv import load_dotenv
5
 
6
- # Initialize environment
7
- load_dotenv()
 
 
 
8
 
9
- class Summarizer:
10
- def __init__(self):
11
- self.model_url = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
12
- self.token = os.getenv("HF_API_TOKEN", "").strip()
13
 
14
- def validate_token(self):
15
- """Secure token verification with debug logging"""
16
- if not self.token.startswith("hf_"):
17
- print(" Token missing 'hf_' prefix") # Debug to logs
18
- return False
19
-
20
- try:
21
- test = requests.get(
22
- "https://api-inference.huggingface.co/status",
23
- headers={"Authorization": f"Bearer {self.token}"},
24
- timeout=5
25
- )
26
- if test.status_code == 401:
27
- print("🔑 Token rejected by API") # Debug to logs
28
- return test.ok
29
- except:
30
- return False
31
-
32
- def summarize(self, text):
33
- """Core summarization with robust error handling"""
34
- try:
35
- # Input validation
36
- if not text.strip():
37
- return "📝 Please enter text", "⚠️ Warning"
38
-
39
- # Token check
40
- if not self.validate_token():
41
- return "🔒 Invalid token - Check Secrets", "❌ Error"
42
-
43
- # API Call
44
- response = requests.post(
45
- self.model_url,
46
- headers={"Authorization": f"Bearer {self.token}"},
47
- json={
48
- "inputs": text[:5000],
49
- "parameters": {
50
- "max_length": 150,
51
- "min_length": 30,
52
- "do_sample": False
53
- }
54
- },
55
- timeout=25
56
- )
57
-
58
- # Response handling
59
- if response.status_code == 200:
60
- result = response.json()[0].get("summary_text", "No summary generated")
61
- return result, "✅ Success"
62
- elif response.status_code == 503:
63
- return "🔄 Model loading... Try again soon", "⚠️ Retry"
64
- else:
65
- return f"API Error {response.status_code}", "❌ Failed"
66
-
67
- except requests.exceptions.RequestException as e:
68
- return f"🌐 Network issue: {str(e)}", "⚠️ Connection"
69
- except Exception as e:
70
- return f"Unexpected error: {str(e)}", "❌ Critical"
71
-
72
- # Initialize summarizer
73
- summarizer = Summarizer()
74
-
75
- # Gradio Interface
76
- with gr.Blocks(
77
- title="Summify Pro",
78
- theme=gr.themes.Soft(
79
- primary_hue="indigo",
80
- secondary_hue="blue",
81
- font=[gr.themes.GoogleFont("Inter")]
82
- ),
83
- css=".gradio-container {max-width: 800px !important}"
84
- ) as app:
85
- gr.Markdown("""
86
- # 📝 Summify Pro
87
- *Secure text summarization powered by Hugging Face*
88
- """)
89
-
90
- with gr.Row():
91
- input_box = gr.Textbox(
92
- label="Your Text",
93
- placeholder="Paste article, essay, or document...",
94
- lines=8,
95
- max_lines=20,
96
- elem_id="input-box"
97
  )
98
- output_box = gr.Textbox(
99
- label="Summary",
100
- interactive=False,
101
- lines=8,
102
- elem_id="output-box"
 
 
 
 
 
103
  )
104
-
105
- status = gr.Textbox(
106
- label="System Status",
107
- interactive=False,
108
- elem_id="status-box"
109
- )
110
-
111
- submit_btn = gr.Button(
112
- "Generate Summary",
113
- variant="primary",
114
- elem_id="submit-btn"
115
- )
116
- clear_btn = gr.Button("Clear")
117
-
118
- submit_btn.click(
119
- fn=summarizer.summarize,
120
- inputs=input_box,
121
- outputs=[output_box, status]
122
- )
123
- clear_btn.click(
124
- lambda: ["", "", ""],
125
- outputs=[input_box, output_box, status]
126
- )
127
 
128
- # Launch configuration
129
- if __name__ == "__main__":
130
- app.launch(
131
- server_name="0.0.0.0",
132
- server_port=7860,
133
- show_error=True,
134
- debug=True
135
- )
 
1
  import os
2
  import requests
3
  import gradio as gr
 
4
 
5
+ # Debug token loading - SAFE (only shows metadata)
6
+ TOKEN = os.getenv("HF_API_TOKEN", "").strip()
7
+ print("🛠️ DEBUG: Token exists?", bool(TOKEN))
8
+ print("🛠️ DEBUG: Token starts with hf_?", TOKEN.startswith("hf_"))
9
+ print("🛠️ DEBUG: Token length:", len(TOKEN))
10
 
11
+ def summarize(text):
12
+ try:
13
+ if not TOKEN.startswith("hf_"):
14
+ return "🔴 Invalid token format", "❌ Critical Error"
15
 
16
+ # Test API connection
17
+ test_response = requests.get(
18
+ "https://api-inference.huggingface.co/status",
19
+ headers={"Authorization": f"Bearer {TOKEN}"},
20
+ timeout=10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  )
22
+
23
+ if test_response.status_code == 401:
24
+ return "🔴 Token rejected by API", "❌ Auth Failed"
25
+
26
+ # Main request
27
+ response = requests.post(
28
+ "https://api-inference.huggingface.co/models/facebook/bart-large-cnn",
29
+ headers={"Authorization": f"Bearer {TOKEN}"},
30
+ json={"inputs": text[:2000], "parameters": {"max_length": 100}},
31
+ timeout=20
32
  )
33
+
34
+ if response.ok:
35
+ return response.json()[0]['summary_text'], " Success"
36
+ return f"⚠️ API Error {response.status_code}", "❌ Failed"
37
+
38
+ except Exception as e:
39
+ return f"🚨 Error: {str(e)}", "⚠️ Exception"
40
+
41
+ # Minimal UI
42
+ with gr.Blocks() as app:
43
+ gr.Markdown("## 🚀 Debug Mode Summify")
44
+ with gr.Row():
45
+ input_txt = gr.Textbox(label="Input", placeholder="Type here...")
46
+ output_txt = gr.Textbox(label="Summary", interactive=False)
47
+ status = gr.Textbox(label="Debug Status")
48
+ gr.Button("Summarize").click(summarize, input_txt, [output_txt, status])
 
 
 
 
 
 
 
49
 
50
+ app.launch(server_name="0.0.0.0", server_port=7860)