Krish2606 commited on
Commit
b3f587f
Β·
1 Parent(s): 4c2ce90

Switch to Gemma 4 model, add retry logic, fix voice rate limits, fix subtitle bar glitch

Browse files
backend/ai_service.py CHANGED
@@ -18,9 +18,11 @@ class AIService:
18
 
19
  def _call_api(self, system_prompt, contents, timeout=60):
20
  """
21
- Send a request to OpenRouter API.
22
  `contents` should be a list of {'role': 'user'|'assistant', 'content': str}
23
  """
 
 
24
  headers = {
25
  "Content-Type": "application/json",
26
  "Authorization": f"Bearer {self.api_key}",
@@ -40,20 +42,27 @@ class AIService:
40
  "messages": messages
41
  }
42
 
43
- response = requests.post(self.base_url, headers=headers, json=payload, timeout=timeout)
44
-
45
- if response.status_code == 200:
46
- data = response.json()
47
- try:
48
- return data['choices'][0]['message']['content']
49
- except (KeyError, IndexError):
50
- return None
51
- elif response.status_code in [400, 401, 403]:
52
- return "API Key is missing or invalid. Please check your backend configuration."
53
- elif response.status_code == 429:
54
- return "API rate limit reached. Please wait a moment and try again."
55
- else:
56
- return f"AI API Error (HTTP {response.status_code}): {response.text[:200]}"
 
 
 
 
 
 
 
57
 
58
  # ── Public methods ───────────────────────────────────────────────
59
 
 
18
 
19
  def _call_api(self, system_prompt, contents, timeout=60):
20
  """
21
+ Send a request to OpenRouter API with automatic retry on rate limits.
22
  `contents` should be a list of {'role': 'user'|'assistant', 'content': str}
23
  """
24
+ import time
25
+
26
  headers = {
27
  "Content-Type": "application/json",
28
  "Authorization": f"Bearer {self.api_key}",
 
42
  "messages": messages
43
  }
44
 
45
+ max_retries = 3
46
+ for attempt in range(max_retries + 1):
47
+ response = requests.post(self.base_url, headers=headers, json=payload, timeout=timeout)
48
+
49
+ if response.status_code == 200:
50
+ data = response.json()
51
+ try:
52
+ return data['choices'][0]['message']['content']
53
+ except (KeyError, IndexError):
54
+ return None
55
+ elif response.status_code == 429:
56
+ if attempt < max_retries:
57
+ wait_time = 2 ** (attempt + 1) # 2s, 4s, 8s
58
+ print(f"Rate limited (429). Retrying in {wait_time}s... (attempt {attempt + 1}/{max_retries})")
59
+ time.sleep(wait_time)
60
+ continue
61
+ return "API rate limit reached. Please wait a moment and try again."
62
+ elif response.status_code in [400, 401, 403]:
63
+ return "API Key is missing or invalid. Please check your backend configuration."
64
+ else:
65
+ return f"AI API Error (HTTP {response.status_code}): {response.text[:200]}"
66
 
67
  # ── Public methods ───────────────────────────────────────────────
68
 
backend/config.py CHANGED
@@ -42,7 +42,7 @@ class Config:
42
 
43
  # OpenRouter Settings
44
  OPENROUTER_API_KEY = os.environ.get('OPENROUTER_API_KEY', '')
45
- OPENROUTER_MODEL = os.environ.get('OPENROUTER_MODEL', 'openrouter/auto')
46
 
47
  # Session - Fixed for proper cookie handling
48
  SESSION_TYPE = 'filesystem'
 
42
 
43
  # OpenRouter Settings
44
  OPENROUTER_API_KEY = os.environ.get('OPENROUTER_API_KEY', '')
45
+ OPENROUTER_MODEL = os.environ.get('OPENROUTER_MODEL', 'google/gemma-4-31b-it:free')
46
 
47
  # Session - Fixed for proper cookie handling
48
  SESSION_TYPE = 'filesystem'
frontend/js/pages/share-access.js CHANGED
@@ -809,10 +809,15 @@ const ShareVideoPage = {
809
  padding: 0.6rem 1rem;
810
  text-align: center;
811
  transition: all 0.3s ease;
 
 
 
 
 
812
  }
813
 
814
  .vc-subtitles:empty {
815
- opacity: 0;
816
  }
817
 
818
  .vc-subtitle-line {
 
809
  padding: 0.6rem 1rem;
810
  text-align: center;
811
  transition: all 0.3s ease;
812
+ display: none;
813
+ }
814
+
815
+ .vc-subtitles:not(:empty) {
816
+ display: block;
817
  }
818
 
819
  .vc-subtitles:empty {
820
+ display: none;
821
  }
822
 
823
  .vc-subtitle-line {
frontend/js/pages/video-call.js CHANGED
@@ -101,6 +101,7 @@ const VideoCallPage = {
101
  this._voiceRequestId = 0;
102
  this._pendingSpeechTimer = null;
103
  this._pendingSpeechText = '';
 
104
  },
105
 
106
  renderVideoCall(container) {
@@ -401,11 +402,15 @@ const VideoCallPage = {
401
  padding: 0.75rem 1.25rem;
402
  text-align: center;
403
  transition: opacity 0.3s ease;
 
 
 
 
 
404
  }
405
 
406
  .vc-subtitles:empty {
407
- opacity: 0;
408
- padding: 0;
409
  }
410
 
411
  .vc-subtitle-line {
@@ -786,10 +791,13 @@ const VideoCallPage = {
786
  const combined = this._pendingSpeechText.trim();
787
  this._pendingSpeechText = '';
788
  this._pendingSpeechTimer = null;
789
- if (combined) {
790
  this.sendVoiceMessage(combined);
 
 
 
791
  }
792
- }, 800);
793
  }
794
  };
795
 
@@ -863,6 +871,15 @@ const VideoCallPage = {
863
  },
864
 
865
  async sendVoiceMessage(content) {
 
 
 
 
 
 
 
 
 
866
  // ── REQUEST GENERATION COUNTER ──
867
  // Increment to invalidate any in-flight request's response.
868
  // Only the latest request's response will be spoken.
@@ -912,6 +929,15 @@ const VideoCallPage = {
912
  Toast.error('Failed to send message');
913
  this.updateStatus('Listening...', true);
914
  }
 
 
 
 
 
 
 
 
 
915
  }
916
  },
917
 
 
101
  this._voiceRequestId = 0;
102
  this._pendingSpeechTimer = null;
103
  this._pendingSpeechText = '';
104
+ this._isProcessingVoice = false;
105
  },
106
 
107
  renderVideoCall(container) {
 
402
  padding: 0.75rem 1.25rem;
403
  text-align: center;
404
  transition: opacity 0.3s ease;
405
+ display: none;
406
+ }
407
+
408
+ .vc-subtitles:not(:empty) {
409
+ display: block;
410
  }
411
 
412
  .vc-subtitles:empty {
413
+ display: none;
 
414
  }
415
 
416
  .vc-subtitle-line {
 
791
  const combined = this._pendingSpeechText.trim();
792
  this._pendingSpeechText = '';
793
  this._pendingSpeechTimer = null;
794
+ if (combined && !this._isProcessingVoice) {
795
  this.sendVoiceMessage(combined);
796
+ } else if (combined && this._isProcessingVoice) {
797
+ // Queue: re-set pending text so it fires after current request completes
798
+ this._pendingSpeechText = combined;
799
  }
800
+ }, 1500);
801
  }
802
  };
803
 
 
871
  },
872
 
873
  async sendVoiceMessage(content) {
874
+ // ── CONCURRENCY GUARD ──
875
+ // Prevent multiple simultaneous API calls that burn through rate limits
876
+ if (this._isProcessingVoice) {
877
+ console.log('Voice request already in progress, queueing...');
878
+ this._pendingSpeechText += (this._pendingSpeechText ? ' ' : '') + content;
879
+ return;
880
+ }
881
+ this._isProcessingVoice = true;
882
+
883
  // ── REQUEST GENERATION COUNTER ──
884
  // Increment to invalidate any in-flight request's response.
885
  // Only the latest request's response will be spoken.
 
929
  Toast.error('Failed to send message');
930
  this.updateStatus('Listening...', true);
931
  }
932
+ } finally {
933
+ this._isProcessingVoice = false;
934
+
935
+ // Process any queued speech that arrived while we were busy
936
+ if (this._pendingSpeechText.trim()) {
937
+ const queued = this._pendingSpeechText.trim();
938
+ this._pendingSpeechText = '';
939
+ this.sendVoiceMessage(queued);
940
+ }
941
  }
942
  },
943