lightmate commited on
Commit
7a71a16
Β·
verified Β·
1 Parent(s): 0a8d4fb

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +253 -0
app.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ DGaze - Simplified Gradio App for Hugging Face Spaces
3
+ """
4
+
5
+ import os
6
+ import gradio as gr
7
+ import requests
8
+ import time
9
+ import uuid
10
+
11
+ # Import our modular components
12
+ from components.verification_result import format_verification_results
13
+
14
+ # Simple configuration for Spaces
15
+ class SpacesSettings:
16
+ def __init__(self):
17
+ # For Spaces deployment, we'll use environment variables
18
+ self.API_BASE_URL = os.getenv("API_BASE_URL", "https://your-backend-api.com")
19
+ self.API_ENDPOINT = f"{self.API_BASE_URL}/api/verify"
20
+ self.HEALTH_ENDPOINT = f"{self.API_BASE_URL}/api/health"
21
+
22
+ settings = SpacesSettings()
23
+
24
+ # Simple API client for Spaces
25
+ class SimpleAPIClient:
26
+ def __init__(self):
27
+ self.base_url = settings.API_BASE_URL
28
+ self.verify_endpoint = settings.API_ENDPOINT
29
+ self.health_endpoint = settings.HEALTH_ENDPOINT
30
+
31
+ def verify_news(self, text: str) -> dict:
32
+ """Verify news using the backend API."""
33
+ try:
34
+ payload = {"text": text}
35
+ response = requests.post(
36
+ self.verify_endpoint,
37
+ json=payload,
38
+ timeout=30,
39
+ headers={"Content-Type": "application/json"}
40
+ )
41
+ response.raise_for_status()
42
+ return response.json()
43
+ except requests.exceptions.RequestException as e:
44
+ raise Exception(f"API request failed: {str(e)}")
45
+ except Exception as e:
46
+ raise Exception(f"Verification failed: {str(e)}")
47
+
48
+ api_client = SimpleAPIClient()
49
+
50
+ # Free trial management for Spaces
51
+ trial_tracker = {}
52
+ session_timestamps = {}
53
+
54
+ def get_session_id(request) -> str:
55
+ """Get session ID from Gradio request."""
56
+ # For Spaces, we'll use a simpler session tracking
57
+ if hasattr(request, 'headers'):
58
+ # Try to get a unique identifier from headers
59
+ session_id = request.headers.get('x-session-id', f"trial_{uuid.uuid4().hex[:12]}")
60
+ else:
61
+ session_id = f"trial_{uuid.uuid4().hex[:12]}"
62
+ return session_id
63
+
64
+ def cleanup_old_sessions():
65
+ """Clean up sessions older than 24 hours."""
66
+ current_time = time.time()
67
+ old_sessions = []
68
+ for session_id, timestamp in session_timestamps.items():
69
+ if current_time - timestamp > 86400: # 24 hours
70
+ old_sessions.append(session_id)
71
+
72
+ for session_id in old_sessions:
73
+ trial_tracker.pop(session_id, None)
74
+ session_timestamps.pop(session_id, None)
75
+
76
+ def get_trial_count(session_id: str) -> int:
77
+ """Get current trial verification count."""
78
+ cleanup_old_sessions()
79
+ return trial_tracker.get(session_id, 0)
80
+
81
+ def increment_trial_count(session_id: str) -> int:
82
+ """Increment and return trial verification count."""
83
+ current_count = trial_tracker.get(session_id, 0)
84
+ new_count = current_count + 1
85
+ trial_tracker[session_id] = new_count
86
+ session_timestamps[session_id] = time.time()
87
+ return new_count
88
+
89
+ def verify_news_with_trial_check(input_text: str, request: gr.Request) -> str:
90
+ """Verification function with free trial tracking for Spaces."""
91
+ if not input_text.strip():
92
+ return "Please enter some text or URL to verify"
93
+
94
+ try:
95
+ # Get session ID for trial tracking
96
+ session_id = get_session_id(request)
97
+ current_count = get_trial_count(session_id)
98
+
99
+ # Check trial limits (2 free trials)
100
+ if current_count >= 2:
101
+ return """
102
+ <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
103
+ padding: 2rem; border-radius: 12px; color: white; text-align: center;
104
+ box-shadow: 0 10px 25px rgba(0,0,0,0.1);">
105
+ <h2 style="margin: 0 0 1rem 0; font-size: 1.5rem; color: white !important;">πŸ” Free Trial Limit Reached</h2>
106
+ <p style="margin: 0 0 1.5rem 0; opacity: 0.9; color: white !important;">
107
+ You've used your 2 free verifications! To continue using DGaze:
108
+ </p>
109
+ <ul style="text-align: left; margin: 1rem 0; color: white !important;">
110
+ <li>Deploy your own instance with unlimited access</li>
111
+ <li>Visit our website for more information</li>
112
+ <li>Contact us for enterprise solutions</li>
113
+ </ul>
114
+ <p style="margin: 1.5rem 0 0 0; font-size: 0.9rem; opacity: 0.8; color: white !important;">
115
+ Thank you for trying DGaze!
116
+ </p>
117
+ </div>
118
+ """
119
+
120
+ # Increment trial count
121
+ new_count = increment_trial_count(session_id)
122
+ remaining = 2 - new_count
123
+
124
+ # Proceed with verification
125
+ data = api_client.verify_news(input_text)
126
+ result = format_verification_results(data)
127
+
128
+ # Add trial info
129
+ trial_info = f"""
130
+ <div style="background: #e3f2fd; border-left: 4px solid #2196f3; padding: 1rem; margin: 1rem 0; border-radius: 4px;">
131
+ <p style="margin: 0; color: #1565c0; font-size: 0.9rem;">
132
+ ⚑ Free Trial: <strong>{remaining} verification{'s' if remaining != 1 else ''} remaining</strong>
133
+ {' β€’ Deploy your own instance for unlimited access!' if remaining > 0 else ''}
134
+ </p>
135
+ </div>
136
+ """
137
+ result = trial_info + result
138
+ return result
139
+
140
+ except Exception as e:
141
+ return f"Error: {str(e)}"
142
+
143
+ # Create Gradio interface for Spaces
144
+ def create_spaces_interface():
145
+ """Create the main interface for Hugging Face Spaces."""
146
+ with gr.Blocks(
147
+ title="DGaze - News Verification",
148
+ theme=gr.themes.Soft(),
149
+ css="""
150
+ .main-header {
151
+ text-align: center;
152
+ padding: 2rem 0;
153
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
154
+ color: white;
155
+ border-radius: 12px;
156
+ margin-bottom: 2rem;
157
+ }
158
+ .main-header h1 {
159
+ color: white !important;
160
+ font-size: 3rem;
161
+ margin: 0;
162
+ }
163
+ .main-header p {
164
+ color: white !important;
165
+ font-size: 1.2rem;
166
+ opacity: 0.9;
167
+ }
168
+ """
169
+ ) as demo:
170
+
171
+ # Header
172
+ gr.HTML("""
173
+ <div class="main-header">
174
+ <h1>πŸ” DGaze</h1>
175
+ <p>Advanced News Verification System</p>
176
+ <p style="font-size: 1rem; opacity: 0.8;">Free Trial: 2 verifications β€’ Deploy your own for unlimited access</p>
177
+ </div>
178
+ """)
179
+
180
+ # Info section
181
+ gr.Markdown("""
182
+ ### How it works:
183
+ 1. **Paste news text** or **URL** in the input box below
184
+ 2. **Click "Verify News"** to analyze the content
185
+ 3. **Get detailed results** including credibility score and analysis
186
+
187
+ *Try our free demo with 2 verifications, then deploy your own instance for unlimited access!*
188
+ """)
189
+
190
+ # Main interface
191
+ with gr.Row():
192
+ with gr.Column(scale=2):
193
+ input_text = gr.Textbox(
194
+ label="Enter news text or URL to verify",
195
+ placeholder="Paste news article text or URL here...",
196
+ lines=8,
197
+ max_lines=15
198
+ )
199
+
200
+ submit_btn = gr.Button("πŸ” Verify News", variant="primary", size="lg")
201
+
202
+ with gr.Column(scale=3):
203
+ output_html = gr.HTML(label="Verification Results")
204
+
205
+ # Handle submission
206
+ submit_btn.click(
207
+ fn=verify_news_with_trial_check,
208
+ inputs=input_text,
209
+ outputs=output_html
210
+ )
211
+ input_text.submit(
212
+ fn=verify_news_with_trial_check,
213
+ inputs=input_text,
214
+ outputs=output_html
215
+ )
216
+
217
+ # Examples
218
+ gr.Examples(
219
+ examples=[
220
+ ["""BREAKING: Revolutionary AI breakthrough! πŸš€ Scientists at MIT have developed a new quantum AI system that can predict earthquakes with 99.7% accuracy up to 6 months in advance. The system, called "QuakeNet AI", uses quantum computing combined with machine learning to analyze seismic patterns invisible to current technology. Dr. Sarah Chen, lead researcher, claims this could save millions of lives and prevent billions in damages. The technology will be commercially available by 2026 according to insider sources. This comes just weeks after similar breakthroughs in cancer detection AI. What do you think about this amazing discovery? #AI #Earthquake #MIT #Science"""],
221
+ ["""SpaceX conducted another major test for their Starship program yesterday, with Elon Musk claiming on social media that Flight 10 is "ready to revolutionize space travel forever." The company fired up all 33 Raptor engines on their Super Heavy booster at the Starbase facility in Texas. According to various reports and this detailed article (https://www.space.com/space-exploration/launches-spacecraft/spacex-fires-up-super-heavy-booster-ahead-of-starships-10th-test-flight-video), the test was part of preparations for the upcoming 10th test flight. However, some critics argue that SpaceX is moving too fast without proper safety protocols, especially after Flight 9 experienced issues. The FAA is still investigating the previous mission where both the booster and ship were lost. Industry experts remain divided on whether this aggressive testing schedule is beneficial or dangerous for the future of commercial spaceflight. πŸš€ #SpaceX #Starship #Space"""]
222
+ ],
223
+ inputs=[input_text],
224
+ label="Example News Articles to Verify"
225
+ )
226
+
227
+ # Footer
228
+ gr.Markdown("""
229
+ ---
230
+ ### About DGaze
231
+ DGaze is an advanced news verification system that helps you identify potentially misleading or false information.
232
+
233
+ **Features:**
234
+ - Real-time news analysis
235
+ - Credibility scoring
236
+ - Source verification
237
+ - Detailed explanations
238
+
239
+ **Deploy Your Own:**
240
+ - Get unlimited verifications
241
+ - Customize for your needs
242
+ - Enterprise support available
243
+
244
+ ---
245
+ *Built with ❀️ using Gradio and Hugging Face Spaces*
246
+ """)
247
+
248
+ return demo
249
+
250
+ # Launch the app
251
+ if __name__ == "__main__":
252
+ demo = create_spaces_interface()
253
+ demo.launch()