-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebserver.py
2541 lines (2156 loc) · 94.2 KB
/
webserver.py
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 zipfile # built-in
import py7zr
import rarfile
import tempfile
import os
import shutil
from werkzeug.utils import secure_filename
from flask import render_template, redirect, url_for, make_response
from datetime import datetime, timedelta
import shutil
import json
from flask import Flask, request, jsonify, send_from_directory, send_file, Response, session, g
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
import threading
import requests
import time
import uuid
from dotenv import load_dotenv
from tts_with_rvc import TTS_RVC
from flask_talisman import Talisman
from flask_cors import CORS, cross_origin
import stripe
from sqlalchemy import and_
import time
from queue_system import request_queue, setup_queue_handlers
from model_cache import model_cache
import base64
import lzma
import json
from functools import wraps
# Load environment variables
load_dotenv('/root/.env')
app = Flask(__name__,
template_folder='/root/templates',
static_folder='/root/main'
)
CORS(app,
supports_credentials=True,
resources={
r"/*": {
"origins": ["*"], # Allow all origins for local deployment
"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allow_headers": ["Content-Type", "Authorization"],
"supports_credentials": True
}
}
)
model_cache._base_model_path = "/root/models"
model_cache._input_dir = "/root/input/"
model_cache._output_dir = "/root/output/"
model_cache._cache_timeout = 1800 # 30 minutes timeout
# App Configuration
app.config.update(
SQLALCHEMY_DATABASE_URI='sqlite:////root/db/users.db',
SQLALCHEMY_TRACK_MODIFICATIONS=False,
SECRET_KEY=os.getenv('SECRET_KEY', 'dev-key-change-this'),
STATIC_FOLDER='/root/main',
SESSION_COOKIE_SECURE=False, # Changed for local deployment
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE='Lax',
PERMANENT_SESSION_LIFETIME=timedelta(days=31),
SESSION_COOKIE_PATH='/',
MAX_CONTENT_LENGTH=1024 * 1024 * 1024,
)
# Stripe Configuration
stripe.api_key = os.getenv('STRIPE_SECRET_KEY')
STRIPE_PRICE_IDS = {
'creator': os.getenv('STRIPE_CREATOR_PRICE_ID'), # $9.99 monthly
'master': os.getenv('STRIPE_MASTER_PRICE_ID'), # $24.99 monthly
}
# Credit package configuration
CREDIT_PACKAGES = {
1000: 500, # 1000 credits for $5.00
2500: 1000 # 2500 credits for $10.00
}
# Initialize extensions
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.unauthorized_handler
def unauthorized():
if request.blueprint == 'api' or request.path.startswith('/api/') or request.path.startswith('/auth/'):
return jsonify({'error': 'Authentication required'}), 401
return redirect(url_for('serve_index'))
# Directory configurations
STATIC_DIR = "/root/main"
OUTPUT_DIRECTORY = "/root/output/"
UPLOAD_FOLDER = '/root/main/avatars'
CHARACTER_FOLDER = '/root/main/characters'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'mp4', 'webm', 'wmv'}
KOBOLD_API = os.getenv('KOBOLD_API', 'http://127.0.0.1:5000')
os.makedirs(OUTPUT_DIRECTORY, exist_ok=True)
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(CHARACTER_FOLDER, exist_ok=True)
# User Model
class User(UserMixin, db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(200))
credits = db.Column(db.Integer, default=1000)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
last_login = db.Column(db.DateTime)
is_active = db.Column(db.Boolean, default=True)
is_admin = db.Column(db.Boolean, default=False)
characters = db.relationship('Character', backref='creator', lazy=True)
stripe_customer_id = db.Column(db.String(100), unique=True)
subscription_tier = db.Column(db.String(20), default='explorer')
subscription_status = db.Column(db.String(20), default='free')
subscription_id = db.Column(db.String(100), unique=True)
monthly_credits = db.Column(db.Integer, default=1000)
last_credit_refresh = db.Column(db.DateTime, default=datetime.utcnow)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def get_credits(self):
return self.credits
def add_credits(self, amount):
self.credits += amount
db.session.commit()
def deduct_credits(self, amount):
if self.credits >= amount:
self.credits -= amount
db.session.commit()
return True
return False
# Add the new method here, indented at the same level as the others
def deduct_credits_atomic(self, amount):
"""
Atomically deduct credits from user balance.
Returns True if successful, False if insufficient credits.
"""
max_retries = 3
retry_delay = 0.1
for attempt in range(max_retries):
try:
# Create a new session for this transaction
with db.session.begin():
user = db.session.query(User).filter(
User.id == self.id
).with_for_update().first()
if not user or user.credits < amount:
return False
# Update credits directly in the transaction
user.credits = user.credits - amount
return True
except Exception as e:
db.session.rollback()
if attempt == max_retries - 1:
print(f"Error in atomic credit deduction: {e}")
return False
time.sleep(retry_delay)
retry_delay *= 2 # Exponential backoff
return False # All retries failed
return False # All retries failed
class StorySession(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
creator_id = db.Column(db.String(36), db.ForeignKey('user.id'), nullable=False)
title = db.Column(db.String(100), nullable=False)
scenario = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
is_active = db.Column(db.Boolean, default=True)
max_characters = db.Column(db.Integer, default=4)
settings = db.Column(db.JSON)
class StoryCharacter(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
session_id = db.Column(db.String(36), db.ForeignKey('story_session.id'), nullable=False)
character_id = db.Column(db.String(36), db.ForeignKey('character.id'), nullable=True) # Nullable for placeholders
position = db.Column(db.Integer)
added_at = db.Column(db.DateTime, default=datetime.utcnow)
is_active = db.Column(db.Boolean, default=True)
is_placeholder = db.Column(db.Boolean, default=False)
placeholder_name = db.Column(db.String(100), default="Empty Panel")
class StripeTransaction(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
user_id = db.Column(db.String(36), db.ForeignKey('user.id'), nullable=False)
amount = db.Column(db.Integer, nullable=False) # Amount in cents
credits = db.Column(db.Integer, nullable=False)
type = db.Column(db.String(20), nullable=False) # 'credit_purchase' or 'subscription'
status = db.Column(db.String(20), nullable=False)
stripe_payment_id = db.Column(db.String(100), unique=True)
timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
# Changed backref name to avoid conflict
user = db.relationship('User', backref=db.backref('stripe_payment_transactions', lazy=True))
class SubscriptionTier(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
name = db.Column(db.String(50), nullable=False) # 'explorer', 'creator', 'master'
price = db.Column(db.Integer, nullable=False) # Price in cents
monthly_credits = db.Column(db.Integer) # None for unlimited
features = db.Column(db.JSON)
# Credit Transaction Model
class CreditTransaction(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
user_id = db.Column(db.String(36), db.ForeignKey('user.id'), nullable=False)
amount = db.Column(db.Integer, nullable=False)
transaction_type = db.Column(db.String(50), nullable=False)
description = db.Column(db.String(200))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship('User', backref=db.backref('transactions', lazy=True))
class Character(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
creator_id = db.Column(db.String(36), db.ForeignKey('user.id'), nullable=False)
name = db.Column(db.String(100), nullable=False)
description = db.Column(db.Text, nullable=False)
system_prompt = db.Column(db.Text, nullable=False)
avatar_path = db.Column(db.String(255), nullable=False)
background_path = db.Column(db.String(255))
tts_voice = db.Column(db.String(50), nullable=False)
category = db.Column(db.String(50))
is_private = db.Column(db.Boolean, default=False)
is_approved = db.Column(db.Boolean, default=False)
approval_status = db.Column(db.String(20), default='pending')
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, onupdate=datetime.utcnow)
settings = db.Column(db.JSON)
greetings = db.Column(db.JSON)
def to_dict(self):
return {
'id': self.id,
'name': self.name,
'description': self.description,
'avatar': self.avatar_path,
'background': self.background_path,
'category': self.category,
'is_private': self.is_private,
'is_approved': self.is_approved,
'created_at': self.created_at.isoformat(),
'settings': self.settings
}
class CharacterApprovalQueue(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
character_id = db.Column(db.String(36), db.ForeignKey('character.id'), nullable=False)
submitted_at = db.Column(db.DateTime, default=datetime.utcnow)
status = db.Column(db.String(20), default='pending')
reviewer_id = db.Column(db.String(36), db.ForeignKey('user.id'))
review_notes = db.Column(db.Text)
reviewed_at = db.Column(db.DateTime)
character = db.relationship('Character')
reviewer = db.relationship('User')
def to_dict(self):
return {
'id': self.id,
'character': self.character.to_dict(),
'submitted_at': self.submitted_at.isoformat(),
'status': self.status,
'review_notes': self.review_notes,
'reviewed_at': self.reviewed_at.isoformat() if self.reviewed_at else None
}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def kobold_handler(data):
"""Handle Kobold API requests"""
try:
# Your existing Kobold API call
kobold_response = requests.post(
'http://127.0.0.1:5000/v1/chat/completions',
json=data
)
return kobold_response.json()
except Exception as e:
raise Exception(f"Kobold API error: {str(e)}")
def check_kobold_available():
"""Check if KoboldCPP API is available"""
try:
response = requests.get(f'{KOBOLD_API}/api/v1/model')
return response.ok
except:
return False
def handle_kobold_error(response):
"""Handle error responses from KoboldCPP"""
try:
error_data = response.json()
return jsonify({
'error': 'KoboldCPP API error',
'details': error_data.get('detail', str(response.status_code))
}), response.status_code
except:
return jsonify({
'error': 'KoboldCPP API error',
'details': str(response.status_code)
}), response.status_code
def require_kobold(f):
"""Decorator to check if KoboldCPP is available"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not check_kobold_available():
return jsonify({
'error': 'KoboldCPP API is not available'
}), 503
return f(*args, **kwargs)
return decorated_function
def tts_handler(data):
try:
print("TTS handler received data:", data)
text = data.get("text")
character_id = data.get("rvc_model")
edge_voice = data.get("edge_voice")
tts_rate = data.get("tts_rate", 0)
rvc_pitch = data.get("rvc_pitch", 0)
# Get TTS instance from cache
tts = model_cache.get_model(character_id)
unique_id = str(uuid.uuid4())
output_filename = f"response_{unique_id}.wav"
output_path = os.path.join(OUTPUT_DIRECTORY, output_filename)
# Set voice and generate audio
if edge_voice:
tts.set_voice(edge_voice)
tts(
text=text,
pitch=rvc_pitch,
tts_rate=tts_rate,
output_filename=output_path
)
if not os.path.exists(output_path):
raise Exception("Failed to generate audio file")
return {"audio_url": f"/audio/{output_filename}"}
except Exception as e:
print(f"TTS handler error: {str(e)}")
traceback.print_exc()
raise Exception(f"TTS error: {str(e)}")
def prepare_story_context(character, messages, scenario, other_characters):
base_context = {
'role': 'system',
'content': f"""You are {character.name}. {character.system_prompt}
Current Story Setting:
{scenario}
Current Speaker: {character.name}
Player Character: {story.settings.get('userName', 'User')}
Player's Role: {story.settings.get('userPersona', 'A participant in the story')}
Other Characters Present:
{format_character_list(other_characters)}
Story Context Rules:
- You are ONLY speaking when it's natural for {character.name} to respond
- Never speak for other characters or the player character
- Remember previous interactions and maintain story consistency"""
}
recent_context = get_relevant_messages(messages, max_tokens=8000)
return [base_context] + recent_context
def extract_character_traits(character):
"""Parse character settings for key traits and characteristics"""
if character.settings and 'traits' in character.settings:
return character.settings['traits']
return "No specific traits defined"
def format_character_list(characters):
"""Format information about other characters in the scene"""
return "\n".join([
f"- {char.name}: {char.description[:100]}..."
for char in characters
])
def get_relevant_messages(messages, max_tokens=2000):
"""
Implement smart context window that keeps relevant interactions
while staying within token limits.
"""
relevant_messages = []
token_count = 0
# Process messages in reverse to prioritize recent context
for msg in reversed(messages):
estimated_tokens = len(msg['content'].split()) * 1.3 # Rough token estimate
if token_count + estimated_tokens > max_tokens:
break
relevant_messages.insert(0, msg)
token_count += estimated_tokens
return relevant_messages
class StorySetup:
def __init__(self, title, creator_id):
self.id = str(uuid.uuid4())
self.title = title
self.creator_id = creator_id
self.characters = []
self.scenario = ""
self.themes = []
self.relationships = {}
self.scene_settings = {}
PLACEHOLDER_IMAGE = "./assets/placeholders/placeholder.jpg"
PLACEHOLDER_NAME = "Empty Panel"
def parse_character_responses(narrative, valid_characters):
"""
Parse character responses with improved handling for length and completeness.
Args:
narrative (str): Raw narrative text
valid_characters (list): List of tuples containing (character_data, story_character)
"""
responses = []
lines = narrative.split('\n')
current_char = None
current_content = []
max_response_length = 150 # Characters, not tokens
for line in lines:
if ':' not in line:
if current_char and current_content:
current_content.append(line)
continue
char_name, content = line.split(':', 1)
char_name = char_name.strip()
# Check if this is a valid character
if char_name in [c[0]['name'] for c in valid_characters]:
# Process previous character's response if exists
if current_char and current_content:
response_text = ' '.join(current_content).strip()
# Truncate if too long while preserving complete sentences
if len(response_text) > max_response_length:
sentences = response_text.split('.')
truncated = ''
for sent in sentences:
if len(truncated) + len(sent) <= max_response_length:
truncated += sent + '.'
else:
break
response_text = truncated.strip()
# Ensure asterisk expressions are properly closed
if response_text.count('*') % 2 == 1:
response_text = response_text.replace('*', '')
responses.append((current_char, response_text))
current_char = char_name
current_content = [content.strip()]
continue
# Process the last character's response
if current_char and current_content:
response_text = ' '.join(current_content).strip()
if len(response_text) > max_response_length:
sentences = response_text.split('.')
truncated = ''
for sent in sentences:
if len(truncated) + len(sent) <= max_response_length:
truncated += sent + '.'
else:
break
response_text = truncated.strip()
if response_text.count('*') % 2 == 1:
response_text = response_text.replace('*', '')
responses.append((current_char, response_text))
return responses
def generate_character_prompt(story, characters):
"""
Generate a more focused prompt for character interactions.
"""
character_list = "\n".join([
f"- {char[0]['name']}: {char[0].get('description', '')[:100]}..."
for char in characters
])
return f"""You are managing an interactive scene. Setting:
{story.scenario}
Characters present:
{character_list}
Guidelines:
- Keep responses short and focused (1-2 sentences maximum)
- Include either an action OR dialogue, not both
- Avoid repetitive expressions and mannerisms
- Stay in character but be concise
- Never speak for other characters
Format each response as:
CHARACTER_NAME: action/dialogue"""
def process_story_responses(story, valid_characters, user_message, temperature=0.7):
"""
Process story responses with improved controls.
"""
try:
master_prompt = generate_character_prompt(story, valid_characters)
master_response = kobold_handler({
'model': "koboldcpp",
'messages': [{'role': 'system', 'content': master_prompt}],
'temperature': temperature,
'max_tokens': 150, # Reduced from 300
'frequency_penalty': 0.7, # Increased to reduce repetition
'presence_penalty': 0.7,
'stop_sequences': ["\n\n", "###"]
})
if not master_response or 'choices' not in master_response:
raise ValueError("Invalid response from master storyteller")
narrative = master_response['choices'][0]['message']['content']
parsed_responses = parse_character_responses(narrative, valid_characters)
responses = []
for char_name, content in parsed_responses:
matching_char = next(
(char for char, _ in valid_characters if char['name'].lower() == char_name.lower()),
None
)
if matching_char:
char_position = next(
sc.position for _, sc in valid_characters
if sc.character_id == matching_char['id']
)
responses.append({
'character_id': matching_char['id'],
'name': matching_char['name'],
'content': content,
'avatar': matching_char['avatar'],
'position': char_position,
'ttsVoice': matching_char.get('ttsVoice'),
'rvc_model': matching_char.get('rvc_model'),
'tts_rate': matching_char.get('tts_rate', 0),
'rvc_pitch': matching_char.get('rvc_pitch', 0)
})
return responses
except Exception as e:
print(f"Error processing story responses: {str(e)}")
raise
@app.route('/story/setup', methods=['POST'])
@login_required
def create_story_setup():
try:
data = request.json
# Validate minimum character requirement
active_characters = sum(1 for char in data['characters'] if not char.get('is_placeholder', False))
if active_characters < 2:
return jsonify({'error': 'At least two characters are required'}), 400
# Create new story session
story = StorySession(
creator_id=current_user.id,
title=data['title'],
scenario=data['scenario'],
settings={
'active_character_count': active_characters,
'placeholder_panels': [i for i, char in enumerate(data['characters'])
if char.get('is_placeholder', False)]
}
)
db.session.add(story)
db.session.flush() # Get the story ID
# Add characters and placeholders
for char_data in data['characters']:
position = char_data['position']
is_placeholder = char_data.get('is_placeholder', False)
story_char = StoryCharacter(
session_id=story.id,
character_id=None if is_placeholder else char_data['id'],
position=position,
is_placeholder=is_placeholder,
placeholder_name=PLACEHOLDER_NAME if is_placeholder else None
)
db.session.add(story_char)
db.session.commit()
return jsonify({
'message': 'Story session created successfully',
'session_id': story.id
})
except Exception as e:
db.session.rollback()
print(f"Error creating story: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/v1/story/completions', methods=['POST'])
@login_required
def story_completions():
try:
data = request.json
session_id = data.get('session_id')
user_message = data.get('message', '')
temperature = data.get('temperature', 0.7)
# Get story session and validate
story = StorySession.query.get_or_404(session_id)
if story.creator_id != current_user.id:
return jsonify({'error': 'Unauthorized'}), 403
# Get active characters
story_chars = StoryCharacter.query.filter_by(
session_id=session_id,
is_placeholder=False
).order_by(StoryCharacter.position).all()
if not story_chars:
return jsonify({'error': 'No active characters'}), 400
# Calculate credits needed
CREDITS_PER_CHARACTER = 10
total_credits = CREDITS_PER_CHARACTER * len(story_chars)
# Check credits
if not current_user.deduct_credits_atomic(total_credits):
return jsonify({
'error': 'Insufficient credits',
'credits_required': total_credits,
'credits_available': current_user.credits
}), 402
# Create credit transaction
transaction = CreditTransaction(
user_id=current_user.id,
amount=-total_credits,
transaction_type='story_interaction',
description=f'Story interaction in: {story.title}'
)
db.session.add(transaction)
try:
# Load character data
print("\nLoading character data...")
valid_characters = []
for story_char in story_chars:
char_file_path = os.path.join(CHARACTER_FOLDER, f"{story_char.character_id}.json")
if os.path.exists(char_file_path):
with open(char_file_path, 'r', encoding='utf-8') as f:
char_data = json.load(f)
valid_characters.append((char_data, story_char))
print(f"Loaded character: {char_data['name']}")
if not valid_characters:
raise ValueError("No valid characters found")
# Process responses using new function
responses = process_story_responses(
story=story,
valid_characters=valid_characters,
user_message=user_message,
temperature=temperature
)
# Commit transaction and return responses
db.session.commit()
return jsonify({'responses': responses})
except Exception as e:
# Refund credits on error
current_user.add_credits(total_credits)
db.session.delete(transaction)
db.session.commit()
raise e
except Exception as e:
print(f"Error in story_completions: {str(e)}")
return jsonify({'error': str(e)}), 500
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
# Authentication Routes
@app.route('/auth/register', methods=['POST'])
def register():
data = request.json
if not data or not data.get('username') or not data.get('password'):
return jsonify({'error': 'Missing required fields'}), 400
if User.query.filter_by(username=data['username']).first():
return jsonify({'error': 'Username already taken'}), 409
user = User(
username=data['username'],
email=f"{data['username']}@temp.com", # Temporary email since model requires it
created_at=datetime.utcnow()
)
user.set_password(data['password'])
try:
db.session.add(user)
db.session.commit()
login_user(user, remember=True)
session.permanent = True
return jsonify({
'message': 'Registration successful',
'user': {
'id': user.id,
'username': user.username,
'credits': user.credits,
'is_admin': user.is_admin
}
}), 201
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@app.route('/auth/login', methods=['POST'])
def login():
data = request.json
if not data or not data.get('username') or not data.get('password'):
return jsonify({'error': 'Missing credentials'}), 400
user = User.query.filter_by(username=data['username']).first()
if user and user.check_password(data['password']):
login_user(user, remember=True)
session.permanent = True
user.last_login = datetime.utcnow()
db.session.commit()
return jsonify({
'message': 'Login successful',
'user': {
'id': user.id,
'email': user.email,
'username': user.username,
'credits': user.credits,
'is_admin': user.is_admin
}
}), 200
return jsonify({'error': 'Invalid credentials'}), 401
@app.route('/auth/logout')
@login_required
def logout():
logout_user()
return jsonify({'message': 'Logged out successfully'}), 200
@app.route('/auth/user')
@login_required
def get_user():
return jsonify({
'user': {
'id': current_user.id,
'email': current_user.email,
'username': current_user.username,
'credits': current_user.credits, # Added missing comma here
'is_admin': current_user.is_admin
}
}), 200
# Static Routes
@app.route('/')
def serve_index():
return send_from_directory(STATIC_DIR, 'index.html')
@app.route('/<path:path>')
def serve_static(path):
try:
# Strip any route prefixes
if path.startswith('edit-character/'):
path = path.replace('edit-character/', '', 1)
if path.startswith('admin-dashboard/'): # Add this line
path = path.replace('admin-dashboard/', '', 1) # Add this line
if path.startswith('css/') or path.startswith('js/'):
return send_from_directory(STATIC_DIR, path)
return send_from_directory(STATIC_DIR, path)
except Exception as e:
print(f"Error serving {path}: {e}")
return f"Error: Could not serve {path}", 404
@app.route('/chat/<path:filename>')
def serve_chat_files(filename):
try:
# Map extensions to MIME types
mime_types = {
'js': 'application/javascript',
'css': 'text/css',
'html': 'text/html'
}
# Get file extension
ext = filename.split('.')[-1]
mime_type = mime_types.get(ext, 'text/plain')
# Send file with correct MIME type
response = send_from_directory(os.path.join(STATIC_DIR, 'chat'), filename)
response.headers['Content-Type'] = mime_type
return response
except Exception as e:
print(f"Error serving chat file {filename}: {e}")
return f"Error: Could not serve {filename}", 404
@app.route('/v1/tts', methods=['POST'])
@login_required
def tts():
if request.method == 'OPTIONS':
return handle_options()
try:
CREDITS_PER_TTS = 5
# Check if user has enough credits
if not current_user.deduct_credits_atomic(CREDITS_PER_TTS):
return jsonify({
'error': 'Insufficient credits',
'credits_required': CREDITS_PER_TTS,
'credits_available': current_user.credits
}), 402
# Create transaction record
transaction = CreditTransaction(
user_id=current_user.id,
amount=-CREDITS_PER_TTS,
transaction_type='tts',
description='Text-to-speech conversion'
)
db.session.add(transaction)
# Add request to queue
data = request.json
request_id = request_queue.add_request(current_user.id, 'tts', data)
# Check initial status
status = request_queue.get_status(request_id)
if status['status'] == 'queued' and status['position'] > 3:
return jsonify({
'status': 'queued',
'position': status['position'],
'request_id': request_id
})
# Poll for completion if position is low
max_attempts = 30
for _ in range(max_attempts):
status = request_queue.get_status(request_id)
if status['status'] == 'complete':
db.session.commit()
return jsonify(status['result'])
elif status['status'] == 'error':
current_user.add_credits(CREDITS_PER_TTS)
db.session.delete(transaction)
db.session.commit()
return jsonify({'error': status['result']['error']}), 500
time.sleep(1)
# Timeout - refund credits
current_user.add_credits(CREDITS_PER_TTS)
db.session.delete(transaction)
db.session.commit()
return jsonify({'error': 'Request timeout'}), 408
except Exception as e:
if 'transaction' in locals():
current_user.add_credits(CREDITS_PER_TTS)
db.session.delete(transaction)
db.session.commit()
return jsonify({'error': str(e)}), 500
@app.route('/v1/chat/status/<request_id>')
@login_required
def check_chat_status(request_id):
status = request_queue.get_status(request_id)
if not status:
return jsonify({'error': 'Request not found'}), 404
return jsonify(status)
@app.route('/v1/chat/completions', methods=['POST'])
@login_required
def chat_completions():
if request.method == 'OPTIONS':
return handle_options()
try:
CREDITS_PER_MESSAGE = 10
# Check if user has enough credits
if not current_user.deduct_credits_atomic(CREDITS_PER_MESSAGE):
return jsonify({
'error': 'Insufficient credits',
'credits_required': CREDITS_PER_MESSAGE,
'credits_available': current_user.credits
}), 402
# Create transaction record
transaction = CreditTransaction(
user_id=current_user.id,
amount=-CREDITS_PER_MESSAGE,
transaction_type='message',
description='Chat completion message'
)
db.session.add(transaction)
# Add request to queue
data = request.json
request_id = request_queue.add_request(current_user.id, 'chat', data)
# Check initial status
status = request_queue.get_status(request_id)
if status['status'] == 'queued' and status['position'] > 3:
# Return queued status if position is high
return jsonify({
'status': 'queued',
'position': status['position'],
'request_id': request_id
})
# Poll for completion if position is low
max_attempts = 30 # 30 second timeout
for _ in range(max_attempts):
status = request_queue.get_status(request_id)
if status['status'] == 'complete':
db.session.commit() # Commit the transaction
return jsonify(status['result'])
elif status['status'] == 'error':
# Refund credits on error
current_user.add_credits(CREDITS_PER_MESSAGE)
db.session.delete(transaction)
db.session.commit()
return jsonify({'error': status['result']['error']}), 500
time.sleep(1)
# Timeout - refund credits
current_user.add_credits(CREDITS_PER_MESSAGE)
db.session.delete(transaction)
db.session.commit()
return jsonify({'error': 'Request timeout'}), 408
except Exception as e:
if 'transaction' in locals():