Spaces:
Sleeping
Sleeping
| import { NextRequest, NextResponse } from "next/server"; | |
| import { createClient } from "@/lib/supabase/server"; | |
| const GRADIO_URL = process.env.CLAUSEGUARD_GRADIO_URL || "https://gaurv007-clauseguard.hf.space"; | |
| export async function POST(req: NextRequest) { | |
| try { | |
| const supabase = await createClient(); | |
| const { data: { user } } = await supabase.auth.getUser(); | |
| if (!user) { | |
| return NextResponse.json({ error: "Unauthorized. Please log in." }, { status: 401 }); | |
| } | |
| const body = await req.json(); | |
| let { text_a, text_b } = body; | |
| if (!text_a || !text_b || text_a.trim().length < 50 || text_b.trim().length < 50) { | |
| return NextResponse.json( | |
| { error: "Both contracts must have at least 50 characters." }, | |
| { status: 400 } | |
| ); | |
| } | |
| // Sanitize basically | |
| text_a = text_a.replace(/</g, "<").replace(/>/g, ">"); | |
| text_b = text_b.replace(/</g, "<").replace(/>/g, ">"); | |
| // Call Gradio Space API | |
| const submitRes = await fetch(`${GRADIO_URL}/gradio_api/call/run_comparison`, { | |
| method: "POST", | |
| headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ data: [text_a, text_b] }), | |
| }); | |
| if (!submitRes.ok) { | |
| throw new Error(`Gradio submit failed: ${submitRes.status}`); | |
| } | |
| const { event_id } = await submitRes.json(); | |
| if (!event_id) throw new Error("No event_id from Gradio"); | |
| // Poll for result | |
| const resultRes = await fetch( | |
| `${GRADIO_URL}/gradio_api/call/run_comparison/${event_id}`, | |
| { headers: { Accept: "text/event-stream" } } | |
| ); | |
| if (!resultRes.ok) { | |
| throw new Error(`Gradio result failed: ${resultRes.status}`); | |
| } | |
| const resultText = await resultRes.text(); | |
| const dataMatch = resultText.match(/event:\s*complete\s*\ndata:\s*(.+)/); | |
| if (!dataMatch) throw new Error("No complete event from Gradio"); | |
| const gradioData = JSON.parse(dataMatch[1]); | |
| // gradioData[0] = comparison HTML | |
| // gradioData[1] = raw JSON comparison data | |
| const comparisonResult = gradioData[1]; | |
| if (typeof comparisonResult === "object" && comparisonResult !== null) { | |
| return NextResponse.json(comparisonResult); | |
| } | |
| // If it's a string (JSON stringified), parse it | |
| if (typeof comparisonResult === "string") { | |
| return NextResponse.json(JSON.parse(comparisonResult)); | |
| } | |
| throw new Error("Unexpected comparison result format"); | |
| } catch (error: any) { | |
| console.error("Compare error:", error.message); | |
| return NextResponse.json({ error: error.message || "Comparison failed" }, { status: 500 }); | |
| } | |
| } | |