File size: 11,338 Bytes
7a71a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66b71d0
 
 
7a71a16
 
 
66b71d0
 
 
 
 
 
 
 
 
 
 
7a71a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66b71d0
 
 
 
 
 
 
 
 
 
 
7a71a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""
DGaze - Simplified Gradio App for Hugging Face Spaces
"""

import os
import gradio as gr
import requests
import time
import uuid

# Import our modular components
from components.verification_result import format_verification_results

# Simple configuration for Spaces
class SpacesSettings:
    def __init__(self):
        # For Spaces deployment, we'll use environment variables
        self.API_BASE_URL = os.getenv("API_BASE_URL")
        if not self.API_BASE_URL:
            raise ValueError("API_BASE_URL environment variable is required")
        self.API_ENDPOINT = f"{self.API_BASE_URL}/api/verify"
        self.HEALTH_ENDPOINT = f"{self.API_BASE_URL}/api/health"

# Initialize settings with error handling
try:
    settings = SpacesSettings()
except ValueError as e:
    # Create a dummy settings object for graceful degradation
    class DummySettings:
        API_BASE_URL = None
        API_ENDPOINT = None
        HEALTH_ENDPOINT = None
    settings = DummySettings()
    print(f"Warning: {e}")

# Simple API client for Spaces
class SimpleAPIClient:
    def __init__(self):
        self.base_url = settings.API_BASE_URL
        self.verify_endpoint = settings.API_ENDPOINT
        self.health_endpoint = settings.HEALTH_ENDPOINT
    
    def verify_news(self, text: str) -> dict:
        """Verify news using the backend API."""
        try:
            payload = {"text": text}
            response = requests.post(
                self.verify_endpoint,
                json=payload,
                timeout=30,
                headers={"Content-Type": "application/json"}
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"API request failed: {str(e)}")
        except Exception as e:
            raise Exception(f"Verification failed: {str(e)}")

api_client = SimpleAPIClient()

# Free trial management for Spaces
trial_tracker = {}
session_timestamps = {}

def get_session_id(request) -> str:
    """Get session ID from Gradio request."""
    # For Spaces, we'll use a simpler session tracking
    if hasattr(request, 'headers'):
        # Try to get a unique identifier from headers
        session_id = request.headers.get('x-session-id', f"trial_{uuid.uuid4().hex[:12]}")
    else:
        session_id = f"trial_{uuid.uuid4().hex[:12]}"
    return session_id

def cleanup_old_sessions():
    """Clean up sessions older than 24 hours."""
    current_time = time.time()
    old_sessions = []
    for session_id, timestamp in session_timestamps.items():
        if current_time - timestamp > 86400:  # 24 hours
            old_sessions.append(session_id)
    
    for session_id in old_sessions:
        trial_tracker.pop(session_id, None)
        session_timestamps.pop(session_id, None)

def get_trial_count(session_id: str) -> int:
    """Get current trial verification count."""
    cleanup_old_sessions()
    return trial_tracker.get(session_id, 0)

def increment_trial_count(session_id: str) -> int:
    """Increment and return trial verification count."""
    current_count = trial_tracker.get(session_id, 0)
    new_count = current_count + 1
    trial_tracker[session_id] = new_count
    session_timestamps[session_id] = time.time()
    return new_count

def verify_news_with_trial_check(input_text: str, request: gr.Request) -> str:
    """Verification function with free trial tracking for Spaces."""
    if not input_text.strip():
        return "Please enter some text or URL to verify"
    
    # Check if API_BASE_URL is configured
    if not settings.API_BASE_URL:
        return """
        <div style="background: #f8d7da; border: 1px solid #f5c6cb; padding: 1rem; margin: 1rem 0; border-radius: 4px;">
            <p style="margin: 0; color: #721c24; font-size: 0.9rem;">
                ⚠️ <strong>Configuration Error:</strong> API_BASE_URL environment variable is not set. 
                Please configure it in the Space settings.
            </p>
        </div>
        """
    
    try:
        # Get session ID for trial tracking
        session_id = get_session_id(request)
        current_count = get_trial_count(session_id)
        
        # Check trial limits (2 free trials)
        if current_count >= 2:
            return """
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                        padding: 2rem; border-radius: 12px; color: white; text-align: center;
                        box-shadow: 0 10px 25px rgba(0,0,0,0.1);">
                <h2 style="margin: 0 0 1rem 0; font-size: 1.5rem; color: white !important;">πŸ” Free Trial Limit Reached</h2>
                <p style="margin: 0 0 1.5rem 0; opacity: 0.9; color: white !important;">
                    You've used your 2 free verifications! To continue using DGaze:
                </p>
                <ul style="text-align: left; margin: 1rem 0; color: white !important;">
                    <li>Deploy your own instance with unlimited access</li>
                    <li>Visit our website for more information</li>
                    <li>Contact us for enterprise solutions</li>
                </ul>
                <p style="margin: 1.5rem 0 0 0; font-size: 0.9rem; opacity: 0.8; color: white !important;">
                    Thank you for trying DGaze!
                </p>
            </div>
            """
        
        # Increment trial count
        new_count = increment_trial_count(session_id)
        remaining = 2 - new_count
        
        # Proceed with verification
        data = api_client.verify_news(input_text)
        result = format_verification_results(data)
        
        # Add trial info
        trial_info = f"""
        <div style="background: #e3f2fd; border-left: 4px solid #2196f3; padding: 1rem; margin: 1rem 0; border-radius: 4px;">
            <p style="margin: 0; color: #1565c0; font-size: 0.9rem;">
                ⚑ Free Trial: <strong>{remaining} verification{'s' if remaining != 1 else ''} remaining</strong>
                {' β€’ Deploy your own instance for unlimited access!' if remaining > 0 else ''}
            </p>
        </div>
        """
        result = trial_info + result
        return result
        
    except Exception as e:
        return f"Error: {str(e)}"

# Create Gradio interface for Spaces
def create_spaces_interface():
    """Create the main interface for Hugging Face Spaces."""
    with gr.Blocks(
        title="DGaze - News Verification",
        theme=gr.themes.Soft(),
        css="""
        .main-header {
            text-align: center;
            padding: 2rem 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            margin-bottom: 2rem;
        }
        .main-header h1 {
            color: white !important;
            font-size: 3rem;
            margin: 0;
        }
        .main-header p {
            color: white !important;
            font-size: 1.2rem;
            opacity: 0.9;
        }
        """
    ) as demo:
        
        # Header
        gr.HTML("""
        <div class="main-header">
            <h1>πŸ” DGaze</h1>
            <p>Advanced News Verification System</p>
            <p style="font-size: 1rem; opacity: 0.8;">Free Trial: 2 verifications β€’ Deploy your own for unlimited access</p>
        </div>
        """)
        
        # Info section
        gr.Markdown("""
        ### How it works:
        1. **Paste news text** or **URL** in the input box below
        2. **Click "Verify News"** to analyze the content
        3. **Get detailed results** including credibility score and analysis
        
        *Try our free demo with 2 verifications, then deploy your own instance for unlimited access!*
        """)
        
        # Main interface
        with gr.Row():
            with gr.Column(scale=2):
                input_text = gr.Textbox(
                    label="Enter news text or URL to verify",
                    placeholder="Paste news article text or URL here...",
                    lines=8,
                    max_lines=15
                )
                
                submit_btn = gr.Button("πŸ” Verify News", variant="primary", size="lg")
            
            with gr.Column(scale=3):
                output_html = gr.HTML(label="Verification Results")
        
        # Handle submission
        submit_btn.click(
            fn=verify_news_with_trial_check, 
            inputs=input_text, 
            outputs=output_html
        )
        input_text.submit(
            fn=verify_news_with_trial_check, 
            inputs=input_text, 
            outputs=output_html
        )
        
        # Examples
        gr.Examples(
            examples=[
                ["""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"""],
                ["""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"""]
            ],
            inputs=[input_text],
            label="Example News Articles to Verify"
        )
        
        # Footer
        gr.Markdown("""
        ---
        ### About DGaze
        DGaze is an advanced news verification system that helps you identify potentially misleading or false information.
        
        **Features:**
        - Real-time news analysis
        - Credibility scoring
        - Source verification
        - Detailed explanations
        
        **Deploy Your Own:**
        - Get unlimited verifications
        - Customize for your needs
        - Enterprise support available
        
        ---
        *Built with ❀️ using Gradio and Hugging Face Spaces*
        """)
    
    return demo

# Launch the app
if __name__ == "__main__":
    demo = create_spaces_interface()
    demo.launch()