-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.py
More file actions
2839 lines (2317 loc) · 92.7 KB
/
app.py
File metadata and controls
2839 lines (2317 loc) · 92.7 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
# import eventlet
# eventlet.monkey_patch()
import gevent
from gevent import monkey
monkey.patch_all()
import json
import yaml
import os
import random
import boto3
import requests
import together
# Unsandbox SDK for code execution
import un
from flask import (
Flask,
render_template,
request,
send_from_directory,
jsonify,
Response,
redirect,
url_for,
session,
)
from flask_socketio import SocketIO, emit, join_room, leave_room
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import InvalidRequestError
from models import db, Room, UserSession, Message, ActivityState, User, OTPToken
app = Flask(__name__, instance_relative_config=True)
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", "dev-key-change-in-production")
app.config["SQLALCHEMY_DATABASE_URI"] = (
f"sqlite:///{os.path.join(app.instance_path, 'chat.db')}"
)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
# Enable template auto-reload to prevent stale templates during development
app.config["TEMPLATES_AUTO_RELOAD"] = True
db.init_app(app)
from flask_migrate import Migrate
migrate = Migrate(app, db)
# socketio = SocketIO(app, async_mode="eventlet")
socketio = SocketIO(app, async_mode="gevent")
# Global dictionary to keep track of cancellation requests
cancellation_requests = {}
from openai import OpenAI
import activity
import auth
# Build a list of endpoints dynamically.
ENDPOINTS = []
MAX_ENDPOINTS = 1000
for i in range(MAX_ENDPOINTS):
endpoint = os.environ.get(f"MODEL_ENDPOINT_{i}")
if not endpoint:
continue
# API key is optional; if not provided, use a default.
api_key = os.environ.get(f"MODEL_API_KEY_{i}", "not-needed")
ENDPOINTS.append(
{
"base_url": endpoint,
"api_key": api_key,
}
)
if not ENDPOINTS:
raise Exception("No MODEL_ENDPOINT_x environment variables found!")
# Build a dynamic model map by querying each endpoint.
MODEL_CLIENT_MAP = {}
SYSTEM_USERS = []
def get_client_for_endpoint(endpoint, api_key):
# All providers use the OpenAI client; no endpoint URLs are hardcoded here.
return OpenAI(api_key=api_key, base_url=endpoint)
VISION_MODELS = [] # Populated at startup with available vision models
def is_vision_model(model_name: str) -> bool:
"""Check if a model supports vision/image input."""
if not model_name:
return False
model_lower = model_name.lower()
vision_indicators = ["-vl", "vl:", "vision", "gpt-4o", "gpt-4-turbo"]
return any(indicator in model_lower for indicator in vision_indicators)
def initialize_model_map():
global SYSTEM_USERS
MODEL_CLIENT_MAP.clear()
VISION_MODELS.clear()
for ep_config in ENDPOINTS:
base_url = ep_config["base_url"]
api_key = ep_config["api_key"]
client = get_client_for_endpoint(base_url, api_key)
try:
response = client.models.list()
model_list = response.data # Assume each model object has an 'id' attribute
print(f"[DEBUG] {base_url} returned models: {[m.id for m in model_list]}")
except Exception as e:
print(f"[WARN] Could not list models for endpoint '{base_url}': {e}")
continue
for m in model_list:
model_id = m.id
if model_id and model_id not in MODEL_CLIENT_MAP:
MODEL_CLIENT_MAP[model_id] = (client, base_url)
# Populate SYSTEM_USERS with dynamically loaded models.
SYSTEM_USERS = list(MODEL_CLIENT_MAP.keys()) + ["system"] # Include "system" for fetched images
print("Loaded models:", list(MODEL_CLIENT_MAP.keys()))
# Detect and track available vision models
for model_id in MODEL_CLIENT_MAP.keys():
if is_vision_model(model_id):
VISION_MODELS.append(model_id)
if VISION_MODELS:
print(f"Vision models available: {VISION_MODELS}")
else:
print("No vision models available")
if MODEL_CLIENT_MAP:
pass
else:
initialize_model_map()
# 4) Lookup function: get an OpenAI client for a given model name
def get_client_for_model(model_name: str):
"""
If the model name is known, return its dedicated client.
Otherwise, return None and LOL at the user when everything breaks.
"""
if model_name in MODEL_CLIENT_MAP:
print(f"Completion Endpoint Processing: {MODEL_CLIENT_MAP[model_name][1]}")
return MODEL_CLIENT_MAP[model_name][0]
def extract_base64_from_img_tag(content: str) -> tuple[str, str] | None:
"""Extract base64 data and media type from an HTML img tag.
Returns (media_type, base64_data) or None if not found.
"""
import re
# Match data:image/TYPE;base64,DATA patterns in img src
pattern = r'<img[^>]*src="data:image/(jpeg|png|gif|webp);base64,([^"]+)"'
match = re.search(pattern, content)
if match:
media_type = f"image/{match.group(1)}"
base64_data = match.group(2)
return (media_type, base64_data)
return None
def extract_external_image_url(content: str) -> str | None:
"""Extract external image URL from an HTML img tag.
Returns the URL or None if not found.
"""
import re
# Match external URLs in img src (http/https)
pattern = r'<img[^>]*src="(https?://[^"]+)"'
match = re.search(pattern, content)
if match:
return match.group(1)
return None
# Cache for fetched external images (URL -> base64 data URL)
_external_image_cache = {}
# CORS proxy for ethical fetching (respects robots.txt)
CORS_PROXY_URL = "https://cors-proxy.uncloseai.com/api/fetch"
def escape_like_pattern(s: str) -> str:
"""Escape special characters for SQL LIKE patterns."""
# Escape %, _, and \ which have special meaning in LIKE
return s.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
def find_saved_base64_for_url(external_url: str, room_id: int) -> str | None:
"""Look up if we've already saved a base64 version of this URL in this room.
Returns the data URL if found, None otherwise.
"""
# Check in-memory cache first
if external_url in _external_image_cache:
return _external_image_cache[external_url]
# Look for a saved message with this URL in the alt text
try:
# Escape special LIKE characters in URL (%, _, \)
escaped_url = escape_like_pattern(external_url)
# Search for messages containing "Fetched from {external_url}"
saved_msg = Message.query.filter(
Message.room_id == room_id,
Message.content.like(f'%alt="Fetched from {escaped_url}"%', escape='\\')
).first()
if saved_msg:
# Extract base64 from the saved message
img_data = extract_base64_from_img_tag(saved_msg.content)
if img_data:
media_type, base64_data = img_data
data_url = f"data:{media_type};base64,{base64_data}"
# Add to memory cache for faster lookups
_external_image_cache[external_url] = data_url
print(f"Found saved base64 for {external_url} in message {saved_msg.id}")
return data_url
except Exception as e:
print(f"Error looking up saved base64: {e}")
return None
def fetch_external_image_as_base64(image_url: str) -> str | None:
"""Fetch external image via CORS proxy and convert to base64.
Returns data URL (data:image/...;base64,...) or None on failure.
"""
import base64
import httpx
# Check cache first
if image_url in _external_image_cache:
return _external_image_cache[image_url]
try:
proxy_url = f"{CORS_PROXY_URL}?uri_target={image_url}"
with httpx.Client(timeout=15.0) as client:
response = client.get(proxy_url)
if response.status_code == 403:
print(f"Image blocked by robots.txt: {image_url}")
return None
response.raise_for_status()
# Check content type
content_type = response.headers.get("content-type", "")
if not content_type.startswith("image/"):
print(f"Not an image: {image_url} ({content_type})")
return None
# Convert to base64
b64_data = base64.b64encode(response.content).decode("utf-8")
media_type = content_type.split(";")[0] # Remove charset if present
data_url = f"data:{media_type};base64,{b64_data}"
# Cache it
_external_image_cache[image_url] = data_url
return data_url
except Exception as e:
print(f"Failed to fetch external image {image_url}: {e}")
return None
def save_fetched_image_as_message(external_url: str, data_url: str, room_id: int) -> None:
"""Save a fetched external image as a new message in the database.
This persists the base64 version so we don't need to fetch again.
Only saves if no saved version exists for this URL in this room.
"""
print(f"[Vision Save] Attempting to save base64 for room {room_id}: {external_url[:60]}...")
try:
# Check if already saved for this URL in this room
# Escape special LIKE characters in URL (%, _, \)
escaped_url = escape_like_pattern(external_url)
existing = Message.query.filter(
Message.room_id == room_id,
Message.content.like(f'%alt="Fetched from {escaped_url}"%', escape='\\')
).first()
if existing:
print(f"[Vision Save] Already exists as message {existing.id}")
return
# Create img tag with base64 data
img_content = f'<img src="{data_url}" alt="Fetched from {external_url}">'
new_message = Message(
username="system", # Mark as system message
content=img_content,
room_id=room_id
)
db.session.add(new_message)
db.session.commit()
print(f"[Vision Save] SUCCESS - Saved as message {new_message.id}")
# Also cache it in memory
_external_image_cache[external_url] = data_url
except Exception as e:
print(f"[Vision Save] FAILED: {e}")
import traceback
traceback.print_exc()
db.session.rollback()
def build_message_content(msg, is_vision: bool, room_id: int = None) -> dict | str:
"""Build message content, handling images for vision models.
For vision models with images, returns multimodal content array.
Otherwise returns plain text content.
If room_id is provided and an external image is fetched, saves the
base64 version as a new message for future use.
"""
if not is_vision:
return msg.content
# Check if this message contains a base64 image
img_data = extract_base64_from_img_tag(msg.content)
if img_data:
media_type, base64_data = img_data
# Return multimodal content with image
return [
{"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{base64_data}"}}
]
# Check for external image URL
external_url = extract_external_image_url(msg.content)
if external_url:
print(f"[Vision] Found external URL in message {msg.id}: {external_url[:80]}...")
# First check if we already have a saved base64 version
if room_id is not None:
saved_data_url = find_saved_base64_for_url(external_url, room_id)
if saved_data_url:
print(f"[Vision] Using saved base64 for {external_url[:50]}...")
return [
{"type": "image_url", "image_url": {"url": saved_data_url}}
]
# Not saved yet - fetch and save
print(f"[Vision] Fetching external image: {external_url[:80]}...")
data_url = fetch_external_image_as_base64(external_url)
if data_url:
print(f"[Vision] Fetched successfully, saving to room {room_id}...")
# Save the fetched image as a new message for persistence
if room_id is not None:
save_fetched_image_as_message(external_url, data_url, room_id)
return [
{"type": "image_url", "image_url": {"url": data_url}}
]
else:
print(f"[Vision] Failed to fetch external image")
# Plain text message
return msg.content
def extract_first_image_for_og(room_id: int) -> str | None:
"""Extract the first image URL from messages for Open Graph meta tags.
Checks messages in the room for:
1. Base64 images (returns as data URL - may be large)
2. External image URLs in markdown format 
3. External image URLs in img tags
Returns image URL/data URL or None if no image found.
"""
import re
messages = Message.query.filter_by(room_id=room_id).order_by(Message.id.asc()).limit(50).all()
for msg in messages:
if not msg.content:
continue
# Check for base64 image
if msg.is_base64_image():
img_data = extract_base64_from_img_tag(msg.content)
if img_data:
media_type, base64_data = img_data
return f"data:{media_type};base64,{base64_data}"
# Check for markdown image 
md_img_match = re.search(r'!\[[^\]]*\]\(([^)]+)\)', msg.content)
if md_img_match:
url = md_img_match.group(1)
if url.startswith(('http://', 'https://')):
return url
# Check for img tag with src
img_src_match = re.search(r'<img[^>]+src=["\']([^"\']+)["\']', msg.content)
if img_src_match:
url = img_src_match.group(1)
if url.startswith(('http://', 'https://')):
return url
return None
def generate_og_description(room, max_chars: int = 500) -> str:
"""Generate a description for Open Graph meta tags.
Uses room title if available, then extracts text from first few messages.
Strips markdown/code/images and limits to max_chars.
"""
import re
parts = []
# Start with room title if available
if room and room.title:
parts.append(room.title)
# Get first few messages for description
if room:
messages = Message.query.filter_by(room_id=room.id).order_by(Message.id.asc()).limit(10).all()
for msg in messages:
if not msg.content:
continue
# Skip base64 images
if msg.is_base64_image():
continue
text = msg.content
# Remove code blocks
text = re.sub(r'```[\s\S]*?```', '', text)
text = re.sub(r'`[^`]+`', '', text)
# Remove markdown images
text = re.sub(r'!\[[^\]]*\]\([^)]+\)', '', text)
# Remove HTML tags
text = re.sub(r'<[^>]+>', '', text)
# Remove markdown links but keep text
text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
# Remove markdown headers
text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE)
# Remove bold/italic markers
text = re.sub(r'\*{1,2}([^*]+)\*{1,2}', r'\1', text)
text = re.sub(r'_{1,2}([^_]+)_{1,2}', r'\1', text)
# Clean up whitespace
text = re.sub(r'\s+', ' ', text).strip()
if text:
parts.append(text)
# Stop if we have enough content
if len(' '.join(parts)) > max_chars:
break
description = ' '.join(parts)
# Truncate to max_chars
if len(description) > max_chars:
description = description[:max_chars - 3].rsplit(' ', 1)[0] + '...'
return description if description else "AI-powered chat room on OpenCompletion"
def get_openai_client_and_model(
model_name="adamo1139/Hermes-3-Llama-3.1-8B-FP8-Dynamic",
):
"""Get OpenAI client and model name.
Supports MODEL_X references (e.g., MODEL_1, MODEL_2, MODEL_3) that map to
environment variables MODEL_ENDPOINT_X and MODEL_API_KEY_X.
"""
# Handle MODEL_X references
if model_name and model_name.startswith("MODEL_"):
try:
model_num = model_name.split("_")[1]
endpoint_key = f"MODEL_ENDPOINT_{model_num}"
api_key_key = f"MODEL_API_KEY_{model_num}"
endpoint = os.environ.get(endpoint_key)
api_key = os.environ.get(api_key_key)
if endpoint and api_key:
client = get_client_for_endpoint(endpoint, api_key)
# Look up actual model name from MODEL_CLIENT_MAP for this endpoint
actual_model = None
for model_id, (registered_client, base_url) in MODEL_CLIENT_MAP.items():
if base_url == endpoint:
actual_model = model_id
break
if actual_model:
return client, actual_model
else:
# Fallback: query endpoint for models if not in map yet
try:
response = client.models.list()
if response.data:
actual_model = response.data[0].id
print(
f"[DEBUG] Using first model from {endpoint}: {actual_model}"
)
return client, actual_model
except Exception as e:
print(f"Warning: Could not query models from {endpoint}: {e}")
# Final fallback
print(
f"Warning: No models found for {endpoint}, using 'model' as fallback"
)
return client, "model"
else:
print(
f"Warning: MODEL_{model_num} not configured ({endpoint_key} or {api_key_key} missing)"
)
# Fall back to default model
model_name = "adamo1139/Hermes-3-Llama-3.1-8B-FP8-Dynamic"
except Exception as e:
print(f"Warning: Failed to load {model_name}: {e}, falling back to default")
model_name = "adamo1139/Hermes-3-Llama-3.1-8B-FP8-Dynamic"
return get_client_for_model(model_name), model_name
HELP_MESSAGE = """
**Available Commands:**
- `/activity [s3_file_path]`: Start an activity from the specified S3 file path.
- `/activity cancel`: Cancel the current activity.
- `/activity info`: Display information about the current activity.
- `/activity metadata`: Display metadata for the current activity.
- `/s3 ls [s3_file_path_pattern]`: List files in S3 matching the pattern.
- `/s3 load [s3_file_path]`: Load a file from S3.
- `/s3 save [s3_key_path]`: Save the most recent code block from the chatroom to S3.
- `/title new`: Generates a new title which reflects conversation content for the current chatroom.
- `/cancel`: Cancel the most recent chat completion from streaming into the chatroom.
- `/help`: Display this help message.
**Interacting with AI Models:**
- Select a model from the dropdown menu above the chat input. Available models are dynamically loaded from configured endpoints and include options like `gpt-4o-mini`, `llama3-70b-8192`, `anthropic.claude-3-sonnet-20240229-v1:0`, and `dall-e-3` for image generation.
- Type your message and send it. The selected model will respond if it's not "None".
- For image generation, select `dall-e-3` and provide a prompt (e.g., "A futuristic cityscape").
**Getting Started:**
Welcome to the chatroom! Here, you can explore various AI models and engage in interactive activities. Here's how you can get started:
1. **Explore the Chatroom:**
- Join a chatroom by navigating to its unique URL. You can see the list of available chatrooms on the main page.
- Once inside, you can start a conversation by typing your message in the chatbox.
2. **Start an Activity:**
- To begin an educational activity, use the `/activity` command followed by the path to the activity YAML file. For example:
**Getting Started:**
Welcome to the chatroom! Here, you can explore various AI models and engage in interactive activities. Here's how you can get started:
1. **Explore the Chatroom:**
- Join a chatroom by navigating to its unique URL. You can see the list of available chatrooms on the main page.
- Once inside, you can start a conversation by typing your message in the chatbox.
2. **Start an Activity:**
- To begin an educational activity, use the `/activity` command followed by the path to the activity YAML file. For example:
```
/activity research/activity0.yaml
```
- The AI will guide you through the activity, providing feedback and information as you progress.
3. **Interact with AI Models:**
- To interact with a specific AI model, simply type the model's command followed by your prompt. For example:
```
gpt-4 What is the capital of France?
```
- The system will process your message and provide a response from the selected model.
4. **Manage Files with S3:**
- Use the `/s3` commands to load, save, or list files in your S3 bucket. For example, to list all files, use:
```
/s3 ls *
```
5. **Get Help:**
- If you need assistance or want to see a list of available commands, type `/help` to display this message.
Feel free to explore and experiment with different commands and models. Enjoy your time in the chatroom!
"""
def get_room(room_name):
"""Utility function to get room from room name."""
room = Room.query.filter_by(name=room_name).first()
if room:
return room
else:
# Create a new room since it doesn't exist
new_room = Room()
new_room.name = room_name
db.session.add(new_room)
db.session.commit()
return new_room
def get_s3_client():
"""Utility function to get the S3 client with the appropriate profile."""
if app.config.get("PROFILE_NAME"):
session = boto3.Session(profile_name=app.config["PROFILE_NAME"])
s3_client = session.client("s3")
else:
s3_client = boto3.client("s3")
return s3_client
# Initialize activity module after socketio and db are configured
activity.init_activity_module(
app,
socketio,
db,
{
"get_room": get_room,
"get_s3_client": get_s3_client,
"get_openai_client_and_model": get_openai_client_and_model,
"SYSTEM_USERS": SYSTEM_USERS,
},
)
@app.route("/favicon.ico")
def favicon():
return send_from_directory(os.path.join(app.root_path, "static"), "favicon.ico")
@app.route("/")
def index():
total_public_rooms = Room.query.filter_by(is_private=False, is_archived=False).count()
total_private_rooms = 0
user = auth.get_current_user()
if user:
total_private_rooms = Room.query.filter_by(is_private=True, is_archived=False, owner_id=user.id).count()
stats = {
'total_public_rooms': total_public_rooms,
'total_private_rooms': total_private_rooms,
}
return render_template("index.html", stats=stats, user=user)
@app.route("/auth")
def auth_page():
"""Authentication page"""
return render_template("auth.html")
@app.route("/browse")
def browse_rooms():
"""Browse all rooms (public and user's private rooms)"""
user = auth.get_current_user()
# Get public rooms ordered by last updated
public_rooms = Room.query.filter_by(
is_private=False,
is_archived=False
).order_by(Room.updated_at.desc()).all()
# Get user's private rooms if authenticated
private_rooms = []
if user:
private_rooms = Room.query.filter_by(
is_private=True,
is_archived=False,
owner_id=user.id
).order_by(Room.updated_at.desc()).all()
return render_template(
"browse.html",
public_rooms=public_rooms,
private_rooms=private_rooms,
user=user
)
@app.route("/models", methods=["GET"])
def get_models():
# Optionally refresh or reinitialize the model map here.
# For now we simply return the keys.
return jsonify({"models": list(MODEL_CLIENT_MAP.keys())})
@app.route("/vision", methods=["GET"])
def get_vision_status():
"""Return vision model availability status."""
return jsonify({
"available": len(VISION_MODELS) > 0,
"models": VISION_MODELS,
"default": VISION_MODELS[0] if VISION_MODELS else None
})
@app.route("/vision/describe", methods=["POST"])
def describe_image():
"""Generate alt text description for an image using vision model."""
if not VISION_MODELS:
return jsonify({"error": "No vision models available"}), 503
data = request.get_json()
if not data or "image" not in data:
return jsonify({"error": "Missing 'image' field (base64 data URL)"}), 400
image_url = data["image"] # Expected format: data:image/jpeg;base64,...
prompt = data.get("prompt", "Describe this image in one brief sentence for use as alt text.")
model_name = data.get("model", VISION_MODELS[0])
if model_name not in VISION_MODELS:
return jsonify({"error": f"Model {model_name} is not a vision model"}), 400
try:
client = get_client_for_model(model_name)
response = client.chat.completions.create(
model=model_name,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": image_url}}
]
}],
max_tokens=150,
temperature=0.3
)
description = response.choices[0].message.content.strip()
return jsonify({"description": description, "model": model_name})
except Exception as e:
return jsonify({"error": str(e)}), 500
# Authentication endpoints
@app.route("/auth/send-otp", methods=["POST"])
def send_otp():
"""Send OTP to user's email"""
data = request.get_json()
email = data.get('email', '').strip().lower()
if not email:
return jsonify({'error': 'Email is required'}), 400
# Basic email validation
if '@' not in email or '.' not in email.split('@')[1]:
return jsonify({'error': 'Invalid email address'}), 400
# Create OTP token
otp_token = auth.create_otp_token(email)
# Send OTP via email
if auth.send_otp_email(email, otp_token.otp_code):
return jsonify({
'success': True,
'message': 'OTP sent to your email',
'email': email
})
else:
return jsonify({'error': 'Failed to send OTP email'}), 500
@app.route("/auth/verify-otp", methods=["POST"])
def verify_otp():
"""Verify OTP code and check if user exists"""
data = request.get_json()
email = data.get('email', '').strip().lower()
otp_code = data.get('otp_code', '').strip()
if not email or not otp_code:
return jsonify({'error': 'Email and OTP code are required'}), 400
# Verify OTP
otp_token = auth.verify_otp(email, otp_code)
if not otp_token:
return jsonify({'error': 'Invalid or expired OTP code'}), 400
# Check if user exists
user = auth.get_or_create_user(email)
if user:
# Existing user - log them in
auth.login_user(user)
return jsonify({
'success': True,
'needs_display_name': False,
'user': {
'email': user.email,
'display_name': user.display_name
}
})
else:
# New user - needs to claim display name
# Store email in session temporarily
session['pending_email'] = email
return jsonify({
'success': True,
'needs_display_name': True,
'email': email
})
@app.route("/auth/claim-name", methods=["POST"])
def claim_name():
"""Claim display name for new user (after OTP verification)"""
data = request.get_json()
display_name = data.get('display_name', '').strip()
email = session.get('pending_email')
if not email:
return jsonify({'error': 'No pending email verification'}), 400
if not display_name:
return jsonify({'error': 'Display name is required'}), 400
# Validate display name (alphanumeric, underscores, hyphens only, 3-50 chars)
import re
if not re.match(r'^[a-zA-Z0-9_-]{3,50}$', display_name):
return jsonify({
'error': 'Display name must be 3-50 characters (letters, numbers, underscores, hyphens only)'
}), 400
# Create user
user, error = auth.create_user(email, display_name)
if error:
return jsonify({'error': error}), 400
# Log in user
auth.login_user(user)
# Clear pending email
session.pop('pending_email', None)
return jsonify({
'success': True,
'user': {
'email': user.email,
'display_name': user.display_name
}
})
@app.route("/auth/status", methods=["GET"])
def auth_status():
"""Get current authentication status"""
user = auth.get_current_user()
if user:
return jsonify({
'authenticated': True,
'user': {
'email': user.email,
'display_name': user.display_name
}
})
else:
return jsonify({'authenticated': False})
@app.route("/auth/logout", methods=["POST"])
def logout():
"""Log out current user"""
auth.logout_user()
return jsonify({'success': True})
@app.route("/profile")
@auth.require_auth
def profile_page():
"""Profile settings page"""
user = auth.get_current_user()
return render_template("profile.html", user=user)
@app.route("/api/check-username", methods=["GET"])
def check_username():
"""Check if username is available"""
username = request.args.get('username', '').strip()
if not username:
return jsonify({'available': False, 'error': 'Username is required'}), 400
# Validate format
import re
if not re.match(r'^[a-zA-Z0-9_-]{3,50}$', username):
return jsonify({'available': False, 'error': 'Invalid format'}), 400
# Check if username exists
existing_user = User.query.filter_by(display_name=username).first()
return jsonify({'available': existing_user is None})
@app.route("/api/update-username", methods=["POST"])
@auth.require_auth
def update_username():
"""Update user's display name"""
user = auth.get_current_user()
data = request.get_json()
new_username = data.get('new_username', '').strip()
if not new_username:
return jsonify({'error': 'Username is required'}), 400
# Validate format
import re
if not re.match(r'^[a-zA-Z0-9_-]{3,50}$', new_username):
return jsonify({
'error': 'Username must be 3-50 characters (letters, numbers, underscores, hyphens only)'
}), 400
# Check if username is already taken
existing_user = User.query.filter_by(display_name=new_username).first()
if existing_user and existing_user.id != user.id:
return jsonify({'error': 'Username is already taken'}), 400
# Update username
user.display_name = new_username
db.session.commit()
return jsonify({
'success': True,
'user': {
'email': user.email,
'display_name': user.display_name
}
})
@app.route("/api/activities", methods=["GET"])
def get_activities():
"""Return the list of available activities."""
activities = []
if app.config.get("LOCAL_ACTIVITIES"):
# List local activity files from research directory
import os
research_dir = "research"
if os.path.exists(research_dir):
for filename in sorted(os.listdir(research_dir)):
if filename.endswith((".yaml", ".yml")):
activities.append(f"research/{filename}")
else:
# For S3 activities, you would list from S3
# This is a placeholder - you'd need to implement S3 listing
pass
return jsonify({"activities": activities})
@app.route("/api/rooms", methods=["GET"])
def get_rooms_api():
"""Get list of rooms (public or user's private rooms)"""
user = auth.get_current_user()
# Get public rooms
public_rooms = Room.query.filter_by(is_private=False, is_archived=False).order_by(Room.id.desc()).all()
# Get private rooms if authenticated
private_rooms = []
if user:
private_rooms = Room.query.filter_by(is_private=True, is_archived=False, owner_id=user.id).order_by(Room.id.desc()).all()
return jsonify({
'public_rooms': [{
'id': r.id,
'name': r.name,
'title': r.title,
'active_users_count': len(r.get_active_users())
} for r in public_rooms],
'private_rooms': [{
'id': r.id,
'name': r.name,
'title': r.title,
'active_users_count': len(r.get_active_users())
} for r in private_rooms]
})
@app.route("/api/rooms/create", methods=["POST"])