File size: 7,136 Bytes
55b95aa
 
6db868f
 
55b95aa
6db868f
 
55b95aa
6db868f
 
55b95aa
 
 
6db868f
 
 
 
 
 
844f21c
6db868f
844f21c
6db868f
 
 
 
55b95aa
 
 
 
 
6db868f
 
 
55b95aa
6db868f
 
 
 
 
55b95aa
6db868f
55b95aa
6db868f
 
 
55b95aa
 
 
6db868f
 
55b95aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32d0583
55b95aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32d0583
844f21c
32d0583
 
844f21c
32d0583
 
6db868f
d2a66d9
6db868f
55b95aa
6db868f
 
 
844f21c
6db868f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55b95aa
844f21c
6db868f
844f21c
 
 
55b95aa
6db868f
 
 
 
 
844f21c
6db868f
844f21c
6db868f
 
 
 
55b95aa
 
 
 
 
6db868f
 
 
 
 
 
 
 
 
 
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
// src/contexts/AppContext.tsx (نسخه نهایی با اصلاح منطق اتصال)
import React, { createContext, FC, ReactNode, useContext, useEffect, useState, useCallback, useRef } from "react";
import { useLiveAPI, type UseLiveAPIResults } from "../hooks/use-live-api";
import { LiveConfig } from "../multimodal-live-types";
import { speakers } from '../data/speakers';

const LS_SELECTED_PERSONALITY = 'app_selected_personality';
const LS_SELECTED_VOICE = 'app_selected_voice';
const LS_CUSTOM_NAME = 'app_custom_name';
const LS_CUSTOM_INSTRUCTIONS = 'app_custom_instructions';
const LS_TIMER_SECONDS = 'app_timer_seconds';
const LS_TIMER_DATE = 'app_timer_date';
const DAILY_LIMIT_SECONDS = 900;

export type PersonalityType = "default" | "teacher" | "poetic" | "funny" | "custom";
export type PersonalityInstructions = Partial<Record<PersonalityType, string>>;

interface AppContextType extends UseLiveAPIResults {
  selectedPersonality: PersonalityType;
  selectedVoice: string;
  changePersonality: (personality: PersonalityType, customDetails?: { name: string, instructions: string }) => void;
  changeVoice: (voiceId: string) => void;
  personalityInstructions: PersonalityInstructions;
  customUserName: string;
  customInstructions: string;
  isRestarting: boolean;
  remainingTime: number;
  isTimeUp: boolean;
  isTimerActive: boolean;
  startTimer: () => void;
  stopTimer: () => void;
}

const AppContext = createContext<AppContextType | undefined>(undefined);
const BASE_INSTRUCTION = `تو یک دستیار صوتی و تصویری پیشرفته از برنامه هوش مصنوعی آلفا هستی. همیشه به زبان فارسی روان، دقیق و طبیعی صحبت کن. هرگز خودت را به عنوان محصول شرکت دیگری معرفی نکن تو توسط هوش مصنوعی آلفا ساخته و توسعه داده شدی. در پاسخ‌های خود از ایموجی یا شکلک استفاده نکن.`;

export const AppProvider: FC<{ children: ReactNode; initialConfig?: LiveConfig; personalityInstructions: PersonalityInstructions; url?: string; }> = ({
  children, initialConfig, personalityInstructions, url
}) => {
  const liveAPI = useLiveAPI({ url });
  const timerIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const [selectedPersonality, setSelectedPersonality] = useState<PersonalityType>(() => (localStorage.getItem(LS_SELECTED_PERSONALITY) as PersonalityType) || 'default');
  const [selectedVoice, setSelectedVoice] = useState<string>(() => localStorage.getItem(LS_SELECTED_VOICE) || speakers[0].id);
  const [customUserName, setCustomUserName] = useState<string>(() => localStorage.getItem(LS_CUSTOM_NAME) || '');
  const [customInstructions, setCustomInstructions] = useState<string>(() => localStorage.getItem(LS_CUSTOM_INSTRUCTIONS) || '');
  const [isRestarting, setIsRestarting] = useState(false);
  const [remainingTime, setRemainingTime] = useState<number>(DAILY_LIMIT_SECONDS);
  const [isTimerActive, setIsTimerActive] = useState(false);
  const isTimeUp = remainingTime <= 0;

  useEffect(() => {
    const today = new Date().toLocaleDateString('fa-IR');
    const storedDate = localStorage.getItem(LS_TIMER_DATE);
    if (storedDate === today) {
      const storedTime = parseInt(localStorage.getItem(LS_TIMER_SECONDS) || `${DAILY_LIMIT_SECONDS}`, 10);
      setRemainingTime(storedTime);
    } else {
      localStorage.setItem(LS_TIMER_DATE, today);
      localStorage.setItem(LS_TIMER_SECONDS, `${DAILY_LIMIT_SECONDS}`);
      setRemainingTime(DAILY_LIMIT_SECONDS);
    }
  }, []);

  const stopTimer = useCallback(() => {
    if (timerIntervalRef.current) {
      clearInterval(timerIntervalRef.current);
      timerIntervalRef.current = null;
    }
    setIsTimerActive(false);
  }, []);

  const startTimer = useCallback(() => {
    if (isTimeUp || timerIntervalRef.current) return;
    setIsTimerActive(true);
    timerIntervalRef.current = setInterval(() => {
      setRemainingTime(prevTime => {
        const newTime = Math.max(0, prevTime - 1);
        localStorage.setItem(LS_TIMER_SECONDS, `${newTime}`);
        if (newTime <= 0) stopTimer();
        return newTime;
      });
    }, 1000);
  }, [isTimeUp, stopTimer]);
  
  useEffect(() => {
    let instructionParts = [BASE_INSTRUCTION];
    if (customUserName) instructionParts.push(`نام کاربر ${customUserName} است. او را با نامش صدا بزن.`);
    if (selectedPersonality === 'custom') {
        if (customInstructions) instructionParts.push(customInstructions);
    } else {
        const personalityPrompt = personalityInstructions[selectedPersonality];
        if (personalityPrompt) instructionParts.push(personalityPrompt);
    }
    const finalInstruction = instructionParts.join('\n\n');
    const newConfig: LiveConfig = {
      model: "models/gemini-live-2.5-flash-preview",
      tools: [{ googleSearch: {} }],
      generationConfig: { responseModalities: "audio", speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: selectedVoice } } } },
      systemInstruction: { parts: [{ text: finalInstruction.trim() }] },
    };
    liveAPI.setConfig(newConfig);
  }, [selectedPersonality, selectedVoice, customUserName, customInstructions, personalityInstructions, liveAPI.setConfig, initialConfig]);

  useEffect(() => {
    if (isRestarting && !liveAPI.connected) {
      const timer = setTimeout(() => liveAPI.connect().then(() => setIsRestarting(false)), 200);
      return () => clearTimeout(timer);
    }
  }, [isRestarting, liveAPI.connected, liveAPI.connect]);

  const changePersonality = useCallback((newPersonality: PersonalityType, customDetails?: { name: string; instructions: string }) => {
    if (newPersonality === 'custom' && customDetails) {
      localStorage.setItem(LS_CUSTOM_NAME, customDetails.name);
      localStorage.setItem(LS_CUSTOM_INSTRUCTIONS, customDetails.instructions);
      setCustomUserName(customDetails.name);
      setCustomInstructions(customDetails.instructions);
    }
    localStorage.setItem(LS_SELECTED_PERSONALITY, newPersonality);
    setSelectedPersonality(newPersonality);
    if (liveAPI.connected) { setIsRestarting(true); liveAPI.disconnect(); }
  }, [liveAPI.connected, liveAPI.disconnect]);

  const changeVoice = useCallback((voiceId: string) => {
    localStorage.setItem(LS_SELECTED_VOICE, voiceId);
    setSelectedVoice(voiceId);
    if (liveAPI.connected) { setIsRestarting(true); liveAPI.disconnect(); }
  }, [liveAPI.connected, liveAPI.disconnect]);

  const contextValue: AppContextType = {
    ...liveAPI,
    selectedPersonality,
    selectedVoice,
    changePersonality,
    changeVoice,
    personalityInstructions,
    customUserName,
    customInstructions,
    isRestarting,
    remainingTime,
    isTimeUp,
    isTimerActive,
    startTimer,
    stopTimer,
  };

  return <AppContext.Provider value={contextValue}>{children}</AppContext.Provider>;
};

export const useAppContext = (): AppContextType => {
  const context = useContext(AppContext);
  if (!context) throw new Error("useAppContext must be used within an AppProvider");
  return context;
};