File size: 16,077 Bytes
0d6dd20
 
f6bae77
0d6dd20
 
 
 
 
 
8f9cd66
 
 
 
 
4c72935
8f9cd66
0d6dd20
 
 
 
 
 
 
 
 
 
f6bae77
0d6dd20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fe3d16
0d6dd20
0fe3d16
0d6dd20
 
 
 
 
 
 
 
 
ea1df65
0d6dd20
ea1df65
0d6dd20
4af29ae
f6bae77
b31117e
f6bae77
 
 
 
0d6dd20
ea1df65
 
0d6dd20
 
 
b31117e
0d6dd20
 
8996981
 
 
27e1f37
8996981
 
 
 
 
 
 
 
 
 
27e1f37
0d6dd20
 
 
 
4af29ae
0d6dd20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8996981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fe3d16
4c72935
 
 
 
 
 
 
 
8996981
4c72935
8996981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c72935
8996981
4c72935
8996981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c72935
 
8996981
 
 
 
 
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
import transformers
from transformers import AutoConfig, AutoTokenizer, AutoModel, AutoModelForCausalLM
from vllm import LLM, SamplingParams
import torch
import gradio as gr
import json
import os
import shutil
import requests
import gradio as gr
from gradio.components import Button, ClearButton
from gradio.layouts import Column, Row
from gradio.data_classes import InterfaceTypes
import inspect
import pandas as pd

# Define the device
device = "cuda" if torch.cuda.is_available() else "cpu"
#Define variables 
temperature=0.7
max_new_tokens=300
top_p=0.92
repetition_penalty=1.7

model_name = "Pclanglais/Bellay"

llm = LLM(model_name)

styles_prompts_dict = {
    "Chansons de gestes": "Tu es Bellay, le troubadour du moyen-âge. Répond à la manière d’une belle chanson de geste.",
    "Constitutions françaises": "Tu es Bellay, le spécialiste de la vie politique française. Répond dans le style d’une constitution.",
    "Montaigne": "Tu es Michel de Montaigne, le philosophe de la Renaissance. Répond dans le style éclairé, élégant et archaïque de tes essais.",
    "La Fontaine": "Tu es Jean de la Fontaine, le fabuliste du 17e siècle. Répond en vers avec une fable bien sentie.",
    "Presse années 1970": "Tu es Bellay, le journaliste de la contre-culture des années 1970. Répond sous la forme d’un article choc.",
    "Molière": "Tu es Molière, le comédien français. Répond sous la forme de dialogues humoristiques enlevés, dans un français un peu ancien.",
    "Racine": "Tu es Jean Racine, le dramaturge français. Répond sous la forme de tirades tragiques exprimées dans un parfait français classique.",
    "Zola": "Tu es Émile Zola, le romancier français. Répond dans un style naturaliste, réaliste mais aussi un peu romantique en faisant des allusions à la vie sociale du 19e siècle.",
    "Correspondances": "Tu es Bellay, un illustre épistolier français. Répond sous la forme d’une lettre, de préférence en incluant une date au début et une signature à la fin.",
    "Poésies": "Tu es Bellay, le poète français. Répond sous la forme de tes plus beaux vers.",
    "Balzac": "Tu es Balzac, le romancier français. Répond dans le style réaliste et romantique de l’auteur de la Comédie humaine.",
    "Baudrillard": "Tu es Jean Baudrillard, le philosophe français. Répond dans un style élégant, très réfléchi et un peu obscur. N’hésite pas à employer des concepts compliqués.",
    "Bourdieu": "Tu es Pierre Bourdieu, le sociologue français. Répond avec un style informé, précis et engagé.",
    "Braudel": "Tu es Fernand Braudel, l’historien français. Répond avec un style érudit, élégant et didactique.",
    "De Gaulle": "Tu es Charles de Gaulle, l’homme politique français. Répond avec un style politique plein d’emphase.",
    "Derrida": "Tu es Jacques Derrida, le philosophe français. Répond avec un style élégant et compliqué, et n’hésite pas à employer un style ardu.",
    "Pagnol": "Tu es Marcel Pagnol, l’écrivain provençal. Répond avec un style simple mais efficace, empreint de références à la Provence.",
    "Proust": "Tu es Marcel Proust, le grand romancier français. Répond dans le style élaboré de la Recherche du temps perdu.",
    "Foucault": "Tu es Michel Foucault, le philosophe français. Répond dans le style précis et élégant de l’Archéologie du savoir.",
    "Duras": "Tu es Marguerite Duras, la romancière contemporaine. Répond dans un style poétique et haché avec des phrases courtes.",
    "Théâtre absurde": "Tu es Bellay, l’auteur de théâtre absurde. Répond par des dialogues interrogeant frontalement le sens de la vie.",
    "Philosophie": "Tu es Bellay, le philosophe français. Répond dans un style classique, érudit et informé.",
    "Bible Segond": "Tu es Bellay, le traducteur de la Bible. Répond avec des références religieuse et un style un peu archaïsant.",
    "Encyclopédie": "Tu es Diderot, l’encyclopédiste du siècle des lumières. Répond dans un style exhaustif et détaillé.",
    "Romans classiques": "Tu es Bellay, le romancier français classique. Répond sous la forme d’un roman un peu archaïque.",
    "Romans contemporains": "Tu es Bellay le romancier français contemporain. Répond sous la forme d’un roman récent avec des références contemporaines.",
    "Série noire": "Tu es Bellay l’auteur de roman policier. Répond sous la forme d’un style hardboiled à la manière de la série noire.",
    "Romans romantiques": "Tu es Bellay le romancier français de la période romantique. Répond sous la forme d’une fiction inspirée.",
    "Romans belle époque": "Tu es Bellay, le romancier français de la belle époque. Répond avec un style un peu introspectif et moderniste.",
    "San Antonio": "Tu es l’auteur des romans San-Antonio. Répond avec un style un peu cru et noir.",
    "Madame de Sévigné": "Tu es Madame de Sévigné, une illustre épistolière française. Répond sous la forme d’une lettre, de préférence en incluant une date au début et une signature à la fin."
}

# Class to encapsulate the Falcon chatbot
class MistralChatBot:
    def __init__(self, system_prompt="Le dialogue suivant est une conversation"):
        self.system_prompt = system_prompt

    def predict(self, user_message, style, temperature):

        system_prompt = styles_prompts_dict[style]

        sampling_params = SamplingParams(temperature=temperature, top_p=.95, max_tokens=500, presence_penalty = 2)
        detailed_prompt = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n<|im_start|>user"""
        detailed_prompt = detailed_prompt + "\n" + user_message + "<|im_end|>\n<|im_start|>assistant\n"
        prompts = [detailed_prompt]
        outputs = llm.generate(prompts, sampling_params, use_tqdm = False)
        generated_text = outputs[0].outputs[0].text
        return generated_text

    def predict_simple(self, user_message, style):
        system_prompt = styles_prompts_dict[style]
        conversation = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n<|im_start|>user\n" + user_message + "<|im_end|>\n<|im_start|>assistant\n"
        return conversation

# Create the Mistral chatbot instance
mistral_bot = MistralChatBot()

title = """
<h1 style='text-align: center; font-weight: bold;'> Bellay, le premier LLM de la littérature française</h1>
"""
description = """
<p style='text-align: justify;'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus elementum leo a
 tortor fringilla elementum. Nullam eget sodales lacus. Nullam non aliquet elit. 
 Etiam enim arcu, vehicula nec enim id, laoreet sodales justo. Nulla feugiat non 
 leo in interdum. Quisque id leo ligula. Etiam id quam urna. Morbi tincidunt eros 
 in eros vulputate, a congue enim feugiat. Ut laoreet ex in dui ultrices elementum. 
 Vivamus eget venenatis dui. Vestibulum dictum ipsum eu mauris convallis, sit amet 
 sollicitudin orci lacinia. Nunc pellentesque hendrerit felis eleifend interdum. 
 Ut ac volutpat nisi. 
</p>
"""
examples = [
    [
        "Comment faire une bonne madeleine ? Donne-moi une recette détaillée avec les ingrédients.",  # user_message
        "Proust",
        0.7  # temperature
    ]
]

list_dropdown = [
    'Proust',
    'Encyclopédie',
    'Balzac',
    'Montaigne',
    'Foucault',
    'Chansons de gestes',
    'Constitutions françaises',
    'La Fontaine',
    'Madame de Sévigné',
    'Molière',
    'Racine',
    'Romans classiques',
    'Romans romantiques',
    'Théâtre absurde',
    'Romans belle époque',
    'Bible Segond',
    'Zola',
    'Pagnol',
    'Philosophie',
    'Poésies',
    'De Gaulle',
    'Série noire',
    'San Antonio',
    'Duras',
    'Presse années 1970',
    'Braudel',
    'Bourdieu',
    'Derrida',
    'Baudrillard',
    'Romans contemporains'
]

# Dictionary of explanations for each artist or style
explanations = {
    'Proust': "Marcel Proust, known for his introspective and lengthy novel 'In Search of Lost Time', which explores themes of memory and time.",
    'Encyclopédie': "A groundbreaking Enlightenment-era work, edited by Diderot and d'Alembert, aiming to compile and disseminate human knowledge.",
    'Balzac': "Honoré de Balzac, a French novelist and playwright, famous for his detailed depiction of society in 'La Comédie Humaine'.",
    'Montaigne': "Michel de Montaigne, a Renaissance philosopher known for popularizing the essay as a literary genre, exploring human nature.",
    'Foucault': "Michel Foucault, a 20th-century philosopher and social theorist, known for his analysis of power and societal institutions.",
    'Chansons de gestes': "Medieval epic poems celebrating heroic deeds, exemplified by 'The Song of Roland', key to French literary history.",
    'Constitutions françaises': "Refers to the various constitutions that France has had throughout its history, each shaping its political landscape.",
    'La Fontaine': "Jean de La Fontaine, famed for his Fables, which are moralistic stories often featuring animals and conveying ethical lessons.",
    'Madame de Sévigné': "Marie de Rabutin-Chantal, Marquise de Sévigné, known for her detailed and insightful letters depicting French aristocratic life.",
    'Molière': "Jean-Baptiste Poquelin, known as Molière, a playwright and actor, acclaimed for his comedies like 'Tartuffe' and 'The Misanthrope'.",
    'Racine': "Jean Racine, a playwright of the French classical era, renowned for his tragedies like 'Phèdre' and 'Andromaque'.",
    'Romans classiques': "Refers to classic French novels, characterized by their adherence to traditional literary standards and themes.",
    'Romans romantiques': "Romantic-era French novels, emphasizing emotion, nature, and individualism, contrasting with the rationality of Enlightenment.",
    'Théâtre absurde': "Absurdist theatre, a post-World War II movement exemplified by playwrights like Samuel Beckett, emphasizing the absurdity of human existence.",
    'Romans belle époque': "Novels from the Belle Époque, a period of French history marked by optimism, cultural innovations, and artistic flourishing.",
    'Bible Segond': "A French translation of the Bible by Louis Segond, widely used in French-speaking Protestant communities.",
    'Zola': "Émile Zola, a key figure in the literary school of naturalism, known for his series of novels 'Les Rougon-Macquart'.",
    'Pagnol': "Marcel Pagnol, a novelist and filmmaker, celebrated for his works depicting life in Provence, including 'Jean de Florette'.",
    'Philosophie': "Refers to French philosophy, a rich tradition ranging from existentialism to post-structuralism, featuring thinkers like Sartre and Derrida.",
    'Poésies': "French poetry, a diverse field ranging from the troubadours of the Middle Ages to the symbolists and modern poets.",
    'De Gaulle': "Charles de Gaulle, a French general and statesman, pivotal in establishing the Fifth Republic and its constitution.",
    'Série noire': "A French publishing imprint known for its translations of American hardboiled detective and noir crime fiction.",
    'San Antonio': "A series of French detective novels by Frédéric Dard, featuring the character San Antonio, known for their humor and inventiveness.",
    'Duras': "Marguerite Duras, a French writer and film director, known for her minimalist style and works like 'The Lover'.",
    'Presse années 1970': "Refers to the French press in the 1970s, a period marked by political activism and the rise of new journalistic styles.",
    'Braudel': "Fernand Braudel, a French historian who revolutionized the study of history by focusing on long-term social and geographic structures.",
    'Bourdieu': "Pierre Bourdieu, a French sociologist, renowned for his theory of social practices and concepts like cultural capital.",
    'Derrida': "Jacques Derrida, a philosopher best known for developing deconstruction, a critical approach that questions the relationship between text and meaning.",
    'Baudrillard': "Jean Baudrillard, a cultural theorist known for his analysis of consumerism, simulation, and hyperreality."
}

# Example data
example_data = pd.DataFrame({
    "Question ou votre instruction": ["Comment faire une bonne madeleine ? Donne-moi une recette détaillée avec les ingrédients."],
    "Style": ["Proust"],
    "Température": [0.7]
})

# Function to handle table row click
def fill_example(data):
    question, style, temp = data.iloc[0]
    user_input.update(question)
    dropdown.change(style)
    temperature_slider.change(temp)
    return "Il y avait eu dans le salon de l'hôtel, que j'avais quitté pour venir à la table où il se trouvait M. de Charlus et une foule d'autres personnes, une très grande madeleine, un peu grasse, mais dont la forme était fort belle, et qui avait été réservée pour moi ; elle avait été posée sur une assiette en porcelaine blanche avec des fleurs bleues dessinées dessus par un graveur français du XVIIIe siècle : cela faisait l'effet d'une madeleine faite de pâte rosée au beurre et décorée de motifs de couture en passementerie rose, sous lesquels on voyait cette couleur donner son éclat aux feuilles d'acanthe. Je pensai donc que je devrais demander à la femme de chambre si elle n'y prenait point goût, si elle ne voudrait pas bien manger ma madeleine ; je lui fis signe, après avoir pris mon cafard, et aussitôt elle s'approcha du plat, fit une pièce, en me porta la tranche avec ses doigts, comme si elle en avait fait autant de fois. Elle y mangea avec plaisir et sans gêne, à peine respectant mes yeux."

# Function to return the explanation based on the selected artist or style
def update_explanation(choice):
    return explanations.get(choice, "No explanation available.")

# Define the Gradio interface using Blocks
with gr.Blocks(theme = 'carlosrosash/bellay_test') as demo:
    gr.Markdown(title)
    gr.Markdown(description)
    with gr.Row():
        dropdown = gr.Dropdown(list_dropdown, label="Choose an Artist or Style")
        explanation_box = gr.Textbox(label="Explanation", type="text", lines=5, interactive=False)
    dropdown.change(update_explanation, inputs=dropdown, outputs=explanation_box)

    # Define the columns for input and output
    with gr.Row():
        with gr.Column():
            user_input = gr.Textbox(label="Question or your instruction", type="text", lines=5, placeholder="Start typing here")
            temperature_slider = gr.Slider(label="Temperature", value=0.7, minimum=0.05, maximum=1.0, step=0.05, interactive=True)
            with gr.Row():
                with gr.Column():
                    clear_button = gr.Button("Effacer")
                with gr.Column():                    
                    submit_button = gr.Button("Let's goooo 🪶")
        with gr.Column():
            output_text = gr.Textbox(label="Response", type="text", lines=10)

    # Function to handle the button click for submit
    def on_submit(user_message, style, temperature):
        return mistral_bot.predict(user_message, style, temperature)

    # Function to handle the button click for clear
    def on_clear():
        user_input.clear()  # Clear the user input
        temperature_slider.change(0.7)  # Reset the slider to default
        output_text.clear()  # Clear the output text

        # Reset the dropdown to a default value and update the explanation
        default_style = list_dropdown[0]  # Assuming the first value is the default
        dropdown.change(default_style)  # Change the dropdown to the default value
        explanation_box.update(explanations[default_style])  # Update the explanation box

    # Examples section
    gr.Markdown("<h2>Examples</h2>")
    examples_df = gr.Dataframe(example_data, interactive=True)
    examples_df.click(fill_example, inputs=examples_df, outputs=output_text)

    submit_button.click(on_submit, inputs=[user_input, dropdown, temperature_slider], outputs=output_text)
    clear_button.click(on_clear)

demo.launch()