louisbrulenaudet commited on
Commit
0c6a021
·
verified ·
1 Parent(s): d448f0a

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +357 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) Louis Brulé Naudet. All Rights Reserved.
3
+ # This software may be used and distributed according to the terms of the License Agreement.
4
+ #
5
+ # Unless required by applicable law or agreed to in writing, software
6
+ # distributed under the License is distributed on an "AS IS" BASIS,
7
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8
+ # See the License for the specific language governing permissions and
9
+ # limitations under the License.
10
+
11
+ import logging
12
+
13
+ from threading import Thread
14
+ from typing import Iterator
15
+
16
+ from typing import (
17
+ Dict,
18
+ List,
19
+ )
20
+
21
+ import chromadb
22
+ import gradio as gr
23
+ import polars as pl
24
+ import spaces
25
+ import torch
26
+
27
+ from chromadb.config import Settings
28
+ from chromadb.utils import embedding_functions
29
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
30
+
31
+
32
+ def setup_logger(name="my_logger", log_file=None, level=logging.INFO):
33
+ """
34
+ Set up and return a logger with optional console and file logging.
35
+
36
+ This function configures a logger that outputs messages to the console and
37
+ optionally writes them to a specified log file. The logger supports different severity levels (e.g., DEBUG, INFO, WARNING, ERROR, CRITICAL) and can be customized with a unique name.
38
+
39
+ Parameters
40
+ ----------
41
+ name : str, optional
42
+ The name of the logger. This allows you to identify different loggers
43
+ if multiple instances are used. Default is "my_logger".
44
+
45
+ log_file : str, optional
46
+ The path to a file where logs will be saved. If None, logs will only
47
+ be displayed in the console. Default is None.
48
+
49
+ level : int, optional
50
+ The logging level that controls the minimum severity of messages to log. Typical values are logging.DEBUG, logging.INFO, logging.WARNING,
51
+ logging.ERROR, and logging.CRITICAL. Default is logging.INFO.
52
+
53
+ Returns
54
+ -------
55
+ logging.Logger
56
+ A configured logger instance with the specified settings.
57
+
58
+ Examples
59
+ --------
60
+ >>> logger = setup_logger("example_logger", log_file="example.log", level=logging.DEBUG)
61
+ >>> logger.info("This is an info message.")
62
+ >>> logger.debug("This is a debug message.")
63
+ >>> logger.warning("This is a warning message.")
64
+ >>> logger.error("This is an error message.")
65
+ >>> logger.critical("This is a critical message.")
66
+
67
+ Notes
68
+ -----
69
+ The function adds a `StreamHandler` to output logs to the console and a
70
+ `FileHandler` if a log file is specified. Each handler uses the same logging format which includes the timestamp, logger name, severity level, and message.
71
+
72
+ The function creates a new logger with the specified name only if one with
73
+ that name does not already exist. Repeated calls with the same `name` will
74
+ retrieve the existing logger, which may lead to duplicate handlers if not
75
+ handled carefully.
76
+
77
+ See Also
78
+ --------
79
+ logging.Logger : Python's built-in logger class, providing full details on
80
+ all supported logging operations.
81
+ """
82
+ # Create a custom logger
83
+ logger = logging.getLogger(name)
84
+ logger.setLevel(level)
85
+
86
+ # Create console handler and set level
87
+ console_handler = logging.StreamHandler()
88
+ console_handler.setLevel(level)
89
+
90
+ # Create formatter and add it to handlers
91
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
92
+ console_handler.setFormatter(formatter)
93
+
94
+ # Add handlers to the logger
95
+ logger.addHandler(console_handler)
96
+
97
+ # Optionally, add a file handler
98
+ if log_file:
99
+ file_handler = logging.FileHandler(log_file)
100
+ file_handler.setLevel(level)
101
+ file_handler.setFormatter(formatter)
102
+ logger.addHandler(file_handler)
103
+
104
+ return logger
105
+
106
+ logger = setup_logger("application", level=logging.DEBUG)
107
+
108
+ MAX_NEW_TOKENS: int = 2048
109
+
110
+ DESCRIPTION: str = """[<img src="https://huggingface.co/louisbrulenaudet/lemone-embed-pro/resolve/main/assets/thumbnail.webp" alt="Built with Lemone-embed Pro" width="600"/>](https://huggingface.co/louisbrulenaudet/lemone-embed-pro)
111
+
112
+ This space showcases the [Lemone-embed-pro](https://huggingface.co/louisbrulenaudet/Lemone-embed-pro)
113
+ model by [Louis Brulé Naudet](https://huggingface.co/louisbrulenaudet).
114
+
115
+ The model is tailored to meet the specific demands of information retrieval across large-scale tax-related corpora, supporting the implementation of production-ready Retrieval-Augmented Generation (RAG) applications. Its primary purpose is to enhance the efficiency and accuracy of legal processes in the taxation domain, with an emphasis on delivering consistent performance in real-world settings, while also contributing to advancements in legal natural language processing research.
116
+ """
117
+
118
+ SYSTEME_PROMPT: str = """Vous êtes un assistant juridique spécialisé en fiscalité, conçu pour fournir des réponses précises et contextualisées en vous appuyant sur des documents de référence considérés comme d'autorité. Votre rôle consiste à extraire et formuler des réponses détaillées et nuancées, qui s'appuient sur le contenu pertinent des documents fournis, en adoptant un discours académique et professionnel.
119
+
120
+ Objectifs principaux :
121
+ 1. **Analyse sémantique rigoureuse** : Évaluez le contenu sémantique des documents afin d'assurer une compréhension exhaustive de chaque passage pertinent en lien avec la question posée.
122
+ 2. **Élaboration de phrases complexes** : Formulez des réponses en utilisant des structures de phrases élaborées et variées qui permettent d'étendre et d'enrichir l'expression des idées sans jamais simplifier excessivement les thématiques abordées.
123
+ 3. **Qualité linguistique** : Chaque réponse doit être rédigée dans un français exempt de fautes d'orthographe, de grammaire, de syntaxe, et de ponctuation. Utilisez un style d'écriture qui témoigne de rigueur professionnelle.
124
+ 4. **Neutralité et objectivité** : Maintenez une approche neutre ou nuancée dans les réponses, en mettant en avant une analyse impartiale de chaque thématique juridique ou fiscale abordée.
125
+ 5. **Contextualisation juridique** : Assurez-vous que chaque réponse contextualise explicitement le sujet juridique ou fiscal en question afin de garantir une compréhension autonome de la problématique posée.
126
+ 6. **Respect du style littéraire** : Utilisez un style littéraire et professionnel dans chaque réponse, et intégrez des exemples pertinents lorsque ceux-ci renforcent la clarté de l'analyse. Évitez tout usage de formulations vagues ou d'interprétations subjectives.
127
+ 7. **Directivité et impersonnalité** : Formulez les réponses de manière directe, en évitant l’utilisation de pronoms personnels ou d'expressions référentielles implicites qui pourraient diminuer la clarté ou l’autorité du discours.
128
+ 8. **Usage exhaustif des sources** : Exploitez intégralement le contenu des documents fournis, de sorte qu'aucun détail pertinent n'est négligé et que chaque réponse conserve un caractère hautement spécialisé. Lorsque des flux ou des exemples numériques apparaissent, intégrez-les sans altérer le contexte.
129
+ 9. **Absence de citation implicite** : Ne faites jamais référence aux documents comme des "sources" ou "textes sources". Intégrez directement les informations en les reformulant dans un discours naturel et autonome, en respectant la logique de la thématique abordée."""
130
+
131
+ if not torch.cuda.is_available():
132
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
133
+
134
+ else:
135
+ logger.info("Loading model from Hugging Face Hub...")
136
+
137
+ model = AutoModelForCausalLM.from_pretrained(
138
+ "CohereForAI/c4ai-command-r-v01-4bit",
139
+ torch_dtype=torch.float16,
140
+ device_map="auto"
141
+ )
142
+
143
+ device = model.device
144
+
145
+ tokenizer = AutoTokenizer.from_pretrained(
146
+ "CohereForAI/c4ai-command-r-v01-4bit"
147
+ )
148
+
149
+ tokenizer.use_default_system_prompt = False
150
+ client = chromadb.Client(
151
+ settings=Settings(anonymized_telemetry=False)
152
+ )
153
+
154
+ sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(
155
+ model_name="louisbrulenaudet/lemone-embed-pro",
156
+ device="cuda" if torch.cuda.is_available() else "cpu",
157
+ trust_remote_code=True
158
+ )
159
+
160
+ logger.info("Creating collection using the embeddings dataset from Hugging Face Hub...")
161
+ collection = client.get_or_create_collection(
162
+ name="tax",
163
+ embedding_function=sentence_transformer_ef
164
+ )
165
+
166
+ dataframe: pl.DataFrame = pl.scan_parquet(
167
+ "hf://datasets/louisbrulenaudet/lemone-docs-embeded-bis/data/train-00000-of-00001.parquet"
168
+ ).filter(
169
+ pl.col(
170
+ "text"
171
+ ).is_not_null()
172
+ ).collect()
173
+
174
+ collection.add(
175
+ embeddings=dataframe["lemone_pro_embeddings"].to_list(),
176
+ documents=dataframe["text"].to_list(),
177
+ metadatas=dataframe.drop(
178
+ [
179
+ "lemone_pro_embeddings",
180
+ "text"
181
+ ]
182
+ ).to_dicts(),
183
+ ids=[
184
+ str(i) for i in range(0, dataframe.shape[0])
185
+ ]
186
+ )
187
+
188
+
189
+ def trim_input_ids(
190
+ input_ids,
191
+ max_length
192
+ ):
193
+ """
194
+ Trim the input token IDs if they exceed the maximum length.
195
+
196
+ Parameters
197
+ ----------
198
+ input_ids : torch.Tensor
199
+ The input token IDs.
200
+
201
+ max_length : int
202
+ The maximum length allowed.
203
+
204
+ Returns
205
+ -------
206
+ torch.Tensor
207
+ The trimmed input token IDs.
208
+ """
209
+ if input_ids.shape[1] > max_length:
210
+ input_ids = input_ids[:, -max_length:]
211
+ print(f"Trimmed input from conversation as it was longer than {max_length} tokens.")
212
+
213
+ return input_ids
214
+
215
+
216
+ @spaces.GPU
217
+ def inference(
218
+ message: str,
219
+ chat_history: list,
220
+ ) -> Iterator[str]:
221
+ """
222
+ Generate a response to a given message within a conversation context.
223
+
224
+ This function utilizes a pre-trained language model to generate a response to a given message, considering the conversation context provided in the chat history.
225
+
226
+ Parameters
227
+ ----------
228
+ message : str
229
+ The user's message for which a response is generated.
230
+
231
+ chat_history : list
232
+ A list containing tuples representing the conversation history. Each tuple should consist of two elements: the user's message and the assistant's response.
233
+
234
+ Yields
235
+ ------
236
+ str
237
+ A generated response to the given message.
238
+
239
+ Notes
240
+ -----
241
+ - This function requires a GPU for efficient processing and may not work properly on CPU.
242
+ - The conversation history should be provided in the form of a list of tuples, where each tuple represents a user message followed by the assistant's response.
243
+ """
244
+ global collection
245
+ global device
246
+ global tokenizer
247
+ global model
248
+ global logger
249
+ global MAX_NEW_TOKENS
250
+ global SYSTEME_PROMPT
251
+
252
+ conversation: List[Dict[str, str]] = []
253
+
254
+ if SYSTEME_PROMPT:
255
+ conversation.append(
256
+ {
257
+ "role": "system", "content": SYSTEME_PROMPT
258
+ }
259
+ )
260
+
261
+ for user, assistant in chat_history:
262
+ conversation.extend(
263
+ [
264
+ {
265
+ "role": "user",
266
+ "content": user
267
+ },
268
+ {
269
+ "role": "assistant",
270
+ "content": assistant
271
+ }
272
+ ]
273
+ )
274
+
275
+ conversation.append(
276
+ {
277
+ "role": "user",
278
+ "content": message
279
+ }
280
+ )
281
+
282
+ documents_with_metadata: Dict[str, List[str]] = collection.query(
283
+ query_texts=[message],
284
+ n_results=5,
285
+ )
286
+
287
+ documents: List[Dict[str, str]] = []
288
+
289
+ for meta, document in zip(documents_with_metadata["metadatas"][0], documents_with_metadata["documents"][0]):
290
+ documents.append({
291
+ "title": f"""{meta["title_main"]}, {meta["id_sub"]}""",
292
+ "text": f"""Lien : {meta["url_sourcepage"]}\n\n{document}"""
293
+ })
294
+
295
+ input_ids = tokenizer.apply_chat_template(
296
+ conversation=conversation,
297
+ documents=documents,
298
+ chat_template="rag",
299
+ tokenize=True,
300
+ add_generation_prompt=True,
301
+ return_tensors="pt"
302
+ ).to(device)
303
+
304
+ # input_ids = trim_input_ids(
305
+ # input_ids=input_ids,
306
+ # max_length=128000
307
+ # )
308
+
309
+ streamer = TextIteratorStreamer(
310
+ tokenizer,
311
+ timeout=10.0,
312
+ skip_prompt=True,
313
+ skip_special_tokens=True
314
+ )
315
+
316
+ generate_kwargs = dict(
317
+ {"input_ids": input_ids},
318
+ streamer=streamer,
319
+ max_new_tokens=MAX_NEW_TOKENS,
320
+ do_sample=True,
321
+ num_beams=1,
322
+ temperature=0.5,
323
+ eos_token_id=tokenizer.eos_token_id
324
+ )
325
+
326
+ t = Thread(
327
+ target=model.generate,
328
+ kwargs=generate_kwargs
329
+ )
330
+
331
+ t.start()
332
+
333
+ outputs: str = []
334
+ for text in streamer:
335
+ outputs.append(text)
336
+
337
+ yield "".join(outputs).replace("<|EOT|>","")
338
+
339
+
340
+ chatbot = gr.Chatbot(
341
+ type="messages",
342
+ show_copy_button=True
343
+ )
344
+
345
+ with gr.Blocks(theme=gr.themes.Origin()) as demo:
346
+ gr.Markdown(
347
+ value=DESCRIPTION
348
+ )
349
+ gr.DuplicateButton()
350
+ chat_interface = gr.ChatInterface(
351
+ fn=inference,
352
+ type="messages",
353
+ chatbot=chatbot,
354
+ )
355
+
356
+ if __name__ == "__main__":
357
+ demo.queue().launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ chromadb==0.5.15
2
+ gradio
3
+ polars==1.12.0
4
+ spaces==0.30.4
5
+ torch
6
+ transformers==4.46.0