carlosrosash commited on
Commit
8996981
1 Parent(s): 1db0ac6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -76
app.py CHANGED
@@ -13,39 +13,6 @@ 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
22
-
23
- with Column(variant="panel"):
24
- input_component_column = Column()
25
- with input_component_column:
26
- for component in self.input_components:
27
- component.render()
28
- with Row():
29
- if self.interface_type in [InterfaceTypes.STANDARD, InterfaceTypes.INPUT_ONLY]:
30
- clear_btn = ClearButton(value="Effacer ❌")
31
- if not self.live:
32
- submit_btn = Button("Soumettez votre requête ✅", variant="primary") # Custom label
33
- if inspect.isgeneratorfunction(self.fn) or inspect.isasyncgenfunction(self.fn):
34
- stop_btn = Button("Stop", variant="stop", visible=False)
35
- elif self.interface_type == InterfaceTypes.UNIFIED:
36
- clear_btn = ClearButton(value="Effacer ❌")
37
- submit_btn = Button("Soumettez votre requête ✅", variant="primary") # Custom label
38
- if (inspect.isgeneratorfunction(self.fn) or inspect.isasyncgenfunction(self.fn)) and not self.live:
39
- stop_btn = Button("Stop", variant="stop")
40
- if self.allow_flagging == "manual":
41
- flag_btns = self.render_flag_btns()
42
- elif self.allow_flagging == "auto":
43
- flag_btns = [submit_btn]
44
-
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 +25,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.",
@@ -118,24 +84,20 @@ class MistralChatBot:
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,29 +140,97 @@ 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
187
- minimum=0.05,
188
- maximum=1.0,
189
- step=0.05,
190
- interactive=True,
191
- info="Des valeurs plus élevées donne plus de créativité, mais aussi d'étrangeté",
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
  # Define the device
17
  device = "cuda" if torch.cuda.is_available() else "cpu"
18
  #Define variables
 
25
 
26
  llm = LLM(model_name)
27
 
 
28
  styles_prompts_dict = {
29
  "Chansons de gestes": "Tu es Bellay, le troubadour du moyen-âge. Répond à la manière d’une belle chanson de geste.",
30
  "Constitutions françaises": "Tu es Bellay, le spécialiste de la vie politique française. Répond dans le style d’une constitution.",
 
84
  # Create the Mistral chatbot instance
85
  mistral_bot = MistralChatBot()
86
 
87
+ title = """
88
+ <h1 style='text-align: center; font-weight: bold;'> Bellay, le premier LLM de la littérature française</h1>
89
+ """
90
  description = """
91
+ <p style='text-align: justify;'>
92
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus elementum leo a
93
+ tortor fringilla elementum. Nullam eget sodales lacus. Nullam non aliquet elit.
94
+ Etiam enim arcu, vehicula nec enim id, laoreet sodales justo. Nulla feugiat non
95
+ leo in interdum. Quisque id leo ligula. Etiam id quam urna. Morbi tincidunt eros
96
+ in eros vulputate, a congue enim feugiat. Ut laoreet ex in dui ultrices elementum.
97
+ Vivamus eget venenatis dui. Vestibulum dictum ipsum eu mauris convallis, sit amet
98
+ sollicitudin orci lacinia. Nunc pellentesque hendrerit felis eleifend interdum.
99
+ Ut ac volutpat nisi.
100
+ </p>
 
 
 
 
 
101
  """
102
  examples = [
103
  [
 
140
  'Romans contemporains'
141
  ]
142
 
143
+ # Dictionary of explanations for each artist or style
144
+ explanations = {
145
+ 'Proust': "Marcel Proust, known for his introspective and lengthy novel 'In Search of Lost Time', which explores themes of memory and time.",
146
+ 'Encyclopédie': "A groundbreaking Enlightenment-era work, edited by Diderot and d'Alembert, aiming to compile and disseminate human knowledge.",
147
+ 'Balzac': "Honoré de Balzac, a French novelist and playwright, famous for his detailed depiction of society in 'La Comédie Humaine'.",
148
+ 'Montaigne': "Michel de Montaigne, a Renaissance philosopher known for popularizing the essay as a literary genre, exploring human nature.",
149
+ 'Foucault': "Michel Foucault, a 20th-century philosopher and social theorist, known for his analysis of power and societal institutions.",
150
+ 'Chansons de gestes': "Medieval epic poems celebrating heroic deeds, exemplified by 'The Song of Roland', key to French literary history.",
151
+ 'Constitutions françaises': "Refers to the various constitutions that France has had throughout its history, each shaping its political landscape.",
152
+ 'La Fontaine': "Jean de La Fontaine, famed for his Fables, which are moralistic stories often featuring animals and conveying ethical lessons.",
153
+ 'Madame de Sévigné': "Marie de Rabutin-Chantal, Marquise de Sévigné, known for her detailed and insightful letters depicting French aristocratic life.",
154
+ 'Molière': "Jean-Baptiste Poquelin, known as Molière, a playwright and actor, acclaimed for his comedies like 'Tartuffe' and 'The Misanthrope'.",
155
+ 'Racine': "Jean Racine, a playwright of the French classical era, renowned for his tragedies like 'Phèdre' and 'Andromaque'.",
156
+ 'Romans classiques': "Refers to classic French novels, characterized by their adherence to traditional literary standards and themes.",
157
+ 'Romans romantiques': "Romantic-era French novels, emphasizing emotion, nature, and individualism, contrasting with the rationality of Enlightenment.",
158
+ 'Théâtre absurde': "Absurdist theatre, a post-World War II movement exemplified by playwrights like Samuel Beckett, emphasizing the absurdity of human existence.",
159
+ 'Romans belle époque': "Novels from the Belle Époque, a period of French history marked by optimism, cultural innovations, and artistic flourishing.",
160
+ 'Bible Segond': "A French translation of the Bible by Louis Segond, widely used in French-speaking Protestant communities.",
161
+ 'Zola': "Émile Zola, a key figure in the literary school of naturalism, known for his series of novels 'Les Rougon-Macquart'.",
162
+ 'Pagnol': "Marcel Pagnol, a novelist and filmmaker, celebrated for his works depicting life in Provence, including 'Jean de Florette'.",
163
+ 'Philosophie': "Refers to French philosophy, a rich tradition ranging from existentialism to post-structuralism, featuring thinkers like Sartre and Derrida.",
164
+ 'Poésies': "French poetry, a diverse field ranging from the troubadours of the Middle Ages to the symbolists and modern poets.",
165
+ 'De Gaulle': "Charles de Gaulle, a French general and statesman, pivotal in establishing the Fifth Republic and its constitution.",
166
+ 'Série noire': "A French publishing imprint known for its translations of American hardboiled detective and noir crime fiction.",
167
+ 'San Antonio': "A series of French detective novels by Frédéric Dard, featuring the character San Antonio, known for their humor and inventiveness.",
168
+ 'Duras': "Marguerite Duras, a French writer and film director, known for her minimalist style and works like 'The Lover'.",
169
+ '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.",
170
+ 'Braudel': "Fernand Braudel, a French historian who revolutionized the study of history by focusing on long-term social and geographic structures.",
171
+ 'Bourdieu': "Pierre Bourdieu, a French sociologist, renowned for his theory of social practices and concepts like cultural capital.",
172
+ 'Derrida': "Jacques Derrida, a philosopher best known for developing deconstruction, a critical approach that questions the relationship between text and meaning.",
173
+ 'Baudrillard': "Jean Baudrillard, a cultural theorist known for his analysis of consumerism, simulation, and hyperreality."
174
+ }
175
 
176
+ def fill_example(data):
177
+ question, style, temp = data
178
+ user_input.update(question)
179
+ dropdown.change(style)
180
+ temperature_slider.change(temp)
181
+ 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."
182
+
183
+
184
+ # Function to return the explanation based on the selected artist or style
185
+ def update_explanation(choice):
186
+ return explanations.get(choice, "No explanation available.")
187
+
188
+ # Define the Gradio interface using Blocks
189
+ with gr.Blocks(theme = 'carlosrosash/bellay_test') as demo:
190
+ gr.Markdown(title)
191
+ gr.Markdown(description)
192
+ with gr.Row():
193
+ dropdown = gr.Dropdown(list_dropdown, label="Choose an Artist or Style")
194
+ explanation_box = gr.Textbox(label="Explanation", type="text", lines=5, interactive=False)
195
+ dropdown.change(update_explanation, inputs=dropdown, outputs=explanation_box)
196
+
197
+ # Define the columns for input and output
198
+ with gr.Row():
199
+ with gr.Column():
200
+ user_input = gr.Textbox(label="Question or your instruction", type="text", lines=5, placeholder="Start typing here")
201
+ temperature_slider = gr.Slider(label="Temperature", value=0.7, minimum=0.05, maximum=1.0, step=0.05, interactive=True)
202
+ with gr.Row():
203
+ with gr.Column():
204
+ clear_button = gr.Button("Clear")
205
+ with gr.Column():
206
+ submit_button = gr.Button("Submit")
207
+ with gr.Column():
208
+ output_text = gr.Textbox(label="Response", type="text", lines=10)
209
+
210
+ # Function to handle the button click for submit
211
+ def on_submit(user_message, style, temperature):
212
+ return mistral_bot.predict(user_message, style, temperature)
213
+
214
+ # Function to handle the button click for clear
215
+ def on_clear():
216
+ user_input.clear() # Clear the user input
217
+ temperature_slider.change(0.7) # Reset the slider to default
218
+ output_text.clear() # Clear the output text
219
+
220
+ # Reset the dropdown to a default value and update the explanation
221
+ default_style = list_dropdown[0] # Assuming the first value is the default
222
+ dropdown.change(default_style) # Change the dropdown to the default value
223
+ explanation_box.update(explanations[default_style]) # Update the explanation box
224
+
225
+ # Examples section
226
+ gr.Markdown("<h2>Examples</h2>")
227
+ examples_table = gr.Table(headers=["Question ou votre instruction", "Style", "Température"],
228
+ values=[["Comment faire une bonne madeleine ? Donne-moi une recette détaillée avec les ingrédients.", "Proust", 0.7]],
229
+ interactive=True, type="array")
230
+ examples_table.click(fill_example, inputs=examples_table, outputs=output_text)
231
+
232
+
233
+ submit_button.click(on_submit, inputs=[user_input, dropdown, temperature_slider], outputs=output_text)
234
+ clear_button.click(on_clear)
235
+
236
+ demo.launch()