File size: 36,953 Bytes
9f620cb
 
 
e0001dd
9f620cb
 
 
 
 
 
 
 
3cf7a11
 
 
 
08bb753
3cf7a11
 
 
e1f3e45
 
9f620cb
3cf7a11
9f620cb
 
 
3cf7a11
 
9f620cb
 
 
3cf7a11
 
 
 
 
 
9f620cb
 
 
3cf7a11
 
9f620cb
 
3cf7a11
 
 
 
 
08bb753
3cf7a11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f620cb
3cf7a11
9f620cb
 
3cf7a11
 
 
 
9f620cb
3cf7a11
 
 
 
 
 
9f620cb
 
3cf7a11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f620cb
 
3dad413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cf7a11
 
 
 
 
9f620cb
3cf7a11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f620cb
089275b
 
 
 
946f51b
9f620cb
 
 
3cf7a11
9f620cb
3cf7a11
 
 
 
 
9f620cb
3cf7a11
 
9f620cb
 
 
 
3cf7a11
 
 
 
 
 
 
 
 
9f620cb
3cf7a11
9f620cb
 
c323aff
 
 
 
 
 
 
7804112
 
cdbc647
 
e0001dd
 
 
 
c323aff
 
3cf7a11
4922cfb
9f620cb
3cf7a11
 
9f620cb
d8c510a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a7a75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c323aff
 
02a7a75
c323aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a7a75
c323aff
 
 
 
 
 
 
 
02a7a75
c323aff
 
 
 
 
 
02a7a75
c323aff
 
 
 
 
 
 
02a7a75
c323aff
 
 
 
 
02a7a75
c323aff
 
 
 
02a7a75
c323aff
 
 
 
 
02a7a75
c323aff
 
 
 
 
 
 
 
 
 
e0001dd
c323aff
 
02a7a75
 
 
 
c323aff
02a7a75
 
52b50a9
 
 
df0e374
c323aff
be356a8
 
e1f3e45
be356a8
 
 
 
 
 
fc9d154
 
 
be356a8
2a881cf
b66908e
be356a8
fc9d154
 
be356a8
 
fc9d154
 
be356a8
 
 
 
 
 
 
 
 
 
fc9d154
 
 
be356a8
 
 
 
 
fc9d154
 
be356a8
 
 
 
 
 
 
 
 
 
 
fc9d154
 
be356a8
 
fc9d154
 
be356a8
 
 
 
 
 
 
 
 
fc9d154
 
be356a8
 
 
 
 
 
fc9d154
 
be356a8
 
 
 
 
fc9d154
 
be356a8
 
 
fc9d154
 
be356a8
 
fc9d154
 
 
85baf0a
be356a8
cd51cb3
 
85baf0a
cd51cb3
be356a8
08bb753
 
 
 
 
 
 
 
 
 
0bf9c17
08bb753
 
85baf0a
08bb753
be356a8
63e3c09
be356a8
 
 
 
 
 
 
 
cd51cb3
 
 
 
 
08bb753
 
0bf9c17
08bb753
 
 
cd51cb3
 
 
be356a8
 
 
cd51cb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8855231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e47f628
85baf0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be356a8
0166a8d
be356a8
 
8855231
be356a8
 
 
 
8855231
 
 
be356a8
 
8855231
be356a8
 
8855231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be356a8
 
 
 
 
cd155d1
be356a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4568a73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be356a8
 
 
 
 
 
 
 
 
 
4568a73
 
be356a8
4568a73
 
 
be356a8
 
4568a73
 
 
 
 
 
 
be356a8
4568a73
 
be356a8
 
 
 
 
 
 
acb7838
be356a8
 
 
 
 
 
 
acb7838
be356a8
 
 
 
 
 
 
 
 
 
 
 
 
acb7838
be356a8
 
 
 
 
 
acb7838
be356a8
 
 
acb7838
be356a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acb7838
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
import gradio as gr
from langchain_mistralai.chat_models import ChatMistralAI
from langchain.prompts import ChatPromptTemplate
from langchain_deepseek import ChatDeepSeek
import os
from pathlib import Path
import json
import faiss
import numpy as np
from langchain.schema import Document
import pickle
import re
import requests
from functools import lru_cache
import torch
from sentence_transformers import SentenceTransformer
from sentence_transformers.cross_encoder import CrossEncoder
import threading
from queue import Queue
import concurrent.futures
from typing import Generator, Tuple
import time

class OptimizedRAGLoader:
    def __init__(self,
                 docs_folder: str = "./docs",
                 splits_folder: str = "./splits",
                 index_folder: str = "./index"):
        
        self.docs_folder = Path(docs_folder)
        self.splits_folder = Path(splits_folder)
        self.index_folder = Path(index_folder)
        
        # Create folders if they don't exist
        for folder in [self.splits_folder, self.index_folder]:
            folder.mkdir(parents=True, exist_ok=True)
            
        # File paths
        self.splits_path = self.splits_folder / "splits.json"
        self.index_path = self.index_folder / "faiss.index"
        self.documents_path = self.index_folder / "documents.pkl"
        
        # Initialize components
        self.index = None
        self.indexed_documents = None
        
        # Initialize encoder model
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.encoder = SentenceTransformer("intfloat/multilingual-e5-large")
        self.encoder.to(self.device)
        self.reranker = model = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1",trust_remote_code=True)
        
        # Initialize thread pool
        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)
        
        # Initialize response cache
        self.response_cache = {}
        
    @lru_cache(maxsize=1000)
    def encode(self, text: str):
        """Cached encoding function"""
        with torch.no_grad():
            embeddings = self.encoder.encode(
                text,
                convert_to_numpy=True,
                normalize_embeddings=True
            )
        return embeddings
    
    def batch_encode(self, texts: list):
        """Batch encoding for multiple texts"""
        with torch.no_grad():
            embeddings = self.encoder.encode(
                texts,
                batch_size=32,
                convert_to_numpy=True,
                normalize_embeddings=True,
                show_progress_bar=False
            )
        return embeddings

    def load_and_split_texts(self):
        if self._splits_exist():
            return self._load_existing_splits()
            
        documents = []
        futures = []
        
        for file_path in self.docs_folder.glob("*.txt"):
            future = self.executor.submit(self._process_file, file_path)
            futures.append(future)
            
        for future in concurrent.futures.as_completed(futures):
            documents.extend(future.result())
            
        self._save_splits(documents)
        return documents
    
    def _process_file(self, file_path):
        with open(file_path, 'r', encoding='utf-8') as file:
            text = file.read()
            chunks = [s.strip() for s in re.split(r'(?<=[.!?])\s+', text) if s.strip()]
            
            return [
                Document(
                    page_content=chunk,
                    metadata={
                        'source': file_path.name,
                        'chunk_id': i,
                        'total_chunks': len(chunks)
                    }
                )
                for i, chunk in enumerate(chunks)
            ]

    def load_index(self) -> bool:
        """
        Charge l'index FAISS et les documents associés s'ils existent

        Returns:
            bool: True si l'index a été chargé, False sinon
        """
        if not self._index_exists():
            print("Aucun index trouvé.")
            return False

        print("Chargement de l'index existant...")
        try:
            # Charger l'index FAISS
            self.index = faiss.read_index(str(self.index_path))

            # Charger les documents associés
            with open(self.documents_path, 'rb') as f:
                self.indexed_documents = pickle.load(f)

            print(f"Index chargé avec {self.index.ntotal} vecteurs")
            return True

        except Exception as e:
            print(f"Erreur lors du chargement de l'index: {e}")
            return False

    def create_index(self, documents=None):
        if documents is None:
            documents = self.load_and_split_texts()
            
        if not documents:
            return False
            
        texts = [doc.page_content for doc in documents]
        embeddings = self.batch_encode(texts)
        
        dimension = embeddings.shape[1]
        self.index = faiss.IndexFlatL2(dimension)
        
        if torch.cuda.is_available():
            # Use GPU for FAISS if available
            res = faiss.StandardGpuResources()
            self.index = faiss.index_cpu_to_gpu(res, 0, self.index)
            
        self.index.add(np.array(embeddings).astype('float32'))
        self.indexed_documents = documents
        
        # Save index and documents
        cpu_index = faiss.index_gpu_to_cpu(self.index) if torch.cuda.is_available() else self.index
        faiss.write_index(cpu_index, str(self.index_path))
        
        with open(self.documents_path, 'wb') as f:
            pickle.dump(documents, f)
            
        return True

    def _index_exists(self) -> bool:
        """Vérifie si l'index et les documents associés existent"""
        return self.index_path.exists() and self.documents_path.exists()

    def get_retriever(self, k: int = 10):
        if self.index is None:
            if not self.load_index():
                if not self.create_index():
                    raise ValueError("Unable to load or create index")

        def retriever_function(query: str) -> list:
            # Check cache first
            cache_key = f"{query}_{k}"
            if cache_key in self.response_cache:
                return self.response_cache[cache_key]

            query_embedding = self.encode(query)
            
            distances, indices = self.index.search(
                np.array([query_embedding]).astype('float32'),
                k
            )
            
            results = [
                self.indexed_documents[idx]
                for idx in indices[0]
                if idx != -1
            ]
            
            # Cache the results
            self.response_cache[cache_key] = results
            return results
            
        return retriever_function

# # Initialize components
# mistral_api_key = os.getenv("mistral_api_key")
# llm = ChatMistralAI(
#     model="mistral-large-latest",
#     mistral_api_key=mistral_api_key,
#     temperature=0.01,
#     streaming=True,
# )

DEEPSEEK_KEY = os.getenv("DEEPSEEK_KEY")

llm = ChatDeepSeek(
    model="deepseek-chat",
    temperature=0,
    api_key=DEEPSEEK_KEY
)

rag_loader = OptimizedRAGLoader()
retriever = rag_loader.get_retriever(k=5)  # Reduced k for faster retrieval

# Cache for processed questions
question_cache = {}

# prompt_template = ChatPromptTemplate.from_messages([
#     ("system", """أنت مساعد مفيد يجيب على الأسئلة باللغة العربية باستخدام المعلومات المقدمة.
#     استخدم المعلومات التالية للإجابة على السؤال:

#     {context}

#     إذا لم تكن المعلومات كافية للإجابة على السؤال بشكل كامل، قل لا أعرف.
#     أجب بشكل دقيق.
#     /n
#     أذكر رقم المادة أو الفصل حسب الحالة.
#     أذكر اسم ورقم القانون ان كان متوفرا وان لم يكن لا تذكر شيئا.
#     """),
#     ("human", "{question}")
# ])

# prompt_template = ChatPromptTemplate.from_messages([
#     ("system", """Vous êtes un assistant juridique spécialisé qui:

# 1. CONTEXTE ET SOURCES
# - Base vos réponses uniquement sur le contexte fourni : {context}
# - Cite systématiquement les références juridiques précises (article, chapitre)
# - Mentionne le nom et numéro de la loi si disponible

# 2. STRUCTURE DE RÉPONSE 
# - Commence par la réponse directe
# - Cite ensuite la référence juridique exacte
# - Développe l'explication si nécessaire

# 3. RÈGLES CRUCIALES
# - Répond exclusivement en arabe
# - Dit "Je ne peux pas répondre de façon précise" si le contexte est insuffisant
# - Ne fait jamais d'interprétation au-delà du texte fourni
# - Reste factuel et précis
# - Ne cite que les informations présentes dans le contexte

# 4. FORMAT
# - Utilise des puces ou paragraphes courts pour la clarté
# - Met en évidence les références juridiques
# - Structure la réponse de façon hiérarchique
# """),
#     ("human", "{question}")
# ])


# prompt_template = ChatPromptTemplate.from_messages([
#     ("system", """Vous êtes un assistant juridique expert hautement qualifié. Votre rôle est d'analyser et de répondre aux questions juridiques avec précision et nuance.:

#     PROCESSUS D'ANALYSE ET DE RÉPONSE :
    
#     1. ANALYSE DES SOURCES
#        - Analysez d'abord le contexte fourni : {context}
#        - Si le contexte est insuffisant, utilisez la recherche web pour compléter
#        - Privilégiez toujours les sources officielles et la jurisprudence récente
#        - Vérifiez la date et la validité des informations trouvées
    
#     2. STRUCTURE DE RÉPONSE
#        Organisez votre réponse selon cette hiérarchie :
#        a) Réponse synthétique initiale (1-2 phrases)
#        b) Base légale et références précises
#        c) Développement détaillé
#        d) Nuances et cas particuliers
#        e) Sources utilisées
#        f) Répond exclusivement en arabe
    
#     3. PRÉCISION JURIDIQUE
#        - Respectez la terminologie juridique exacte
#        - Différenciez clairement : 
#          * Les obligations légales ("doit", "est tenu de")
#          * Les recommandations ("peut", "il est conseillé")
#          * Les interdictions ("ne peut pas", "est interdit")
#        - Citez textuellement les articles pertinents
#        - Précisez la hiérarchie des normes applicables
    
#     4. GESTION DE L'INCERTITUDE
#        Si une information est :
#        - Absente du contexte : Indiquez "Le contexte fourni ne permet pas de répondre à cet aspect"
#        - Incomplète : Précisez "Selon les informations disponibles..."
#        - Ambiguë : Exposez les différentes interprétations possibles
#        - Dépassée : Mentionnez la nécessité de vérifier les mises à jour
    
#     5. UTILISATION DE LA RECHERCHE WEB
#        Quand vous utilisez la recherche web :
#        - Indiquez clairement : "Selon la recherche web complémentaire..."
#        - chercher toujours au Maroc
#        - Citez les sources consultées
#        - Précisez la date de l'information
#        - Mentionnez si l'information nécessite une vérification
    
#     6. LIMITATIONS ET AVERTISSEMENTS
#        - Précisez si la réponse nécessite une consultation juridique professionnelle
#        - Indiquez les limites de votre analyse
#        - Signalez les évolutions législatives possibles
#        - Mentionnez les variations juridictionnelles si pertinent
    
#     FORMAT DE CITATION :
#     - Articles de loi : [Loi n°X-XX du JJ/MM/AAAA, Article XX]
#     - Jurisprudence : [Juridiction, Date, n° de pourvoi]
#     - Sources en ligne : [Nom de la source, Date de consultation]
    
#     RESTRICTIONS :
#     - Ne pas faire d'interprétation extensive sans base légale
#     - Ne pas donner de conseil juridique personnalisé
#     - Ne pas spéculer sur des situations hypothétiques
#     - Ne pas affirmer des points controversés sans mentionner les débats existants
    
#     Question à traiter : {question}
#     """),
#     ("human", "{question}")
# ])

prompt_template = ChatPromptTemplate.from_messages([
    ("system", """Vous êtes un assistant juridique expert qualifié. Analysez et répondez aux questions juridiques avec précision.
    
    PROCESSUS D'ANALYSE :
    1. Analysez le contexte fourni : {context}
    2. Utilisez la recherche web si la reponse n'existe pas dans le contexte
    3. Privilégiez les sources officielles et la jurisprudence récente

    FORMAT DE CITATION :
    - Articles de loi : [Loi n°X-XX du JJ/MM/AAAA, Article XX]
    - Jurisprudence : [Juridiction, Date, n° de pourvoi]
    - Sources en ligne : [Nom de la source, Date de consultation]

    Question à traiter : {question}
    """),
    ("human", "{question}")
])



import gradio as gr
from typing import Iterator

# Ajouter du CSS pour personnaliser l'apparence
css = """
/* Reset RTL global */
*, *::before, *::after {
    direction: rtl !important;
    text-align: right !important;
}

body {
    font-family: 'Amiri', sans-serif;  /* Utilisation de la police Arabe andalouse */
    background-color: black;  /* Fond blanc */
    color: black !important;  /* Texte noir */
    direction: rtl !important;  /* Texte en arabe aligné à droite */
}

.gradio-container {
    direction: rtl !important;  /* Alignement RTL pour toute l'interface */
}

/* Éléments de formulaire */
input[type="text"], 
.gradio-textbox input,
textarea {
    border-radius: 20px;
    padding: 10px 15px;
    border: 2px solid #000;
    font-size: 16px;
    width: 80%;
    margin: 0 auto;
    text-align: right !important;
}

/* Surcharge des styles de placeholder */
input::placeholder,
textarea::placeholder {
    text-align: right !important;
    direction: rtl !important;
}

/* Boutons */
.gradio-button {
    border-radius: 20px;
    font-size: 16px;
    background-color: #007BFF;
    color: white;
    padding: 10px 20px;
    margin: 10px auto;
    border: none;
    width: 80%;
    display: block;
}

.gradio-button:hover {
    background-color: #0056b3;
}

.gradio-chatbot .message {
    border-radius: 20px;
    padding: 10px;
    margin: 10px 0;
    background-color: #f1f1f1;
    border: 1px solid #ddd;
    width: 80%;
    text-align: right !important;
    direction: rtl !important;
}

/* Messages utilisateur alignés à gauche */
.gradio-chatbot .user-message {
    margin-right: auto;
    background-color: #e3f2fd;
    text-align: right !important;
    direction: rtl !important;
}

/* Messages assistant alignés à droite */
.gradio-chatbot .assistant-message {
    margin-right: auto;
    background-color: #f1f1f1;
    text-align: right 
}

/* Corrections RTL pour les éléments spécifiques */
.gradio-textbox textarea {
    text-align: right !important;
}

.gradio-dropdown div {
    text-align: right !important;
}
"""

def process_question(question: str) -> Iterator[str]:
    if question in question_cache:
        response, docs = question_cache[question]
        yield response + "\nSources:\n" + "\n".join([doc.page_content for doc in docs])
        return
        
    relevant_docs = retriever(question)
    # context = "\n".join([doc.page_content for doc in relevant_docs])


    context = [doc.page_content for doc in relevant_docs]
    text_pairs = [[question, text] for text in context]
    scores = rag_loader.reranker.predict(text_pairs)
    
    scored_docs = list(zip(scores, context, relevant_docs))
    # scored_docs.sort(reverse=True)
    scored_docs.sort(key=lambda x: x[0], reverse=True)
    reranked_docs = [d[2].page_content for d in scored_docs][:10]

    
    prompt = prompt_template.format_messages(
        context=reranked_docs,
        question=question
    )
    full_response = ""
    try:
        for chunk in llm.stream(prompt):
            if isinstance(chunk, str):
                current_chunk = chunk
            else:
                current_chunk = chunk.content
            full_response += current_chunk
            # sources = "\n".join(set([doc.metadata.get("source") for doc in relevant_docs]))
            # sources = [os.path.splitext(source[1])[0] for source in sources] 
            # yield full_response + "\n\n\nالمصادر المحتملة :\n" + "".join(sources)
            sources = [doc.metadata.get("source") for doc in relevant_docs]
            sources = list(set([os.path.splitext(source)[0] for source in sources]))


            sources = [d[2].metadata['source'] for d in scored_docs][:10]
            sources = list(set([os.path.splitext(source)[0] for source in sources]))

            
            yield full_response + "\n\n\nالمصادر المحتملة :\n" + "\n".join(sources)
            # yield full_response + "\n\n\nالمصادر المحتملة:\n" + "\n".join([doc.metadata.get("source") for doc in relevant_docs])
        question_cache[question] = (full_response, relevant_docs)
    except Exception as e:
        yield f"Erreur lors du traitement : {str(e)}"

# def process_question(question: str) -> Iterator[str]:
#     """
#     Process the question and return a response generator for streaming.
#     """
#     if question in question_cache:
#         yield question_cache[question][0]
#         return

#     relevant_docs = retriever(question)
#     context = "\n".join([doc.page_content for doc in relevant_docs])

#     prompt = prompt_template.format_messages(
#         context=context,
#         question=question
#     )

#     full_response = ""
#     try:
#         for chunk in llm.stream(prompt):
#             if isinstance(chunk, str):
#                 current_chunk = chunk
#             else:
#                 current_chunk = chunk.content

#             full_response += current_chunk
#             yield full_response  # Send the updated response in streaming

#         question_cache[question] = (full_response, context)
#     except Exception as e:
#         yield f"Erreur lors du traitement : {str(e)}"

# def process_question(question: str) -> Iterator[str]:
#     """
#     Process the question and return a response generator for streaming, including sources.
#     """
#     if question in question_cache:
#         yield question_cache[question][0]
#         return

#     # Récupérer les documents pertinents
#     relevant_docs = retriever(question)
#     context = "\n".join([doc.page_content for doc in relevant_docs])
#     sources = [doc.metadata.get("source", "Source inconnue") for doc in relevant_docs]
#     sources = os.path.splitext(sources[0])[0] if sources else "غير معروف"

#     # Générer le prompt
#     prompt = prompt_template.format_messages(
#         context=context,
#         question=question
#     )

#     full_response = ""
#     try:
#         # Streaming de la réponse
#         for chunk in llm.stream(prompt):
#             if isinstance(chunk, str):
#                 current_chunk = chunk
#             else:
#                 current_chunk = chunk.content

#             full_response += current_chunk
#             yield full_response  # Envoyer la réponse mise à jour en streaming

#         # Ajouter les sources à la réponse finale
#         if sources:
#             sources_str = "\nSources :\n" + "\n".join(f"- {source}" for source in sources)
#             full_response += sources_str
#             yield sources_str  # Envoyer les sources

#         # Mettre en cache la réponse complète
#         question_cache[question] = (full_response, context)
#     except Exception as e:
#         yield f"Erreur lors du traitement : {str(e)}"


# def process_question(question: str) -> tuple[str, list[str]]:
#     # Check cache first
#     if question in question_cache:
#         return question_cache[question]

#     # Get relevant documents using the retriever
#     relevant_docs = retriever(question)
    
#     # Extract the content and sources
#     context = "\n".join(doc.page_content for doc in relevant_docs)
#     sources = [doc.metadata["source"] for doc in relevant_docs]
#     sources = os.path.splitext(sources[0])[0] if sources else "غير معروف"
    
#     # Generate the prompt with the context
#     prompt = prompt_template.format(
#         context=context,
#         question=question
#     )

#     full_response = ""
    
#     try:
#         for chunk in llm.stream(prompt):
#             if isinstance(chunk, str):
#                 current_chunk = chunk
#             else:
#                 current_chunk = chunk.content

#             full_response += current_chunk
#             yield full_response, sources   # Send the updated response in streaming

#         question_cache[question,sources] = (full_response, context)
#     except Exception as e:
#         yield f"Erreur lors du traitement : {str(e)}"



def gradio_stream(question: str, chat_history: list) -> Iterator[list]:
    """
    Format the output for Gradio Chatbot component with streaming.
    """
    full_response = ""
    try:
        for partial_response in process_question(question):
            full_response = partial_response
            # Append the latest assistant response to chat history
            updated_chat = chat_history + [[question, partial_response]]
            yield updated_chat
    except Exception as e:
        # Handle errors during streaming
        updated_chat = chat_history + [[question, f"Erreur : {str(e)}"]]
        yield updated_chat

# def gradio_stream(question: str, chat_history: list) -> Iterator[list]:
#     """
#     Format the output for Gradio Chatbot component with streaming, including sources.
#     """
#     full_response = ""
#     sources_str = ""
#     try:
#         for partial_response in process_question(question):
#             if "Sources :" in partial_response:
#                 # Les sources sont ajoutées à la réponse finale
#                 sources_str = partial_response
#                 updated_chat = chat_history + [[question, full_response + "\n" + sources_str]]
#             else:
#                 # Construire progressivement la réponse
#                 full_response = partial_response
#                 updated_chat = chat_history + [[question, full_response]]
#             yield updated_chat
#     except Exception as e:
#         # Gestion des erreurs lors du streaming
#         updated_chat = chat_history + [[question, f"Erreur : {str(e)}"]]
#         yield updated_chat


# Gradio interface
with gr.Blocks(css=css) as demo:

    gr.Markdown("<h2 style='text-align: center !important;'>هذا تطبيق للاجابة على الأسئلة المتعلقة بالقوانين المغربية</h2>")

    # Organisation en 3 lignes
    with gr.Row():  # Première ligne: Question
        message = gr.Textbox(label="أدخل سؤالك", placeholder="اكتب سؤالك هنا", elem_id="question_input")
        
    with gr.Row():  # Deuxième ligne: Bouton de recherche
        send = gr.Button("بحث", elem_id="search_button")

    with gr.Row():  # Troisième ligne: Affichage de la réponse
        chatbot = gr.Chatbot(label="")

    # Fonction de mise à jour pour l'utilisateur
    def user_input(user_message, chat_history):
        return "", chat_history + [[user_message, None]]

    send.click(user_input, [message, chatbot], [message, chatbot], queue=False)
    send.click(gradio_stream, [message, chatbot], chatbot)

demo.launch(share=True)















# # def process_question(question: str):  
# #     """  
# #     Process the question and yield the answer progressively.  
# #     """  
# #     # Check cache first  
# #     if question in question_cache:  
# #         yield question_cache[question]  # Retourne directement depuis le cache si disponible  

# #     relevant_docs = retriever(question)  
# #     context = "\n".join([doc.page_content for doc in relevant_docs])  

# #     prompt = prompt_template.format_messages(  
# #         context=context,  
# #         question=question  
# #     )  

# #     response = ""  # Initialise la réponse  
# #     # Ici, nous supposons que 'llm.stream' est un générateur qui renvoie des chunks  
# #     for chunk in llm.stream(prompt):  # suppose que llm.stream renvoie des chunks de réponse  
# #         if isinstance(chunk, str):  
# #             response += chunk  # Accumulez la réponse si c'est déjà une chaîne  
# #         else:  
# #             response += chunk.content  # Sinon, prenez le contenu du chunk (si chunk est un type d'objet spécifique)  

# #         yield response, context  # Renvoie la réponse mise à jour et le contexte  

# #     # Mettez le résultat en cache à la fin  
# #     # question_cache[question] = (response, context) 

# def process_question(question: str) -> Generator[Tuple[str, str], None, None]:  
#     """  
#     Process the question and yield the answer progressively.  
#     """  
#     # Check cache first  
#     if question in question_cache:  
#         yield question_cache[question]  

#     relevant_docs = retriever(question)  
#     context = "\n".join([doc.page_content for doc in relevant_docs])  

#     prompt = prompt_template.format_messages(  
#         context=context,  
#         question=question  
#     )  

#     current_response = ""
#     for chunk in llm.stream(prompt):  
#         if isinstance(chunk, str):
#             current_response += chunk
#         else:
#             current_response += chunk.content  
#         yield current_response, context
#     # Mettez le résultat en cache à la fin  
#     question_cache[question] = (response, context) 

# # CSS personnalisé avec l'importation de Google Fonts
# custom_css = """
# /* Import Google Fonts - Noto Sans Arabic */
# @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@300;400;500;600;700&display=swap');

# /* Styles généraux */
# :root {
#     --primary-color: #4299e1;
#     --secondary-color: #666666;
#     --accent-color: #4299E1;
#     --background-color: #ffffff;
#     --border-radius: 8px;
#     --font-family-arabic: 'Noto Sans Arabic', Arial, sans-serif;
# }

# /* Style de base */
# body {
#     font-family: var(--font-family-arabic);
#     background-color: var(--background-color);
#     color: var(--primary-color);
# }

# /* Styles pour le texte RTL */
# .rtl-text {
#     text-align: right !important;
#     direction: rtl !important;
#     font-family: var(--font-family-arabic) !important;
# }

# .rtl-text textarea {
#     text-align: right !important;
#     direction: rtl !important;
#     padding: 1rem !important;
#     border-radius: var(--border-radius) !important;
#     border: 1px solid #E2E8F0 !important;
#     background-color: #ffffff !important;
#     color: var(--primary-color) !important;
#     font-size: 1.1rem !important;
#     line-height: 1.6 !important;
#     font-family: var(--font-family-arabic) !important;
# }

# /* Style du titre */
# .app-title {
#     font-family: var(--font-family-arabic) !important;
#     font-size: 2rem !important;
#     font-weight: 700 !important;
#     color: white !important; /* Texte en blanc */
#     background-color: #3e2b1f !important; /* Fond marron foncé */
#     margin-bottom: 1rem !important;
#     margin-top: 1rem !important;
#     text-align: center !important;
# }

# /* Styles des étiquettes */
# .rtl-text label {
#     font-family: var(--font-family-arabic) !important;
#     font-size: 1.2rem !important;
#     font-weight: 600 !important;
#     color: #000000 !important; /* Couleur noire pour les étiquettes */
#     margin-bottom: 0.5rem !important;
# }

# /* Centrer le bouton */
# button.primary-button {
#     font-family: var(--font-family-arabic) !important;
#     background-color: var(--accent-color) !important;
#     color: white !important;
#     padding: 0.75rem 1.5rem !important;
#     border-radius: var(--border-radius) !important;
#     font-weight: 600 !important;
#     font-size: 1.1rem !important;
#     transition: all 0.3s ease !important;
#     width: 200px !important; /* Réduit la largeur du bouton */
#     margin: 0 auto !important; /* Centrage horizontal */
#     display: block !important; /* Nécessaire pour que le margin auto fonctionne */
# }


# button.primary-button:hover {
#     background-color: #3182CE !important;
#     transform: translateY(-1px) !important;
# }

# /* Styles des boîtes de texte */
# .textbox-container {
#     background-color: #b45f06 !important;
#     padding: 1.5rem !important;
#     border-radius: var(--border-radius) !important;
#     box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
#     margin-bottom: 1rem !important;
# }

# /* Animation de chargement */
# .loading {
#     animation: pulse 2s infinite;
# }

# @keyframes pulse {
#     0% { opacity: 1; }
#     50% { opacity: 0.5; }
#     100% { opacity: 1; }
# }

# /* Style du statut */
# .status-text {
#     font-family: var(--font-family-arabic) !important;
#     text-align: center !important;
#     color: var(--secondary-color) !important;
#     font-size: 1rem !important;
#     margin-top: 1rem !important;
# }
# """

# # Interface Gradio avec streaming
# with gr.Blocks(css=custom_css) as iface:
#     with gr.Column(elem_classes="container"):
#         gr.Markdown(
#             "# نظام الأسئلة والأجوبة الذكي",
#             elem_classes="app-title rtl-text"
#         )
        
#         with gr.Column(elem_classes="textbox-container"):
#             input_text = gr.Textbox(
#                 label="السؤال",
#                 placeholder="اكتب سؤالك هنا...",
#                 lines=1,
#                 elem_classes="rtl-text"
#             )
        
#         with gr.Row():
#             with gr.Column():
#                 answer_box = gr.Textbox(
#                     label="الإجابة",
#                     lines=5,
#                     elem_classes="rtl-text textbox-container"
#                 )
        
#         submit_btn = gr.Button(
#             "إرسال السؤال",
#             elem_classes="primary-button",
#             variant="primary"
#         )

#         # def stream_response(question):
#         #     response_stream = process_question(question)
#         #     for response, _ in response_stream:
#         #         gr.update(value=response)
#         #     yield response

#         def stream_response(question):
#             for chunk_response, _ in process_question(question):
#                 yield chunk_response
#                 time.sleep(0.05)

#         submit_btn.click(
#             fn=stream_response,
#             inputs=input_text,
#             outputs=answer_box,
#             api_name="predict",
#             queue=False
#         )

# if __name__ == "__main__":
#     iface.launch(
#         share=True,
#         server_name="0.0.0.0",
#         server_port=7860,
#         max_threads=3,
#         show_error=True
#     )

# # # Interface Gradio avec la correction
# # with gr.Blocks(css=custom_css) as iface:
# #     with gr.Column(elem_classes="container"):
# #         gr.Markdown(
# #             "# نظام الأسئلة والأجوبة الذكي",
# #             elem_classes="app-title rtl-text"
# #         )
        
# #         with gr.Column(elem_classes="textbox-container"):
# #             input_text = gr.Textbox(
# #                 label="السؤال",
# #                 placeholder="اكتب سؤالك هنا...",
# #                 lines=1,
# #                 elem_classes="rtl-text"
# #             )
        
# #         with gr.Row():
# #             with gr.Column():
# #                 answer_box = gr.Textbox(
# #                     label="الإجابة",
# #                     lines=5,
# #                     elem_classes="rtl-text textbox-container"
# #                 )
# #             # with gr.Column(scale=1):
# #             #     context_box = gr.Textbox(
# #             #         label="السياق المستخدم",
# #             #         lines=4,
# #             #         elem_classes="rtl-text textbox-container"
# #             #     )
        
# #         submit_btn = gr.Button(
# #             "إرسال السؤال",
# #             elem_classes="primary-button",
# #             variant="primary"
# #         )
       

# #         def on_submit(question):
# #             for response, context in process_question(question):
# #                 yield response  # Yield À CHAQUE itération

        
# #         submit_btn.click(
# #             fn=on_submit,
# #             inputs=input_text,
# #             outputs=answer_box,
# #             api_name="predict",
# #             queue=False,
# # )


# # if __name__ == "__main__":
# #     iface.launch(
# #         share=True,
# #         server_name="0.0.0.0",
# #         server_port=7860,
# #         max_threads=3,
# #         show_error=True,
# #     )

# # def process_question(question: str):  
# #     """  
# #     Process the question and yield the answer progressively.  
# #     """  
# #     # Check cache first  
# #     if question in question_cache:  
# #         yield question_cache[question]  # Retourne directement depuis le cache si disponible  

# #     relevant_docs = retriever(question)  
# #     context = "\n".join([doc.page_content for doc in relevant_docs])  

# #     prompt = prompt_template.format_messages(  
# #         context=context,  
# #         question=question  
# #     )  

# #     response = ""  # Initialise la réponse  
# #     # Ici, nous supposons que 'llm.stream' est un générateur qui renvoie des chunks  
# #     for chunk in llm.stream(prompt):  # suppose que llm.stream renvoie des chunks de réponse  
# #         if isinstance(chunk, str):  
# #             response += chunk  # Accumulez la réponse si c'est déjà une chaîne  
# #         else:  
# #             response += chunk.content  # Sinon, prenez le contenu du chunk (si chunk est un type d'objet spécifique)  

# #         yield response, context  # Renvoie la réponse mise à jour et le contexte  

# #     # Mettez le résultat en cache à la fin  
# #     question_cache[question] = (response, context)   

# # # Custom CSS for right-aligned text in textboxes  
# # custom_css = """  
# # .rtl-text {  
# #     text-align: right !important;  
# #     direction: rtl !important;  
# # }  
# # .rtl-text textarea {  
# #     text-align: right !important;  
# #     direction: rtl !important;  
# # }  
# # """  

# # # Gradio interface with queue  
# # with gr.Blocks(css=custom_css) as iface:  
# #     with gr.Column():  
# #         input_text = gr.Textbox(  
# #             label="السؤال",  
# #             placeholder="اكتب سؤالك هنا...",  
# #             lines=2,  
# #             elem_classes="rtl-text"  
# #         )  
        
# #         with gr.Row():  
# #             answer_box = gr.Textbox(  
# #                 label="الإجابة",  
# #                 lines=4,  
# #                 elem_classes="rtl-text"  
# #             )  
# #             context_box = gr.Textbox(  
# #                 label="السياق المستخدم",  
# #                 lines=8,  
# #                 elem_classes="rtl-text"  
# #             )  
        
# #         submit_btn = gr.Button("إرسال")  
        
# #         submit_btn.click(  
# #             fn=process_question,  
# #             inputs=input_text,  
# #             outputs=[answer_box, context_box],  
# #             api_name="predict",  
# #             queue=True  # Utiliser le système de queue pour un traitement asynchrone  
# #         )  

# # if __name__ == "__main__":  
# #     iface.launch(  
# #         share=True,  
# #         server_name="0.0.0.0",  
# #         server_port=7860,  
# #         max_threads=3,  # Controls concurrency  
# #         show_error=True  
# #     )



# # def process_question(question: str):  
# #     """  
# #     Process the question and return the answer and context
# #     """  
# #     # Check cache first  
# #     if question in question_cache:  
# #         return question_cache[question], ""  # Retourne la réponse cachée et un statut vide
# #     relevant_docs = retriever(question)  
# #     context = "\n".join([doc.page_content for doc in relevant_docs])  
# #     prompt = prompt_template.format_messages(  
# #         context=context,  
# #         question=question  
# #         )  
# #     response = ""
# #     for chunk in llm.stream(prompt):
# #         if isinstance(chunk, str):  
# #             response += chunk
# #         else:  
# #             response += chunk.content
# #     # Mettez le résultat en cache à la fin  
# #     question_cache[question] = (response, context)  
# #     return response, context