carlosrosash commited on
Commit
0fe3d16
1 Parent(s): 9af3c84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -39
app.py CHANGED
@@ -13,9 +13,9 @@ from gradio.layouts import Column, Row
13
  from gradio.data_classes import InterfaceTypes
14
  import inspect
15
 
 
 
16
 
17
-
18
- # CustomInterface class definition
19
  class CustomInterface(gr.Interface):
20
  def render_input_column(self):
21
  submit_btn, clear_btn, stop_btn, flag_btns, duplicate_btn = None, None, None, None, None
@@ -45,7 +45,7 @@ class CustomInterface(gr.Interface):
45
  # Return the appropriate tuple
46
  return submit_btn, clear_btn, stop_btn, flag_btns, input_component_column, duplicate_btn, None
47
 
48
-
49
  # Define the device
50
  device = "cuda" if torch.cuda.is_available() else "cpu"
51
  #Define variables
@@ -58,7 +58,6 @@ model_name = "Pclanglais/Bellay"
58
 
59
  llm = LLM(model_name)
60
 
61
-
62
  styles_prompts_dict = {
63
  "Chansons de gestes": "Tu es Bellay, le troubadour du moyen-âge. Répond à la manière d’une belle chanson de geste.",
64
  "Constitutions françaises": "Tu es Bellay, le spécialiste de la vie politique française. Répond dans le style d’une constitution.",
@@ -86,9 +85,9 @@ styles_prompts_dict = {
86
  "Encyclopédie": "Tu es Diderot, l’encyclopédiste du siècle des lumières. Répond dans un style exhaustif et détaillé.",
87
  "Romans classiques": "Tu es Bellay, le romancier français classique. Répond sous la forme d’un roman un peu archaïque.",
88
  "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.",
89
- "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.",
90
  "Romans romantiques": "Tu es Bellay le romancier français de la période romantique. Répond sous la forme d’une fiction inspirée.",
91
- "Romans belle époque": "Tu es Bellay, le romancier français de la belle époque. Répond avec un style un peu introspectif et moderniste.",
92
  "San Antonio": "Tu es l’auteur des romans San-Antonio. Répond avec un style un peu cru et noir.",
93
  "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."
94
  }
@@ -98,9 +97,9 @@ class MistralChatBot:
98
  def __init__(self, system_prompt="Le dialogue suivant est une conversation"):
99
  self.system_prompt = system_prompt
100
 
101
- def predict(self, user_message, style, temperature):
102
 
103
- system_prompt = styles_prompts_dict[style]
104
 
105
  sampling_params = SamplingParams(temperature=temperature, top_p=.95, max_tokens=500, presence_penalty = 2)
106
  detailed_prompt = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n<|im_start|>user"""
@@ -110,32 +109,31 @@ class MistralChatBot:
110
  generated_text = outputs[0].outputs[0].text
111
  return generated_text
112
 
113
- def predict_simple(self, user_message, style):
114
- system_prompt = styles_prompts_dict[style]
115
  conversation = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n<|im_start|>user\n" + user_message + "<|im_end|>\n<|im_start|>assistant\n"
116
  return conversation
117
 
118
  # Create the Mistral chatbot instance
119
  mistral_bot = MistralChatBot()
120
 
 
 
121
  # Define the Gradio interface
122
- title = "Bellay, le premier LLM de la littérature française"
 
 
123
  description = """
124
- 🌟 Bienvenue dans l'univers de Bellay! 🌟
125
-
126
- 📚 Choisissez votre style ou personnage 🎭
127
-
128
- Avec Bellay, embarquez pour un voyage littéraire unique! Sélectionnez l'un des styles fascinants ou transformez-vous en une des personnages emblématiques de Bellay. Êtes-vous prêt à explorer? Voici quelques options pour commencer:
129
-
130
- Proust - Plongez dans l'élégance et la complexité de Proust. 🖋️
131
- La Fontaine - Laissez-vous emporter par le charme des fables de La Fontaine. 🐢🦊
132
- Zola - Découvrez le réalisme poignant et captivant de Zola. 🏭🌆
133
- Montaigne - Engagez-vous dans les réflexions profondes de Montaigne. 🤔💭
134
- ... et bien d'autres encore!
135
-
136
- 🤖 Interagissez avec Bellay 🎙️
137
-
138
- Posez vos questions, lancez des discussions ou demandez des conseils à Bellay. Il est là pour répondre avec l'esprit et le style du personnage ou de l'époque que vous avez choisi. N'hésitez pas, lancez-vous dans cette aventure littéraire passionnante!
139
  """
140
  examples = [
141
  [
@@ -178,9 +176,46 @@ list_dropdown = [
178
  'Romans contemporains'
179
  ]
180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
  additional_inputs=[
183
- gr.Dropdown(list_dropdown, value="Proust", label="Style", info="Le style prédominant de Bellay"),
184
  gr.Slider(
185
  label="Température",
186
  value=0.7, # Default value
@@ -192,15 +227,26 @@ additional_inputs=[
192
  ),
193
  ]
194
 
195
- iface = CustomInterface(
196
- fn=mistral_bot.predict,
197
- title=title,
198
- description=description,
199
- examples=examples,
200
- inputs=[gr.Textbox(label="Question ou votre instruction", type="text", lines=5, placeholder = "Commencer à écrire ici")] + additional_inputs,
201
- outputs=[gr.Textbox(label="Réponse", type="text", lines=5)],
202
- theme="carlosrosash/bellay_test"
203
- )
204
-
205
- # Launch the Gradio interface for the Mistral model
206
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
13
  from gradio.data_classes import InterfaceTypes
14
  import inspect
15
 
16
+ ########################################################################################################################################################################
17
+ #### Create the custom Interface for the buttoms
18
 
 
 
19
  class CustomInterface(gr.Interface):
20
  def render_input_column(self):
21
  submit_btn, clear_btn, stop_btn, flag_btns, duplicate_btn = None, None, None, None, None
 
45
  # Return the appropriate tuple
46
  return submit_btn, clear_btn, stop_btn, flag_btns, input_component_column, duplicate_btn, None
47
 
48
+ ########################################################################################################################################################################
49
  # Define the device
50
  device = "cuda" if torch.cuda.is_available() else "cpu"
51
  #Define variables
 
58
 
59
  llm = LLM(model_name)
60
 
 
61
  styles_prompts_dict = {
62
  "Chansons de gestes": "Tu es Bellay, le troubadour du moyen-âge. Répond à la manière d’une belle chanson de geste.",
63
  "Constitutions françaises": "Tu es Bellay, le spécialiste de la vie politique française. Répond dans le style d’une constitution.",
 
85
  "Encyclopédie": "Tu es Diderot, l’encyclopédiste du siècle des lumières. Répond dans un style exhaustif et détaillé.",
86
  "Romans classiques": "Tu es Bellay, le romancier français classique. Répond sous la forme d’un roman un peu archaïque.",
87
  "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.",
88
+ "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.",
89
  "Romans romantiques": "Tu es Bellay le romancier français de la période romantique. Répond sous la forme d’une fiction inspirée.",
90
+ "Romans belle époque": "Tu es Bellay, le romancier français de la belle époque. Répond avec un style un peu introspectif et moderniste.",
91
  "San Antonio": "Tu es l’auteur des romans San-Antonio. Répond avec un style un peu cru et noir.",
92
  "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."
93
  }
 
97
  def __init__(self, system_prompt="Le dialogue suivant est une conversation"):
98
  self.system_prompt = system_prompt
99
 
100
+ def predict(self, user_message, selected_style, temperature):
101
 
102
+ system_prompt = styles_prompts_dict[selected_style]
103
 
104
  sampling_params = SamplingParams(temperature=temperature, top_p=.95, max_tokens=500, presence_penalty = 2)
105
  detailed_prompt = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n<|im_start|>user"""
 
109
  generated_text = outputs[0].outputs[0].text
110
  return generated_text
111
 
112
+ def predict_simple(self, user_message, selected_style):
113
+ system_prompt = styles_prompts_dict[selected_style]
114
  conversation = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n<|im_start|>user\n" + user_message + "<|im_end|>\n<|im_start|>assistant\n"
115
  return conversation
116
 
117
  # Create the Mistral chatbot instance
118
  mistral_bot = MistralChatBot()
119
 
120
+ ########################################################################################################################################################################
121
+
122
  # Define the Gradio interface
123
+ title = """
124
+ <h1 style='text-align: center; font-weight: bold;'> Bellay, le premier LLM de la littérature française</h1>
125
+ """
126
  description = """
127
+ <p style='text-align: justify;'>
128
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus elementum leo a
129
+ tortor fringilla elementum. Nullam eget sodales lacus. Nullam non aliquet elit.
130
+ Etiam enim arcu, vehicula nec enim id, laoreet sodales justo. Nulla feugiat non
131
+ leo in interdum. Quisque id leo ligula. Etiam id quam urna. Morbi tincidunt eros
132
+ in eros vulputate, a congue enim feugiat. Ut laoreet ex in dui ultrices elementum.
133
+ Vivamus eget venenatis dui. Vestibulum dictum ipsum eu mauris convallis, sit amet
134
+ sollicitudin orci lacinia. Nunc pellentesque hendrerit felis eleifend interdum.
135
+ Ut ac volutpat nisi.
136
+ </p>
 
 
 
 
 
137
  """
138
  examples = [
139
  [
 
176
  'Romans contemporains'
177
  ]
178
 
179
+ # Dictionary of explanations for each artist or style
180
+ explanations = {
181
+ 'Proust': "Marcel Proust, known for his introspective and lengthy novel 'In Search of Lost Time', which explores themes of memory and time.",
182
+ 'Encyclopédie': "A groundbreaking Enlightenment-era work, edited by Diderot and d'Alembert, aiming to compile and disseminate human knowledge.",
183
+ 'Balzac': "Honoré de Balzac, a French novelist and playwright, famous for his detailed depiction of society in 'La Comédie Humaine'.",
184
+ 'Montaigne': "Michel de Montaigne, a Renaissance philosopher known for popularizing the essay as a literary genre, exploring human nature.",
185
+ 'Foucault': "Michel Foucault, a 20th-century philosopher and social theorist, known for his analysis of power and societal institutions.",
186
+ 'Chansons de gestes': "Medieval epic poems celebrating heroic deeds, exemplified by 'The Song of Roland', key to French literary history.",
187
+ 'Constitutions françaises': "Refers to the various constitutions that France has had throughout its history, each shaping its political landscape.",
188
+ 'La Fontaine': "Jean de La Fontaine, famed for his Fables, which are moralistic stories often featuring animals and conveying ethical lessons.",
189
+ 'Madame de Sévigné': "Marie de Rabutin-Chantal, Marquise de Sévigné, known for her detailed and insightful letters depicting French aristocratic life.",
190
+ 'Molière': "Jean-Baptiste Poquelin, known as Molière, a playwright and actor, acclaimed for his comedies like 'Tartuffe' and 'The Misanthrope'.",
191
+ 'Racine': "Jean Racine, a playwright of the French classical era, renowned for his tragedies like 'Phèdre' and 'Andromaque'.",
192
+ 'Romans classiques': "Refers to classic French novels, characterized by their adherence to traditional literary standards and themes.",
193
+ 'Romans romantiques': "Romantic-era French novels, emphasizing emotion, nature, and individualism, contrasting with the rationality of Enlightenment.",
194
+ 'Théâtre absurde': "Absurdist theatre, a post-World War II movement exemplified by playwrights like Samuel Beckett, emphasizing the absurdity of human existence.",
195
+ 'Romans belle époque': "Novels from the Belle Époque, a period of French history marked by optimism, cultural innovations, and artistic flourishing.",
196
+ 'Bible Segond': "A French translation of the Bible by Louis Segond, widely used in French-speaking Protestant communities.",
197
+ 'Zola': "Émile Zola, a key figure in the literary school of naturalism, known for his series of novels 'Les Rougon-Macquart'.",
198
+ 'Pagnol': "Marcel Pagnol, a novelist and filmmaker, celebrated for his works depicting life in Provence, including 'Jean de Florette'.",
199
+ 'Philosophie': "Refers to French philosophy, a rich tradition ranging from existentialism to post-structuralism, featuring thinkers like Sartre and Derrida.",
200
+ 'Poésies': "French poetry, a diverse field ranging from the troubadours of the Middle Ages to the symbolists and modern poets.",
201
+ 'De Gaulle': "Charles de Gaulle, a French general and statesman, pivotal in establishing the Fifth Republic and its constitution.",
202
+ 'Série noire': "A French publishing imprint known for its translations of American hardboiled detective and noir crime fiction.",
203
+ 'San Antonio': "A series of French detective novels by Frédéric Dard, featuring the character San Antonio, known for their humor and inventiveness.",
204
+ 'Duras': "Marguerite Duras, a French writer and film director, known for her minimalist style and works like 'The Lover'.",
205
+ '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.",
206
+ 'Braudel': "Fernand Braudel, a French historian who revolutionized the study of history by focusing on long-term social and geographic structures.",
207
+ 'Bourdieu': "Pierre Bourdieu, a French sociologist, renowned for his theory of social practices and concepts like cultural capital.",
208
+ 'Derrida': "Jacques Derrida, a philosopher best known for developing deconstruction, a critical approach that questions the relationship between text and meaning.",
209
+ 'Baudrillard': "Jean Baudrillard, a cultural theorist known for his analysis of consumerism, simulation, and hyperreality."
210
+ }
211
+
212
+ # Function to return the explanation based on the selected artist or style
213
+ def update_explanation(choice):
214
+ global selected_style
215
+ selected_style = choice
216
+ return explanations.get(choice, "No explanation available.")
217
 
218
  additional_inputs=[
 
219
  gr.Slider(
220
  label="Température",
221
  value=0.7, # Default value
 
227
  ),
228
  ]
229
 
230
+ # Use gradio.Blocks for a more dynamic interface
231
+ with gr.Blocks() as demo:
232
+ # Block 1: Title, Description, Dropdown, Explanation
233
+ gr.Markdown(title)
234
+ gr.Markdown(description)
235
+ with gr.Row():
236
+ dropdown = gr.Dropdown(list_dropdown, label="Choose an Artist or Style")
237
+ explanation_box = gr.Textbox(label="Explanation", type="text", lines=5, interactive=False)
238
+ dropdown.change(update_explanation, inputs=dropdown, outputs=explanation_box)
239
+
240
+ # Block 2: Embedding the Gradio Interface
241
+ iface = gr.Interface(
242
+ fn=mistral_bot.predict,
243
+ examples = examples,
244
+ inputs=[gr.Textbox(label="Question ou votre instruction", type="text", lines=5, placeholder="Commencer à écrire ici")] + additional_inputs,
245
+ outputs=gr.Textbox(label="Réponse", type="text", lines=5),
246
+ theme="carlosrosash/bellay_test",
247
+ )
248
+
249
+ # Initialize the shared variable
250
+ selected_style = "Proust" # Default value or any value from your dropdown list
251
+
252
+ demo.launch()