File size: 8,393 Bytes
50a8ea3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import os
import sys
import tempfile
from pathlib import Path

from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from gradio_client import Client, handle_file
from pydantic import BaseModel


# ============================================================
# PROJECT PATH
# ============================================================

PROJECT_ROOT = Path(__file__).resolve().parent.parent

# Allow Python to find:
# oosc/rights_navigator/
sys.path.append(str(PROJECT_ROOT))


# ============================================================
# RIGHTS NAVIGATOR
# ============================================================

from rights_navigator.rights_navigator import get_rights_response


# ============================================================
# FASTAPI APP
# ============================================================

app = FastAPI(
    title="Civic & RTI Hub API"
)


# ============================================================
# CORS
# ============================================================

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# ============================================================
# HUGGING FACE TOKEN
# ============================================================

HF_TOKEN = os.getenv("HF_TOKEN")


# ============================================================
# HUGGING FACE SPACES
# ============================================================

# Friend's PDF Simplifier
SIMPLIFIER_SPACE_ID = "Ronak0/RC"

# Friend's RTI Drafter
DRAFTER_SPACE_ID = "Ronak0/rti-drafter"


# ============================================================
# CLIENTS
# ============================================================

# IMPORTANT:
# Do NOT connect to the Spaces when the server starts.
#
# They will be initialized only when /simplify or /draft
# is actually called.

simplifier_client = None
drafter_client = None


# ============================================================
# LAZY LOAD - PDF SIMPLIFIER
# ============================================================

def get_simplifier_client():

    global simplifier_client

    if simplifier_client is None:

        print("Connecting to PDF Simplifier Space...")

        simplifier_client = Client(
            SIMPLIFIER_SPACE_ID,
            token=HF_TOKEN
        )

        print("PDF Simplifier connected.")

    return simplifier_client


# ============================================================
# LAZY LOAD - RTI DRAFTER
# ============================================================

def get_drafter_client():

    global drafter_client

    if drafter_client is None:

        print("Connecting to RTI Drafter Space...")

        drafter_client = Client(
            DRAFTER_SPACE_ID,
            token=HF_TOKEN
        )

        print("RTI Drafter connected.")

    return drafter_client


# ============================================================
# REQUEST MODELS
# ============================================================

class DraftRequest(BaseModel):
    prompt: str


class RightsRequest(BaseModel):
    grievance: str


# ============================================================
# HEALTH CHECK
# ============================================================

@app.get("/")
async def root():

    return {
        "status": "online",
        "service": "Civic & RTI Hub API",
        "endpoints": [
            "/simplify",
            "/draft",
            "/rights"
        ]
    }


# ============================================================
# PDF SIMPLIFIER
# ============================================================

@app.post("/simplify")
@app.post("/api/simplify")
async def simplify_pdf(

    file: UploadFile = File(...)

):

    # --------------------------------------------------------
    # Validate PDF
    # --------------------------------------------------------

    if not file.filename.lower().endswith(".pdf"):

        raise HTTPException(
            status_code=400,
            detail="Must be a PDF file."
        )


    # --------------------------------------------------------
    # Save uploaded PDF temporarily
    # --------------------------------------------------------

    with tempfile.NamedTemporaryFile(
        delete=False,
        suffix=".pdf"
    ) as tmp:

        tmp.write(
            await file.read()
        )

        tmp_path = tmp.name


    try:

        # ----------------------------------------------------
        # Connect only when this endpoint is used
        # ----------------------------------------------------

        client = get_simplifier_client()


        # ----------------------------------------------------
        # Call friend's Hugging Face Space
        # ----------------------------------------------------

        raw_result = client.predict(
            pdf_file=handle_file(tmp_path),
            api_name="/simplify_document"
        )


        # ----------------------------------------------------
        # Format response
        # ----------------------------------------------------

        points = [
            p.strip()
            for p in raw_result.split("\n\n")
            if p.strip()
        ]


        return {
            "simplified_points": points
        }


    except Exception as e:

        raise HTTPException(
            status_code=500,
            detail=f"PDF simplifier error: {str(e)}"
        )


    finally:

        # ----------------------------------------------------
        # Delete temporary PDF
        # ----------------------------------------------------

        if os.path.exists(tmp_path):

            os.remove(tmp_path)


# ============================================================
# RTI DRAFTER
# ============================================================

@app.post("/draft")
@app.post("/api/draft")
async def draft_rti_endpoint(

    request: DraftRequest

):

    # --------------------------------------------------------
    # Validate request
    # --------------------------------------------------------

    if not request.prompt.strip():

        raise HTTPException(
            status_code=400,
            detail="Prompt cannot be empty."
        )


    try:

        # ----------------------------------------------------
        # Connect only when this endpoint is used
        # ----------------------------------------------------

        client = get_drafter_client()


        # ----------------------------------------------------
        # Call friend's Hugging Face Space
        # ----------------------------------------------------

        draft_result = client.predict(
            user_prompt=request.prompt,
            api_name="/draft_rti"
        )


        return {
            "draft": draft_result
        }


    except Exception as e:

        raise HTTPException(
            status_code=500,
            detail=f"RTI drafter error: {str(e)}"
        )


# ============================================================
# RIGHTS NAVIGATOR
# ============================================================

@app.post("/rights")
@app.post("/api/rights")
async def rights_navigator_endpoint(

    request: RightsRequest

):

    # --------------------------------------------------------
    # Validate grievance
    # --------------------------------------------------------

    if not request.grievance.strip():

        raise HTTPException(
            status_code=400,
            detail="Grievance cannot be empty."
        )


    try:

        # ----------------------------------------------------
        # Call YOUR Rights Navigator
        # ----------------------------------------------------

        result = get_rights_response(
            request.grievance
        )


        return result


    except Exception as e:

        raise HTTPException(
            status_code=500,
            detail=f"Rights Navigator error: {str(e)}"
        )