File size: 3,931 Bytes
942a690
 
c56dc42
 
43ae172
942a690
 
 
 
c56dc42
 
 
 
 
 
 
 
 
 
 
 
942a690
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43ae172
 
 
 
c56dc42
 
43ae172
 
 
 
 
 
 
 
 
942a690
 
 
 
 
 
 
 
 
c56dc42
 
 
 
 
 
942a690
c56dc42
942a690
cd022f7
942a690
 
cd022f7
 
942a690
 
cd022f7
 
 
 
 
 
 
 
 
 
 
 
942a690
 
 
 
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
# main.py
from fastapi import FastAPI
from pydantic import BaseModel, Field, HttpUrl,root_validator, validator
from typing import List, Optional
from fastapi.middleware.cors import CORSMiddleware
# -- 1. Define Pydantic Models for Data Validation --

# This model defines the structure of the incoming request JSON
class RequestPacket(BaseModel):
    # 1. Make fields optional by using Optional[<type>] and setting default to None
    text: Optional[str] = None
    url: Optional[HttpUrl] = None
    image: Optional[str] = None

    # 2. Add a validator to ensure at least one field is provided
    @root_validator(pre=False, skip_on_failure=True)
    def check_at_least_one_field_present(cls, values):
        """Ensure at least one of text, url, or image is provided."""
        if not any(values.values()):
            raise ValueError('At least one of the fields (text, url, image) must be provided.')
        return values

# These models define the structure of the outgoing response JSON
class Analysis(BaseModel):
    isMisinformation: bool
    reasoning: str
    confidenceScore: float = Field(
        ..., 
        ge=0,  # Must be greater than or equal to 0
        le=1   # Must be less than or equal to 1
    )

class Source(BaseModel):
    name: str
    description: str

class ResponsePacket(BaseModel):
    summary: str
    analysis: Analysis
    sources: List[Source]

# -- 2. Create the FastAPI Application --
app = FastAPI(
    title="Backend Checker API",
    description="A mock API to validate requests and send simulated responses."
)
# ⬇️ ADD THIS MIDDLEWARE SECTION
# This tells the API to accept requests from your frontend
origins = [
    "https://your-firebase-app-name.web.app", # Your production frontend URL
    "http://localhost:3000", 
    "https://6000-firebase-studio-1758293511500.cluster-6dx7corvpngoivimwvvljgokdw.cloudworkstations.dev/"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"], # Allows all methods, including POST
    allow_headers=["*"], # Allows all headers
)

# -- 3. Define the API Endpoint --
@app.post("/check", response_model=ResponsePacket)
async def check_request_format(request: RequestPacket):
    """
    This endpoint receives a request packet, validates its structure,
    and returns a mock analysis response.
    """
    print("✅ Request received and successfully validated!")
    if request.text:
        print(f"Text received (length): {len(request.text)}")
    if request.url:
        print(f"URL received: {request.url}")
    if request.image:
        print(f"Image data received, starts with: {request.image[:30]}...")

    # The mock response logic remains the same
    mock_response = ResponsePacket(
        summary="The provided content appears to be a satirical piece, but it is being shared in contexts that suggest it is factual news, which can mislead audiences.",
        analysis=Analysis(
            isMisinformation=True,
            reasoning="The core claim originates from a known satirical website. While not intentionally malicious, its presentation lacks clear satirical markers, leading to its spread as genuine misinformation.",
            confidenceScore=0.95
        ),
        sources=[
            Source(
                name="The Daily Satire Times",
                description="The original publisher of the article, which is officially listed as a satirical publication."
            ),
            Source(
                name="Cross-Platform Fact-Check Initiative",
                description="Shows multiple instances where this article was shared on social media without satire labels, leading to user confusion."
            ),
            Source(
                name="Media Literacy Hub",
                description="Provides guidelines on how to identify satire versus fake news."
            )
        ]
    )
    
    return mock_response