-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
1739 lines (1440 loc) · 57.2 KB
/
api_server.py
File metadata and controls
1739 lines (1440 loc) · 57.2 KB
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Baarn Raadsinformatie REST API Server
FastAPI server die dezelfde functionaliteit biedt als de MCP server,
maar via REST endpoints. Geschikt voor ChatGPT Actions en andere integraties.
Authenticatie via X-API-Key header.
"""
import base64
import os
from contextlib import asynccontextmanager
from datetime import date, timedelta
from typing import Optional
from fastapi import FastAPI, HTTPException, Query, Depends, Security, UploadFile, File, Form
from fastapi.security import APIKeyHeader
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
from core.config import Config
from core.database import get_database
from core.document_index import get_document_index
from core.coalitie_tracker import get_coalitie_tracker
from providers.meeting_provider import get_meeting_provider
from providers.document_provider import get_document_provider
from providers.search_sync_provider import get_search_sync_provider
from providers.document_generator import get_document_generator
from providers.election_program_provider import get_election_program_provider
from providers.standpunt_provider import get_standpunt_provider
from providers.visit_report_provider import get_visit_report_provider
from shared.logging_config import get_logger
logger = get_logger(__name__)
# API Key authentication
API_KEY_NAME = "X-API-Key"
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
def get_api_key() -> str:
"""Get API key from environment."""
return os.getenv("API_KEY", "baarn-api-key-change-me")
async def verify_api_key(api_key: str = Security(api_key_header)) -> str:
"""Verify API key from header."""
if not api_key:
raise HTTPException(
status_code=401,
detail="API key required. Provide X-API-Key header."
)
if api_key != get_api_key():
raise HTTPException(status_code=403, detail="Invalid API key")
return api_key
# Track if initial sync is done
_initial_sync_done = False
async def perform_initial_sync():
"""Perform initial data sync if database is empty."""
global _initial_sync_done
if _initial_sync_done or not Config.AUTO_SYNC_ENABLED:
return
db = get_database()
stats = db.get_statistics()
if stats.get('meetings', 0) == 0:
logger.info('Database empty - performing initial sync...')
meeting_provider = get_meeting_provider()
doc_provider = get_document_provider()
meeting_provider.sync_gremia()
date_from = (date.today() - timedelta(days=Config.AUTO_SYNC_DAYS)).isoformat()
meetings, docs = meeting_provider.sync_meetings(
date_from=date_from,
full_details=True
)
logger.info(f'Initial sync: {meetings} meetings, {docs} documents')
if Config.AUTO_DOWNLOAD_DOCS:
logger.info('Downloading documents...')
success, failed = doc_provider.download_pending_documents()
logger.info(f'Downloaded {success} documents, {failed} failed')
doc_provider.extract_all_text()
if Config.AUTO_INDEX_DOCS:
logger.info('Indexing documents for semantic search...')
index = get_document_index()
indexed, chunks = index.index_all_documents()
logger.info(f'Indexed {indexed} documents, {chunks} chunks')
_initial_sync_done = True
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Startup and shutdown events."""
logger.info(f'Starting {Config.SERVER_NAME} REST API v{Config.SERVER_VERSION}')
await perform_initial_sync()
yield
logger.info('Shutting down REST API')
# Initialize FastAPI with OpenAPI config for ChatGPT Custom GPT
app = FastAPI(
title="Baarn Raadsinformatie API",
description="""
REST API voor toegang tot politieke documenten en vergaderingen van gemeente Baarn.
## Features
- **Vergaderingen**: Ophalen van gemeenteraads- en commissievergaderingen
- **Documenten**: Doorzoeken van raadsstukken (keyword en semantisch)
- **Gremia**: Lijst van commissies en de gemeenteraad
- **Annotaties**: Notities toevoegen en ophalen
- **Coalitieakkoord**: Tracking van coalitieafspraken en voortgang
## Authenticatie
Alle endpoints vereisen een API key via de `X-API-Key` header.
## Gebruik met ChatGPT
Deze API is ontworpen voor ChatGPT Custom GPT Actions.
Importeer de OpenAPI spec via `/openapi.json`.
""",
version=Config.SERVER_VERSION,
lifespan=lifespan,
contact={
"name": "Baarn Raadsinformatie",
"url": "https://github.com/tiemenrtuinstra/baarn-raadsinformatie"
},
license_info={
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
},
servers=[
{"url": "http://localhost:8000", "description": "Local development"},
]
)
# CORS middleware voor browser toegang
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def _parse_list(value: Optional[str]) -> Optional[list[str]]:
"""Parse comma-separated list values from form inputs."""
if not value:
return None
items = [item.strip() for item in value.split(',') if item.strip()]
return items or None
# ==================== Pydantic Models ====================
class MeetingBase(BaseModel):
id: int
title: str
date: str
gremium: Optional[str] = None
class MeetingsResponse(BaseModel):
count: int
meetings: list[MeetingBase]
class AgendaItem(BaseModel):
id: int
title: str
description: Optional[str] = None
class MeetingDetail(BaseModel):
id: int
title: str
date: str
location: Optional[str] = None
agenda_items: list[dict]
documents: list[dict]
class DocumentResponse(BaseModel):
id: int
title: str
url: Optional[str] = None
notubiz_url: Optional[str] = None
has_text: bool
text_content: Optional[str] = None
truncated: bool = False
class SearchResult(BaseModel):
id: int
title: str
url: Optional[str] = None
match_type: list[str] = []
class SearchResponse(BaseModel):
query: str
count: int
results: list[SearchResult]
class SemanticResult(BaseModel):
document_id: int
title: str
similarity: float
excerpt: str
class SemanticSearchResponse(BaseModel):
query: str
count: int
results: list[SemanticResult]
class SyncRequest(BaseModel):
date_from: Optional[str] = Field(None, description="Start datum (YYYY-MM-DD)")
date_to: Optional[str] = Field(None, description="Eind datum (YYYY-MM-DD)")
download_documents: bool = Field(False, description="Download documenten")
index_documents: bool = Field(False, description="Indexeer voor semantic search")
class SyncResponse(BaseModel):
meetings: int
documents_found: int
documents_downloaded: Optional[int] = None
documents_indexed: Optional[int] = None
class SearchSyncRequest(BaseModel):
query: str = Field(..., description="Zoekterm (bijv. 'Paleis Soestdijk', 'De Speeldoos')")
start_date: str = Field("2010-01-01", description="Start datum (YYYY-MM-DD)")
end_date: Optional[str] = Field(None, description="Eind datum (YYYY-MM-DD), default vandaag")
download_documents: bool = Field(True, description="Download documenten en extraheer tekst")
index_documents: bool = Field(True, description="Indexeer voor semantic search")
limit: int = Field(100, description="Maximum aantal vergaderingen", ge=1, le=500)
class SearchSyncResponse(BaseModel):
query: str
date_range: str
meetings_found: int
meetings_synced: int
documents_found: int
documents_downloaded: int
documents_indexed: int
errors: list[str] = []
class AnnotationCreate(BaseModel):
content: str = Field(..., description="Inhoud van de annotatie")
document_id: Optional[int] = Field(None, description="Document ID")
meeting_id: Optional[int] = Field(None, description="Vergadering ID")
title: Optional[str] = Field(None, description="Titel")
tags: Optional[list[str]] = Field(None, description="Tags")
@app.get("/upload", response_class=HTMLResponse, include_in_schema=False)
async def upload_portal():
"""Simple local upload portal."""
return UPLOAD_HTML
@app.post("/upload", dependencies=[Depends(verify_api_key)], include_in_schema=False)
async def upload_file(
file: UploadFile = File(...),
title: str = Form(...),
create_visit_report: bool = Form(True),
date: Optional[str] = Form(None),
location: Optional[str] = Form(None),
participants: Optional[str] = Form(None),
organizations: Optional[str] = Form(None),
topics: Optional[str] = Form(None),
visit_type: Optional[str] = Form(None),
summary: Optional[str] = Form(None),
status: Optional[str] = Form(None),
source_url: Optional[str] = Form(None),
):
"""Upload a local file and store it in the database."""
file_bytes = await file.read()
max_size = Config.MAX_FILE_SIZE_MB * 1024 * 1024
if len(file_bytes) > max_size:
raise HTTPException(status_code=413, detail="File too large for DB storage")
file_base64 = base64.b64encode(file_bytes).decode('ascii')
filename = file.filename or 'upload.bin'
mime_type = file.content_type or 'application/octet-stream'
if create_visit_report:
provider = get_visit_report_provider()
report_id = provider.add_manual_visit_report(
title=title,
file_base64=file_base64,
filename=filename,
mime_type=mime_type,
date=date,
location=location,
participants=_parse_list(participants),
organizations=_parse_list(organizations),
topics=_parse_list(topics),
visit_type=visit_type,
summary=summary,
status=status,
source_url=source_url
)
return {"success": True, "visit_report_id": report_id}
doc_provider = get_document_provider()
document_id = doc_provider.create_document_from_base64(
title=title,
filename=filename,
mime_type=mime_type,
file_base64=file_base64,
source_url=source_url
)
return {"success": True, "document_id": document_id}
# ==================== Upload Portal ====================
UPLOAD_HTML = """
<!doctype html>
<html lang="nl">
<head>
<meta charset="utf-8" />
<title>Baarn Raadsinformatie - Uploader</title>
<style>
:root {
--bg: #f7f4ef;
--card: #ffffff;
--ink: #1d1d1b;
--accent: #0b4f6c;
--muted: #6b6b6b;
}
body { font-family: "Segoe UI", Tahoma, sans-serif; margin: 0; background: var(--bg); color: var(--ink); }
header { background: linear-gradient(135deg, #0b4f6c, #2a9d8f); color: #fff; padding: 24px; }
header h1 { margin: 0 0 6px; font-size: 24px; }
header p { margin: 0; opacity: 0.9; }
main { max-width: 900px; margin: 24px auto; padding: 0 16px 32px; }
.card { background: var(--card); border-radius: 12px; padding: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.08); }
.row { margin-bottom: 14px; }
label { display: block; font-weight: 600; margin-bottom: 6px; }
input, textarea, select { width: 100%; padding: 10px; box-sizing: border-box; border: 1px solid #ddd; border-radius: 8px; }
small { color: var(--muted); }
.inline { display: inline-block; width: auto; margin-right: 12px; }
.actions { display: flex; gap: 12px; flex-wrap: wrap; }
button { padding: 10px 16px; border-radius: 8px; border: 0; cursor: pointer; font-weight: 600; }
.primary { background: var(--accent); color: #fff; }
.ghost { background: #e8f0f3; color: #0b4f6c; }
pre { background: #f5f5f5; padding: 12px; border-radius: 8px; white-space: pre-wrap; }
</style>
</head>
<body>
<header>
<h1>Werkbezoek/Document Uploader</h1>
<p>Upload lokale bestanden (PDF/DOCX/PPTX/XLSX) en sla ze op in de database.</p>
</header>
<main>
<div class="card">
<div class="row">
<label>Bestand</label>
<input id="file" type="file" />
</div>
<div class="row">
<label>Titel</label>
<input id="title" type="text" placeholder="Titel van het document/verslag" />
</div>
<div class="row">
<label>
<input id="createVisit" type="checkbox" class="inline" checked />
Werkbezoek-verslag aanmaken
</label>
<small>Laat uit om alleen een document te uploaden.</small>
</div>
<div class="row">
<label>Datum (YYYY-MM-DD)</label>
<input id="date" type="text" placeholder="2026-01-15" />
</div>
<div class="row">
<label>Locatie</label>
<input id="location" type="text" placeholder="Locatie" />
</div>
<div class="row">
<label>Deelnemers (comma separated)</label>
<input id="participants" type="text" placeholder="Naam 1, Naam 2" />
</div>
<div class="row">
<label>Organisaties (comma separated)</label>
<input id="organizations" type="text" placeholder="Organisatie A, Organisatie B" />
</div>
<div class="row">
<label>Onderwerpen/tags (comma separated)</label>
<input id="topics" type="text" placeholder="wonen, verkeer" />
</div>
<div class="row">
<label>Type werkbezoek</label>
<input id="visitType" type="text" placeholder="werkbezoek" />
</div>
<div class="row">
<label>Samenvatting</label>
<textarea id="summary" rows="3"></textarea>
</div>
<div class="row">
<label>Status</label>
<select id="status">
<option value="">(default)</option>
<option value="draft">draft</option>
<option value="published">published</option>
<option value="archived">archived</option>
</select>
</div>
<div class="row">
<label>Bron URL (optioneel)</label>
<input id="sourceUrl" type="text" placeholder="https://..." />
</div>
<div class="row actions">
<button id="setKeyBtn" class="ghost">API key instellen</button>
<button id="uploadBtn" class="primary">Upload</button>
</div>
<small>De API key wordt opgeslagen in je browser (localStorage) en meegestuurd als header.</small>
</div>
<h3>Resultaat</h3>
<pre id="output"></pre>
</main>
<script>
const uploadBtn = document.getElementById('uploadBtn');
const setKeyBtn = document.getElementById('setKeyBtn');
setKeyBtn.addEventListener('click', () => {
const key = prompt('Voer je X-API-Key in:');
if (key) {
localStorage.setItem('baarnApiKey', key.trim());
alert('API key opgeslagen.');
}
});
uploadBtn.addEventListener('click', async () => {
const fileInput = document.getElementById('file');
const file = fileInput.files[0];
if (!file) {
alert('Kies eerst een bestand.');
return;
}
const apiKey = (localStorage.getItem('baarnApiKey') || '').trim();
if (!apiKey) {
alert('Stel eerst een API key in via "API key instellen".');
return;
}
const formData = new FormData();
formData.append('file', file);
formData.append('title', document.getElementById('title').value.trim() || file.name);
formData.append('create_visit_report', document.getElementById('createVisit').checked);
formData.append('date', document.getElementById('date').value.trim());
formData.append('location', document.getElementById('location').value.trim());
formData.append('participants', document.getElementById('participants').value.trim());
formData.append('organizations', document.getElementById('organizations').value.trim());
formData.append('topics', document.getElementById('topics').value.trim());
formData.append('visit_type', document.getElementById('visitType').value.trim());
formData.append('summary', document.getElementById('summary').value.trim());
formData.append('status', document.getElementById('status').value);
formData.append('source_url', document.getElementById('sourceUrl').value.trim());
const response = await fetch('/upload', {
method: 'POST',
headers: { 'X-API-Key': apiKey },
body: formData
});
const text = await response.text();
document.getElementById('output').textContent = text;
});
</script>
</body>
</html>
"""
class GremiumResponse(BaseModel):
id: int
name: str
class StatisticsResponse(BaseModel):
database: dict
index: dict
municipality: str
class CoalitieAfspraak(BaseModel):
id: str
thema: str
tekst: str
status: str
prioriteit: Optional[str] = None
gerelateerde_besluiten: int = 0
class CoalitieResponse(BaseModel):
summary: dict
afspraken: list[CoalitieAfspraak]
count: int
class UpdateAfspraakRequest(BaseModel):
new_status: Optional[str] = Field(None, description="Nieuwe status")
link_meeting_id: Optional[int] = Field(None, description="Meeting ID om te koppelen")
# ==================== Verkiezingsprogramma Models ====================
class PartyResponse(BaseModel):
id: int
name: str
abbreviation: Optional[str] = None
active: bool = True
website: Optional[str] = None
color: Optional[str] = None
class PartiesResponse(BaseModel):
count: int
parties: list[PartyResponse]
class ElectionProgramResult(BaseModel):
program_id: int
party: str
abbreviation: Optional[str] = None
year: int
snippet: str
class ElectionProgramSearchResponse(BaseModel):
query: str
count: int
results: list[ElectionProgramResult]
class PartyPositionComparison(BaseModel):
topic: str
year: Optional[int] = None
parties: dict
class PartySyncResponse(BaseModel):
timestamp: str
sources_checked: list[str]
parties_found: list[dict]
new_parties: list[str]
reactivated_parties: list[str]
deactivated_parties: list[str]
errors: list[str]
class PartySyncStatusResponse(BaseModel):
total_parties: int
active_parties: int
historical_parties: int
parties: list[dict]
# ==================== Document Generatie Models ====================
class MotieRequest(BaseModel):
titel: str = Field(..., description="Titel van de motie")
indieners: list[str] = Field(..., description="Namen van de indieners")
partijen: list[str] = Field(..., description="Partijen van de indieners")
constateringen: list[str] = Field(..., description="Constaterende dat... punten")
overwegingen: list[str] = Field(..., description="Overwegende dat... punten")
verzoeken: list[str] = Field(..., description="Verzoekt het college... punten")
vergadering_datum: Optional[str] = Field(None, description="Datum vergadering (YYYY-MM-DD)")
agendapunt: Optional[str] = Field(None, description="Agendapunt nummer")
toelichting: Optional[str] = Field(None, description="Optionele toelichting")
class WijzigingItem(BaseModel):
oorspronkelijk: str = Field(..., description="Oorspronkelijke tekst")
wordt: str = Field(..., description="Nieuwe tekst")
class AmendementRequest(BaseModel):
titel: str = Field(..., description="Titel van het amendement")
indieners: list[str] = Field(..., description="Namen van de indieners")
partijen: list[str] = Field(..., description="Partijen van de indieners")
raadsvoorstel_nummer: str = Field(..., description="Nummer van het raadsvoorstel")
raadsvoorstel_titel: str = Field(..., description="Titel van het raadsvoorstel")
wijzigingen: list[WijzigingItem] = Field(..., description="Lijst van tekstwijzigingen")
toelichting: Optional[str] = Field(None, description="Toelichting op de wijzigingen")
vergadering_datum: Optional[str] = Field(None, description="Datum vergadering (YYYY-MM-DD)")
agendapunt: Optional[str] = Field(None, description="Agendapunt nummer")
class DocumentGenerationResponse(BaseModel):
titel: str
type: str
filepath: Optional[str] = None
filename: Optional[str] = None
markdown: str
warning: Optional[str] = None
# ==================== Standpunten Models ====================
class StandpuntCreate(BaseModel):
party_id: Optional[int] = Field(None, description="Partij ID")
raadslid_id: Optional[int] = Field(None, description="Raadslid ID")
topic: str = Field(..., description="Onderwerp")
position_summary: str = Field(..., description="Korte samenvatting")
position_text: Optional[str] = Field(None, description="Volledige tekst")
stance: str = Field("onbekend", description="voor/tegen/neutraal/genuanceerd/onbekend")
stance_strength: Optional[int] = Field(None, ge=1, le=5, description="Sterkte (1-5)")
source_type: str = Field(..., description="Type bron")
source_document_id: Optional[int] = Field(None, description="Document ID bron")
source_meeting_id: Optional[int] = Field(None, description="Vergadering ID bron")
source_quote: Optional[str] = Field(None, description="Citaat uit bron")
position_date: Optional[str] = Field(None, description="Datum (YYYY-MM-DD)")
subtopic: Optional[str] = Field(None, description="Subonderwerp")
tags: Optional[list[str]] = Field(None, description="Tags")
class StandpuntResponse(BaseModel):
id: int
party_id: Optional[int] = None
party_name: Optional[str] = None
raadslid_id: Optional[int] = None
raadslid_name: Optional[str] = None
topic: str
subtopic: Optional[str] = None
position_summary: str
position_text: Optional[str] = None
stance: str
stance_strength: Optional[int] = None
source_type: str
verified: bool = False
position_date: Optional[str] = None
class StandpuntenSearchResponse(BaseModel):
count: int
standpunten: list[dict]
class StandpuntenCompareResponse(BaseModel):
topic: str
parties: dict
summary: Optional[dict] = None
class StandpuntHistoryResponse(BaseModel):
topic: str
history: list[dict]
class PartyContextResponse(BaseModel):
party_id: Optional[int] = None
party_name: Optional[str] = None
standpunten_by_topic: dict
total_standpunten: int
class RaadslidCreate(BaseModel):
name: str = Field(..., description="Volledige naam")
party_id: Optional[int] = Field(None, description="Partij ID")
email: Optional[str] = Field(None, description="E-mailadres")
start_date: Optional[str] = Field(None, description="Start datum (YYYY-MM-DD)")
is_wethouder: bool = Field(False, description="Is wethouder")
is_fractievoorzitter: bool = Field(False, description="Is fractievoorzitter")
is_steunfractielid: bool = Field(False, description="Is steunfractielid (geen stemrecht in raad)")
class RaadslidResponse(BaseModel):
id: int
name: str
party_id: Optional[int] = None
party_name: Optional[str] = None
email: Optional[str] = None
active: bool = True
is_wethouder: bool = False
is_fractievoorzitter: bool = False
is_steunfractielid: bool = False
class RaadsledenResponse(BaseModel):
count: int
raadsleden: list[dict]
class TopicResponse(BaseModel):
id: int
name: str
parent_id: Optional[int] = None
keywords: Optional[str] = None
class TopicsResponse(BaseModel):
count: int
topics: list[TopicResponse]
# ==================== API Endpoints ====================
@app.get("/", tags=["Info"])
async def root():
"""API root - basisinformatie."""
return {
"name": Config.SERVER_NAME,
"version": Config.SERVER_VERSION,
"municipality": Config.MUNICIPALITY_NAME,
"description": "REST API voor Baarn raadsinformatie"
}
@app.get("/health", tags=["Info"])
async def health():
"""Health check endpoint."""
db = get_database()
stats = db.get_statistics()
return {
"status": "healthy",
"database": {
"meetings": stats.get('meetings', 0),
"documents": stats.get('documents', 0)
}
}
# ==================== Vergaderingen ====================
@app.get("/api/meetings", response_model=MeetingsResponse, tags=["Vergaderingen"])
async def get_meetings(
limit: int = Query(20, description="Maximum aantal resultaten", le=100),
date_from: Optional[str] = Query(None, description="Start datum (YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Eind datum (YYYY-MM-DD)"),
search: Optional[str] = Query(None, description="Zoekterm"),
api_key: str = Depends(verify_api_key)
):
"""
Haal een lijst van vergaderingen op met optionele filters.
- **limit**: Maximum aantal resultaten (default 20, max 100)
- **date_from**: Filter op start datum
- **date_to**: Filter op eind datum
- **search**: Zoek in vergadertitels
"""
provider = get_meeting_provider()
meetings = provider.get_meetings(
limit=limit,
date_from=date_from,
date_to=date_to,
search=search
)
return {
"count": len(meetings),
"meetings": [
{"id": m['id'], "title": m['title'], "date": m['date'], "gremium": m.get('gremium_name')}
for m in meetings
]
}
@app.get("/api/meetings/{meeting_id}", response_model=MeetingDetail, tags=["Vergaderingen"])
async def get_meeting_details(meeting_id: int, api_key: str = Depends(verify_api_key)):
"""
Haal gedetailleerde informatie op over een specifieke vergadering.
Inclusief agenda items en gekoppelde documenten.
"""
provider = get_meeting_provider()
meeting = provider.get_meeting(meeting_id=meeting_id)
if not meeting:
raise HTTPException(status_code=404, detail="Vergadering niet gevonden")
return {
"id": meeting['id'],
"title": meeting['title'],
"date": meeting['date'],
"location": meeting.get('location'),
"agenda_items": [{"id": i['id'], "title": i['title']} for i in meeting.get('agenda_items', [])],
"documents": [{"id": d['id'], "title": d['title'], "has_content": bool(d.get('text_content'))} for d in meeting.get('documents', [])]
}
@app.get("/api/meetings/{meeting_id}/agenda", tags=["Vergaderingen"])
async def get_agenda_items(meeting_id: int, api_key: str = Depends(verify_api_key)):
"""
Haal agendapunten op voor een specifieke vergadering.
"""
provider = get_meeting_provider()
items = provider.get_agenda_items(meeting_id)
return {"meeting_id": meeting_id, "count": len(items), "agenda_items": items}
# ==================== Documenten ====================
@app.get("/api/documents/{document_id}", response_model=DocumentResponse, tags=["Documenten"])
async def get_document(document_id: int, api_key: str = Depends(verify_api_key)):
"""
Haal een specifiek document op met metadata en geëxtraheerde tekst.
Tekst wordt afgekapt op 10.000 karakters.
Inclusief download URL naar het originele document.
"""
provider = get_document_provider()
doc = provider.get_document(document_id)
if not doc:
raise HTTPException(status_code=404, detail="Document niet gevonden")
text = doc.get('text_content', '')
# Build Notubiz URL if we have a notubiz_id
notubiz_url = None
if doc.get('notubiz_id'):
notubiz_url = f"https://api.notubiz.nl/document/{doc['notubiz_id']}/1"
return {
"id": doc['id'],
"title": doc['title'],
"url": doc.get('url') or notubiz_url,
"notubiz_url": notubiz_url,
"has_text": bool(text),
"text_content": text[:10000] if text else None,
"truncated": len(text) > 10000 if text else False
}
@app.get("/api/documents/search", response_model=SearchResponse, tags=["Zoeken"])
async def search_documents(
query: str = Query(..., description="Zoekterm"),
limit: int = Query(20, description="Maximum resultaten", le=100),
api_key: str = Depends(verify_api_key)
):
"""
Zoek in documenten op titel en inhoud (keyword search).
Doorzoekt document titels en geëxtraheerde tekst.
Inclusief download URLs naar de originele documenten.
"""
provider = get_document_provider()
results = provider.search_documents(query, limit)
return {
"query": query,
"count": len(results),
"results": [
{
"id": d['id'],
"title": d['title'],
"url": d.get('url') or (f"https://api.notubiz.nl/document/{d['notubiz_id']}/1" if d.get('notubiz_id') else None),
"match_type": d.get('match_type', [])
}
for d in results
]
}
@app.get("/api/documents/semantic-search", response_model=SemanticSearchResponse, tags=["Zoeken"])
async def semantic_search(
query: str = Query(..., description="Zoekvraag in natuurlijke taal"),
limit: int = Query(10, description="Maximum resultaten", le=50),
api_key: str = Depends(verify_api_key)
):
"""
Semantisch zoeken met AI embeddings.
Vindt documenten op basis van betekenis, niet alleen exacte keywords.
Vereist dat embeddings zijn geïndexeerd.
"""
index = get_document_index()
results = index.search(query, limit)
if not results:
stats = index.get_index_stats()
if not stats.get('embeddings_available'):
raise HTTPException(
status_code=503,
detail="Embeddings niet beschikbaar. Installeer: pip install sentence-transformers torch"
)
if stats.get('indexed_documents', 0) == 0:
raise HTTPException(
status_code=503,
detail="Geen documenten geïndexeerd. Roep /sync aan met index_documents=true"
)
return {
"query": query,
"count": len(results),
"results": [
{
"document_id": r.document_id,
"title": r.document_title,
"similarity": round(r.similarity, 3),
"excerpt": r.chunk_text[:300]
}
for r in results
]
}
# ==================== Gremia ====================
@app.get("/api/gremia", tags=["Gremia"])
async def get_gremia(api_key: str = Depends(verify_api_key)):
"""
Haal de lijst van gremia (commissies) op.
"""
provider = get_meeting_provider()
gremia = provider.get_gremia()
return {"count": len(gremia), "gremia": [{"id": g['id'], "name": g['name']} for g in gremia]}
# ==================== Annotaties ====================
@app.post("/api/annotations", tags=["Annotaties"])
async def add_annotation(annotation: AnnotationCreate, api_key: str = Depends(verify_api_key)):
"""
Voeg een annotatie/notitie toe.
Kan gekoppeld worden aan een document of vergadering.
"""
db = get_database()
aid = db.add_annotation(
content=annotation.content,
document_id=annotation.document_id,
meeting_id=annotation.meeting_id,
title=annotation.title,
tags=annotation.tags
)
return {"success": True, "annotation_id": aid}
@app.get("/api/annotations", tags=["Annotaties"])
async def get_annotations(
document_id: Optional[int] = Query(None, description="Filter op document"),
meeting_id: Optional[int] = Query(None, description="Filter op vergadering"),
search: Optional[str] = Query(None, description="Zoekterm"),
api_key: str = Depends(verify_api_key)
):
"""
Haal annotaties op met optionele filters.
"""
db = get_database()
annotations = db.get_annotations(
document_id=document_id,
meeting_id=meeting_id,
search=search
)
return {"annotations": annotations}
# ==================== Statistieken ====================
@app.get("/api/statistics", response_model=StatisticsResponse, tags=["Info"])
async def get_statistics(api_key: str = Depends(verify_api_key)):
"""
Haal statistieken op over de database en index.
"""
db = get_database()
index = get_document_index()
return {
"database": db.get_statistics(),
"index": index.get_index_stats(),
"municipality": Config.MUNICIPALITY_NAME
}
# ==================== Coalitieakkoord ====================
@app.get("/api/coalitie", response_model=CoalitieResponse, tags=["Coalitie"])
async def get_coalitie_akkoord(
thema: Optional[str] = Query(None, description="Filter op thema"),
status: Optional[str] = Query(None, description="Filter op status"),
api_key: str = Depends(verify_api_key)
):
"""
Haal coalitieakkoord informatie op met afspraken en voortgang.
- **thema**: Filter op thema (bijv: 'wonen', 'duurzaamheid')
- **status**: Filter op status (niet_gestart, in_voorbereiding, in_uitvoering, gerealiseerd)
"""
tracker = get_coalitie_tracker()
summary = tracker.get_akkoord_summary()
afspraken = tracker.get_afspraken(thema=thema, status=status)
return {
"summary": summary,
"afspraken": [
{
"id": a.get('id'),
"thema": a.get('thema'),