File size: 15,774 Bytes
02d4b13
051660a
 
bfc1376
051660a
19377cf
95d6996
bfc1376
19377cf
 
 
5076b3f
 
ba9555f
19377cf
02d4b13
19377cf
051660a
 
19377cf
 
 
 
051660a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19377cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02d4b13
 
 
 
bfc1376
 
02d4b13
 
 
 
bfc1376
 
 
 
 
02d4b13
 
bfc1376
 
02d4b13
 
 
 
 
bfc1376
 
02d4b13
 
bfc1376
 
02d4b13
bfc1376
 
02d4b13
bfc1376
 
 
 
 
 
 
 
 
02d4b13
 
 
 
 
5076b3f
 
02d4b13
 
 
 
 
 
 
 
 
 
 
 
 
1b7782e
02d4b13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b5753
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b725a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5076b3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba9555f
 
 
051660a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba9555f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5076b3f
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
from fastapi import FastAPI, Depends, HTTPException, BackgroundTasks
from pathlib import Path
import os
import requests
from dotenv import load_dotenv
from sqlalchemy.orm import Session
from database import Base, engine,SessionLocal
from models import User, Log, CtrReport
from schemas import SignupRequest, LoginRequest, LogRequest
from auth import hash_password, verify_password, create_token
from deps import get_db, get_current_user
from config import API_BASE_URL
from models import User, Log, CtrReport, Restaurant, Review
from utils import extract_points


app = FastAPI()
env_path = Path(__file__).resolve().parent / ".env"
load_dotenv(env_path)

Base.metadata.create_all(bind=engine)


def get_representatives(
    texts: list[str],
    eps: float,
    min_samples: int,
    error_label: str
) -> list[str]:
    if not texts:
        return []

    try:
        response = requests.post(
            f"{API_BASE_URL}/get_representatives",
            json={
                "texts": texts,
                "eps": eps,
                "min_samples": min_samples
            },
            timeout=60
        )
    except requests.RequestException as exc:
        raise HTTPException(
            502,
            f"{error_label} service failed: {exc}"
        )

    if response.status_code != 200:
        raise HTTPException(
            502,
            f"{error_label} service error"
        )

    payload = response.json()

    return payload.get("representatives", [])


def requesty_chat(prompt: str) -> str:
    api_key = os.getenv("REQUESTY_API_KEY")
    if not api_key:
        raise HTTPException(500, "Requesty API key not configured")

    base_url = os.getenv(
        "REQUESTY_API_URL",
        "https://router.requesty.ai/v1"
    ).rstrip("/")

    headers = {
        "Authorization": f"Bearer {api_key}",
    }

    referer = os.getenv("REQUESTY_HTTP_REFERER")
    title = os.getenv("REQUESTY_X_TITLE")
    if referer:
        headers["HTTP-Referer"] = referer
    if title:
        headers["X-Title"] = title

    try:
        response = requests.post(
            f"{base_url}/chat/completions",
            headers=headers,
            json={
                "model": "openai/gpt-4o",
                "temperature": 0.2,
                "max_tokens": 256,
                "messages": [
                    {
                        "role": "system",
                        "content": (
                            "You find correlations between insights and reviews. "
                            "Return 3-6 short numbered points, each under 20 words."
                        )
                    },
                    {"role": "user", "content": prompt}
                ]
            },
            timeout=60
        )
    except requests.RequestException as exc:
        raise HTTPException(502, f"Requesty service failed: {exc}")

    if response.status_code != 200:
        detail = response.text.strip()
        if detail:
            raise HTTPException(
                502,
                f"Requesty service error: {detail}"
            )
        raise HTTPException(502, "Requesty service error")

    payload = response.json()
    choices = payload.get("choices", [])
    if not choices:
        raise HTTPException(502, "Requesty service returned no choices")

    message = choices[0].get("message", {})
    content = message.get("content", "")

    return content.strip()


@app.post("/auth/signup")
def signup(data: SignupRequest, db: Session = Depends(get_db)):
    existing = db.query(User).filter(User.email == data.email).first()
    if existing:
        raise HTTPException(400, "Email already exists")

    user = User(
        email=data.email,
        password_hash=hash_password(data.password),
        name=data.name
    )
    db.add(user)
    db.commit()
    db.refresh(user)

    return {"message": "User created"}


@app.post("/auth/login")
def login(data: LoginRequest, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.email == data.email).first()

    if not user or not verify_password(data.password, user.password_hash):
        raise HTTPException(401, "Invalid credentials")

    token = create_token({"user_id": user.id, "name": user.name, "email":user.email})

    return {"access_token": token}




def process_session_logs(user_id: int, session_id: str, db_session_factory):
    db = db_session_factory()

    try:
        session_logs = (
            db.query(Log)
            .filter(
                Log.user_id == user_id,
                Log.session_id == session_id
            )
            .order_by(Log.timestamp.asc())
            .all()
        )

        combined_logs = "\n".join(
            f"{entry.timestamp.isoformat()} : {entry.log}"
            for entry in session_logs
        )

        response = requests.post(
            f"{API_BASE_URL}/processed-logs",
            json={"logs": combined_logs},
            timeout=300   # allow long processing
        )

        if response.status_code != 200:
            print("Processing service error")
            return

        payload = response.json()

        report = CtrReport(
            user_id=user_id,
            session_id=session_id,
            report=payload.get("report", ""),
            insights=payload.get("insights", ""),
            state_flow=payload.get("state_flow", ""),
            suggestions=payload.get("suggestions", "")
        )

        db.add(report)
        db.commit()

    except Exception as e:
        print("Background processing failed:", e)

    finally:
        db.close()


@app.post("/addLog")
def add_log(
    data: LogRequest,
    background_tasks: BackgroundTasks,
    user_id: int = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    log = Log(
        user_id=user_id,
        session_id=data.session_id,
        log=data.log,
        timestamp=data.timestamp
    )
    print(data.log)
    db.add(log)
    db.commit()

    # trigger async/background processing
    if "<END>" in data.log:

        background_tasks.add_task(
            process_session_logs,
            user_id,
            data.session_id,
            SessionLocal   # your DB session factory
        )

    return {"message": "Log stored"}


@app.get("/session-summary")
def get_session_summary(
    session_id: str,
    db: Session = Depends(get_db)
):

    logs = (
        db.query(Log)
        .filter(Log.session_id == session_id)
        .order_by(Log.timestamp.asc())
        .all()
    )

    report = (
        db.query(CtrReport)
        .filter(CtrReport.session_id == session_id)
        .order_by(CtrReport.id.desc())
        .first()
    )

    return {
        "session_id": session_id,
        "logs_count": len(logs),
        "logs": [
            {
                "id": entry.id,
                "log": entry.log,
                "timestamp": entry.timestamp
            }
            for entry in logs
        ],
        "report": report.report if report else "",
        "insights": report.insights if report else "",
        "suggestions": report.suggestions if report else "",
        "state_flow": report.state_flow if report else ""
    }


@app.get("/sessionid_list")
def get_sessionid_list(db: Session = Depends(get_db)):

    rows = (
        db.query(CtrReport.session_id)
        .distinct()
        .order_by(CtrReport.session_id.asc())
        .all()
    )

    session_ids = [row[0] for row in rows]

    return {
        "count": len(session_ids),
        "session_ids": session_ids
    }

@app.get("/restaurants")
def get_restaurants(db: Session = Depends(get_db)):

    restaurants = db.query(Restaurant).all()

    result = []

    for r in restaurants:
        result.append({
            "id": r.id,
            "name": r.name,
            "cuisine": r.cuisine,
            "location": r.location,
            "price_range": r.price_range,
            "avg_rating": r.avg_rating,
            "description": r.description
        })

    return {
        "count": len(result),
        "restaurants": result
    }


@app.get("/restaurants/{restaurant_id}/reviews")
def get_restaurant_reviews(
    restaurant_id: int,
    db: Session = Depends(get_db)
):

    restaurant = (
        db.query(Restaurant)
        .filter(Restaurant.id == restaurant_id)
        .first()
    )

    if not restaurant:
        raise HTTPException(404, "Restaurant not found")

    reviews = (
        db.query(Review)
        .filter(Review.restaurant_id == restaurant_id)
        .order_by(Review.created_at.desc())
        .all()
    )

    result = []

    for review in reviews:
        result.append({
            "id": review.id,
            "user_name": review.user_name,
            "rating": review.rating,
            "review": review.review,
            "created_at": review.created_at
        })

    return {
        "restaurant": {
            "id": restaurant.id,
            "name": restaurant.name,
            "cuisine": restaurant.cuisine,
            "location": restaurant.location,
            "avg_rating": restaurant.avg_rating
        },
        "total_reviews": len(result),
        "reviews": result
    }

@app.get("/restaurants/{restaurant_id}/get-few-reviews")
def get_few_reviews(
    restaurant_id: int,
    eps: float = 0.55,
    min_samples: int = 2,
    db: Session = Depends(get_db)
):

    restaurant = (
        db.query(Restaurant)
        .filter(Restaurant.id == restaurant_id)
        .first()
    )

    if not restaurant:
        raise HTTPException(404, "Restaurant not found")

    reviews = (
        db.query(Review)
        .filter(Review.restaurant_id == restaurant_id)
        .all()
    )

    if not reviews:
        return {
            "restaurant_id": restaurant_id,
            "restaurant_name": restaurant.name,
            "total_reviews": 0,
            "selected_reviews": []
        }

    review_texts = [r.review for r in reviews]

    try:
        response = requests.post(
            f"{API_BASE_URL}/get_representatives",
            json={
                "texts": review_texts,
                "eps": eps,
                "min_samples": min_samples
            },
            timeout=60
        )

    except requests.RequestException as exc:
        raise HTTPException(
            502,
            f"Representative review service failed: {exc}"
        )

    if response.status_code != 200:
        raise HTTPException(
            502,
            "Representative review service error"
        )

    payload = response.json()

    representative_texts = payload.get("representatives", [])

    selected_reviews = []

    for text in representative_texts:

        matching_review = next(
            (r for r in reviews if r.review == text),
            None
        )

        if matching_review:
            selected_reviews.append({
                "id": matching_review.id,
                "user_name": matching_review.user_name,
                "rating": matching_review.rating,
                "review": matching_review.review,
                "created_at": matching_review.created_at
            })

    return {
        "restaurant_id": restaurant.id,
        "restaurant_name": restaurant.name,
        "total_reviews": len(reviews),
        "selected_count": len(selected_reviews),
        "selected_reviews": selected_reviews
    }


@app.get("/correlated-review-insights")
def correlated_review_insights(
    restaurant_id: int,
    eps: float = 0.41,
    min_samples: int = 2,
    db: Session = Depends(get_db)
):

    restaurant = (
        db.query(Restaurant)
        .filter(Restaurant.id == restaurant_id)
        .first()
    )

    if not restaurant:
        raise HTTPException(404, "Restaurant not found")

    reviews = (
        db.query(Review)
        .filter(Review.restaurant_id == restaurant_id)
        .all()
    )

    reports = (
        db.query(CtrReport)
        .order_by(CtrReport.id.desc())
        .all()
    )

    if not reviews or not reports:
        return {
            "restaurant_id": restaurant.id,
            "restaurant_name": restaurant.name,
            "correlation_points": []
        }

    review_texts = [r.review for r in reviews]

    all_points = []
    for report in reports:
        if not report.insights:
            continue
        all_points.extend(extract_points(report.insights))

    unique_points = list(dict.fromkeys(all_points))

    if not unique_points:
        return {
            "restaurant_id": restaurant.id,
            "restaurant_name": restaurant.name,
            "correlation_points": []
        }

    representative_reviews = get_representatives(
        review_texts,
        eps=eps,
        min_samples=min_samples,
        error_label="Representative review"
    )

    representative_insights = get_representatives(
        unique_points,
        eps=eps,
        min_samples=min_samples,
        error_label="Representative insight"
    )

    trimmed_reviews = representative_reviews[:25]
    trimmed_insights = representative_insights[:25]

    prompt = (
        "Insights:\n"
        + "\n".join(f"- {point}" for point in trimmed_insights)
        + "\n\nReviews:\n"
        + "\n".join(f"- {text}" for text in trimmed_reviews)
        + "\n\nCorrelate them in short numbered points."
    )

    content = requesty_chat(prompt)

    correlation_points = extract_points(content)

    if not correlation_points:
        correlation_points = [
            line.strip("- ").strip()
            for line in content.splitlines()
            if line.strip()
        ]

    if not correlation_points and content:
        correlation_points = [content]

    cleaned_points = []
    for point in correlation_points[:6]:
        cleaned = point.strip()
        if len(cleaned) > 200:
            cleaned = cleaned[:197].rstrip() + "..."
        cleaned_points.append(cleaned)

    return {
        "restaurant_id": restaurant.id,
        "restaurant_name": restaurant.name,
        "reviews_considered": len(trimmed_reviews),
        "insights_considered": len(trimmed_insights),
        "correlation_points": cleaned_points
    }



@app.get("/few-insights")
def get_all_insights(
    eps: float = 0.41,
    min_samples: int = 2,
    db: Session = Depends(get_db)
):

    reports = (
        db.query(CtrReport)
        .order_by(CtrReport.id.desc())
        .all()
    )

    if not reports:
        return {
            "count": 0,
            "insights": [],
            "selected_insights": []
        }

    # flatten all insight points
    all_points = []

    for report in reports:

        if not report.insights:
            continue

        extracted = extract_points(report.insights)

        all_points.extend(extracted)

    # remove duplicates while preserving order
    unique_points = list(dict.fromkeys(all_points))

    selected_insights = []

    if unique_points:

        try:
            response = requests.post(
                f"{API_BASE_URL}/get_representatives",
                json={
                    "texts": unique_points,
                    "eps": eps,
                    "min_samples": min_samples
                },
                timeout=60
            )

        except requests.RequestException as exc:
            raise HTTPException(
                502,
                f"Representative insight service failed: {exc}"
            )

        if response.status_code != 200:
            raise HTTPException(
                502,
                "Representative insight service error"
            )

        payload = response.json()

        selected_insights = payload.get(
            "representatives",
            []
        )

    return {
        "count": len(selected_insights),
        "selected_insights": selected_insights
    }