File size: 5,615 Bytes
0961faf
c4bf3b5
 
e7e3aa3
 
c4bf3b5
 
 
 
 
 
 
 
 
 
 
e7e3aa3
 
 
 
 
 
 
c4bf3b5
 
 
0961faf
 
c4bf3b5
e7e3aa3
c4bf3b5
 
 
0961faf
e7e3aa3
 
 
 
c4bf3b5
e7e3aa3
c4bf3b5
 
e7e3aa3
c4bf3b5
 
e7e3aa3
c4bf3b5
e7e3aa3
 
 
 
 
 
 
c4bf3b5
e7e3aa3
 
 
 
 
 
c4bf3b5
 
e7e3aa3
 
 
 
 
 
 
 
 
 
c4bf3b5
 
 
 
 
 
 
 
 
e7e3aa3
dbb9e5b
c4bf3b5
e7e3aa3
c4bf3b5
 
e7e3aa3
 
 
 
 
 
 
 
c4bf3b5
 
 
 
 
 
 
 
e7e3aa3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4bf3b5
e7e3aa3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4bf3b5
e7e3aa3
 
 
c4bf3b5
 
 
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
import spaces
import gradio as gr

from pathlib import Path

from src.vectorstore.faiss_index import load_index
from src.vectorstore.metadata_store import load_metadata

from src.retrieval.retriever import retrieve
from src.retrieval.reranker import rerank

from src.llm.generator import generate_answer
from src.llm.postprocessing import clean_answer

from src.data_processing.txt_embeddings import compute_embeddings

from src.voice.assistant import text_to_audio
from src.voice.speech_to_text import transcribe_audio


# ============================================================
# Chargement des ressources
# ============================================================

BASE_DIR = Path(__file__).parent

INDEX_PATH = str(BASE_DIR / "data/vectorstore/faiss.index")
METADATA_PATH = str(BASE_DIR / "data/metadata/metadata.json")


index = load_index(INDEX_PATH)
metadata = load_metadata(METADATA_PATH)


# ============================================================
# Fonction RAG + TTS
# ============================================================
@spaces.GPU

#
def chat_fn(message, history):

    # 1. Embedding question
    query_emb = compute_embeddings([message])


    # 2. Retrieval FAISS
    docs = retrieve(
        query_emb,
        index,
        metadata,
        top_k=10
    )


    # 3. Reranking
    docs = rerank(
        message,
        docs,
        top_k=4
    )


    # 4. Construction contexte
    context = "\n\n".join(
        [
            doc["text"]
            for doc, score in docs
        ]
    )


    # 5. Prompt LLM
    prompt = f"""
Context:
{context}

Question:
{message}

Answer:
"""
    # 6. Génération réponse
    answer = generate_answer(prompt)

    # 7. Nettoyage
    answer = clean_answer(answer)

    # 8. Génération audio Kokoro

    try:
        audio = text_to_audio(answer)
    except Exception:
        audio = None

    # Debug sources
    debug = "\n\n".join(
        [
            f"📄 Chunk {i+1} (Score : {score:.3f})\n{doc['text']}"
            for i, (doc, score) in enumerate(docs)
        ]
    )


    final_output = (
        f"{answer}\n\n"
        "---\n\n"
        f"🔍 Retrieved chunks:\n{debug}"
    )

    return final_output, audio

#
def respond_audio(audio, history):

    print("respond_audio appelée")
    print(audio)

    if audio is None:
        return history, None

    if history is None:
        history = []

    message = transcribe_audio(audio)

    answer, output_audio = chat_fn(
        message,
        history
    )

    history.append(
        {
            "role": "user",
            "content": message
        }
    )

    history.append(
        {
            "role": "assistant",
            "content": answer
        }
    )

    return history, output_audio

# ============================================================
# Interface Gradio
# ============================================================

with gr.Blocks() as demo:

    gr.Markdown(
        "# 💬 RAG Assistant vocal"
    )


    # ========================================================
    # Ligne 1 : Chatbot
    # ========================================================

    chatbot = gr.Chatbot(
        label="Conversation",
        height=450
    )


    # ========================================================
    # Ligne 2 : Question texte
    # ========================================================

    msg = gr.Textbox(
        placeholder="Pose ta question...",
        label="✍️ Question texte"
    )


    # ========================================================
    # Ligne 3 : Audio entrée / sortie
    # ========================================================

    with gr.Row():

        with gr.Column():

            audio_input = gr.Audio(
                sources=[
                    "microphone",
                    "upload"
                ],
                type="filepath",
                waveform_options=gr.WaveformOptions(
                    show_recording_waveform=True
                ),
                label="🎤 Parlez ou déposez un fichier audio"
            )


        with gr.Column():

            audio_output = gr.Audio(
                label="🔊 Réponse audio"
            )


    # ========================================================
    # Réponse texte
    # ========================================================

    def respond(message, history):

        if history is None:
            history = []

        answer, audio = chat_fn(
            message,
            history
        )


        history.append(
            {
                "role": "user",
                "content": message
            }
        )


        history.append(
            {
                "role": "assistant",
                "content": answer
            }
        )


        return (
            "",
            history,
            audio
        )

    # ========================================================
    # Events
    # ========================================================

    msg.submit(
        respond,
        inputs=[
            msg,
            chatbot
        ],
        outputs=[
            msg,
            chatbot,
            audio_output
        ]
    )


    audio_input.change(
        respond_audio,
        inputs=[
            audio_input,
            chatbot
        ],
        outputs=[
            chatbot,
            audio_output
        ]
    )

# ============================================================
# Run
# ============================================================

if __name__ == "__main__":
    demo.launch()