File size: 10,762 Bytes
fbfc907
ad2ab25
 
 
9f8226f
2978777
ad2ab25
 
fbfc907
2978777
d4efb04
ad2ab25
83e8d61
d4efb04
c3e7be2
83e8d61
5fbe3e5
c3e7be2
d4efb04
c3e7be2
83e8d61
5fbe3e5
c3e7be2
d4efb04
ad2ab25
 
2978777
 
 
 
b21e058
2978777
 
 
 
 
 
 
 
 
 
 
 
 
ad2ab25
 
 
 
 
 
 
f9d12de
 
ad2ab25
 
 
 
fbfc907
 
 
 
ad2ab25
2978777
0179a13
 
2978777
ad2ab25
fbfc907
 
 
 
 
 
ad2ab25
 
 
 
 
fbfc907
ad2ab25
fbfc907
ad2ab25
 
 
 
 
589e0e8
a434986
 
ad2ab25
 
 
 
 
 
 
 
 
 
 
2978777
0179a13
2978777
b21e058
 
 
 
 
 
 
b52e67d
 
 
 
 
589e0e8
 
b52e67d
 
 
 
 
 
9f8226f
0aa6a75
 
 
589e0e8
 
0aa6a75
ad2ab25
0aa6a75
5a9d2e7
0aa6a75
589e0e8
 
5a9d2e7
 
ad2ab25
 
 
 
b21e058
ad2ab25
 
0179a13
6d6ce37
fbfc907
dd7d4a5
fbfc907
 
 
 
ad2ab25
 
dd7d4a5
ad2ab25
 
dd7d4a5
ad2ab25
 
 
 
 
dd7d4a5
ad2ab25
 
 
 
 
 
dd7d4a5
ad2ab25
589e0e8
 
 
 
dd7d4a5
589e0e8
dd7d4a5
ad2ab25
dd7d4a5
ad2ab25
dd7d4a5
ad2ab25
 
dd7d4a5
 
ad2ab25
fbfc907
589e0e8
b52e67d
b21e058
ad2ab25
 
 
 
dd7d4a5
ad2ab25
0aa6a75
589e0e8
0aa6a75
 
ad2ab25
 
dd7d4a5
ad2ab25
02b5c61
589e0e8
0aa6a75
d10611d
ad2ab25
 
 
 
 
 
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
import os
import gradio as gr
from gradio.components import Slider
import torch
from transformers import pipeline
import pandas as pd

# Model, information and examples ----------------------------------------------
MODEL_NAMES = ["FLOR-1.3B-GL","Cerebras-1.3B-GL"]
markdown_description_en = """
# Galician LLMs


This space contains the Galician language models developed by [Proxecto Nós](https://nos.gal/en/proxecto-nos).


💐 **[FLOR-1.3B-GL](https://huggingface.co/proxectonos/FLOR-1.3B-GL)** is a 1.3B parameters model which is a Continual pretraining from [FLOR-1.3B](https://huggingface.co/projecte-aina/FLOR-1.3B), which is based in [Bloom 1.7B](https://huggingface.co/bigscience/bloom-1b7).

👀 **Learn more about FLOR-1.3B-GL:** [HF official model card](https://huggingface.co/proxectonos/FLOR-1.3B-GL).


🧠 **[Cerebras-1.3B-GL](https://huggingface.co/proxectonos/Cerebras-1.3B-GL)** is a 1.3B parameters model based in [Cerebras-GPT 1.3B](https://huggingface.co/cerebras/Cerebras-GPT-1.3B).

👀 **Learn more about Cerebras-1.3B-GL:** [HF official model card](https://huggingface.co/proxectonos/Cerebras-1.3B-GL)
"""

markdown_description_gl = """
# LLMs de galego


Este espazo contén diferentes Grandes Modelos da Linguaxe feitos para o galego desenvolvidos polo [Proxecto Nós](https://nos.gal/en/proxecto-nos).


💐 **[FLOR-1.3B-GL](https://huggingface.co/proxectonos/FLOR-1.3B-GL)** é un modelo de parámetros 1.3B que é un preadestramento continuo de [FLOR-1.3B]( https://huggingface.co/projecte-aina/FLOR-1.3B), baseado a súa vez en [Bloom 1.7B](https://huggingface.co/bigscience/bloom-1b7).

👀 **Máis información sobre FLOR-1.3B-GL:** [tarxeta modelo oficial HF](https://huggingface.co/proxectonos/FLOR-1.3B-GL).


🧠 **[Cerebras-1.3B-GL](https://huggingface.co/proxectonos/Cerebras-1.3B-GL)** é un modelo de parámetros 1.3B baseado en [Cerebras-GPT 1.3B](https:/ /huggingface.co/cerebras/Cerebras-GPT-1.3B).

👀 **Máis información sobre Cerebras-1.3B-GL:** [tarxeta modelo oficial HF](https://huggingface.co/proxectonos/Cerebras-1.3B-GL)
"""

markdown_description ={"en": markdown_description_en,"gl": markdown_description_gl}
short_prompts_examples = [
    ["A receita tradicional das filloas é"], 
    ["O neno vivía preto de"]
]

few_shot_prompts_examples = [
    ["Responde á seguinte pregunta. \nPregunta: \"Cal é a capital de Noruega? \"\nResposta: \"A capital de Noruega é Oslo.\"\n---- \nResponde á seguinte pregunta.\nPregunta: \"Cal é a moeda de Portugal\" \nResposta: \"A moeda de Portugal é o euro.\" \n---- \nResponde á seguinte pregunta. \nPregunta: \"Cal é a capital de Suecia?\"\nResposta:"],
    ["Extrae as entidades nomeadas do seguinte texto: \nTexto: \"Chámome Wolfgang e vivo en Berlin\" \nEntidades: Wolfgang:PER, Berlin:LOC \n ---- \nExtrae as entidades nomeadas do seguinte texto: \nTexto: \"María e Miguel non teñen ningún problema\" \nEntidades: María:PER, Miguel:PER \n---- \nExtrae as entidades nomeadas do seguinte texto: \nTexto: \"O mellor de Barcelona é o bar do meu amigo Pablo\" \nEntidades: Pablo:PER, Barcelona:LOC \n---- \nExtrae as entidades nomeadas do seguinte texto: \nTexto: \"Carlos comparte cuarto con Marc\" \nEntidades:"],
    ["Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"Estou moi feliz\"\n Polaridade: Positivo\n ---- \n Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"Non me gusta beber cervexa\"\n Polaridade: Negativo\n ----\n Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"O meu pai detesta o seu traballo\"\n Polaridade: Negativo\n ----\n Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"Uxía desfruta xogando ao fútbol\"\n Polaridade: Positivo\n ----\n Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"O neno non está contento coas notas\"\n Polaridade:"]
]
fronted_theme = 'Soft'

# Model charge ---------------------------------------------------------
model_id_flor  = "proxectonos/FLOR-1.3B-GL"
generator_model_flor = pipeline("text-generation", model=model_id_flor)
model_id_cerebras  = "proxectonos/Cerebras-1.3B-GL"
generator_model_cerebras = pipeline("text-generation", model=model_id_cerebras, token=os.environ['TOKEN_HF'])

# Load language texts ---------------------------------------------------------
df_interface = pd.read_csv("interface_texts.csv")
language = "gl"

# Generation functions ---------------------------------------------------------
def get_model(model_selection):
    if model_selection == "FLOR-1.3B-GL":
        return generator_model_flor
    else:
        return generator_model_cerebras

def remove_empty_lines(text):
    lines = text.strip().split("\n")
    non_empty_lines = [line for line in lines if line.strip()]
    return "\n".join(non_empty_lines)

def predict(prompt, model_select, max_length, repetition_penalty, temperature):
    print("Dentro da xeración...")
    generator_model = get_model(model_select)
    prompt_length = len(generator_model.tokenizer.encode(prompt))
    generated_text = generator_model(
        prompt,
        max_length=prompt_length + max_length, 
        pad_token_id=generator_model.tokenizer.eos_token_id, 
        repetition_penalty=repetition_penalty,
        temperature=temperature,
        do_sample=True)

    generated_sequence = generated_text[0]['generated_text']
    if generated_sequence is  None:
        gr.Warning('Inference endpoint is not available right now. Please try again later.')
        return
    
    generated_sequence = remove_empty_lines(generated_sequence)
    print("Xeración completada")
    return generated_sequence

# Gradio app ---------------------------------------------------------
def get_text_lang(variable):
    return df_interface.loc[df_interface['variable'] == variable, language].values[0]

def change_language(demo):
    if language == "gl":
        language = "en"
    else:
        language = "gl"
    demo.launch()

def clear(): 
    return (
        None, 
        None,
        gr.update(value=20),
        gr.update(value=1.3),
        gr.update(value=0.5)
    )
def pass_to_input(generated_gl):
    return (
        gr.update(value=generated_gl),
        None
    )

def parameters_default(text):
    return (
        gr.update(value=30), # max_length
        gr.update(value=1.3), # repetition_penalty
        gr.update(value=0.5) # temperature
    )

def parameters_fewshot_prompt(text):
    return (
        gr.update(value=15), # max_length
        gr.update(value=1), # repetition_penalty
        gr.update(value=0.5) # temperature
    )

def gradio_app():
    with gr.Blocks(theme=fronted_theme) as demo:
        with gr.Row():
            with gr.Column(scale=0.1):
                change_lang = gr.Button(value=get_text_lang("change_lang"))
                gr.HTML('<img src="https://huggingface.co/spaces/proxectonos/README/resolve/main/title-card.png" width="100%" style="border-radius: 0.75rem;">')
            with gr.Column():
                gr.Markdown(markdown_description[language])
        with gr.Row(equal_height=True):            
                model_select = gr.Dropdown(
                    label=get_text_lang("model_select"),
                    choices=MODEL_NAMES,
                    value=MODEL_NAMES[0],
                    interactive=True
                )
        with gr.Row(equal_height=True):
            with gr.Column():
                text_gl = gr.Textbox(label=get_text_lang("text_gl"), 
                                     lines=6, placeholder="e.g. O neno vai a escola con ")
                with gr.Row(variant="panel"):
                        with gr.Accordion(get_text_lang("accordion_parameters"), open=False):
                            max_length = Slider(
                                minimum=1,
                                maximum=200,
                                step=1,
                                value=30,
                                label=get_text_lang("max_length")
                            )
                            repetition_penalty = Slider(
                                minimum=0.1,
                                maximum=4,
                                step=0.1,
                                value=1.3,
                                label=get_text_lang("repetition_penalty")
                            )
                            temperature = Slider(
                                minimum=0,
                                maximum=1,
                                value=0.5,
                                label=get_text_lang("temperature")
                            )
                generator_btn = gr.Button(value=get_text_lang("generator_btn"),variant='primary')
            with gr.Column():
                generated_gl = gr.Textbox(label=get_text_lang("generated_gl_label"), 
                                          lines=6, 
                                          placeholder=get_text_lang("generated_gl_placeholder"),
                                          interactive=False,
                                          show_copy_button=True)
                pass_btn = gr.Button(value=get_text_lang("pass_btn"))
                clean_btn = gr.Button(value=get_text_lang("clean_btn"))

        generator_btn.click(predict, inputs=[text_gl, model_select, max_length, repetition_penalty, temperature], outputs=generated_gl, api_name="generate-flor-gl")
        clean_btn.click(fn=clear, inputs=[], outputs=[text_gl, generated_gl, max_length, repetition_penalty, temperature], queue=False, api_name=False)
        pass_btn.click(fn=pass_to_input, inputs=[generated_gl], outputs=[text_gl,generated_gl], queue=False, api_name=False)
        change_lang.click(fn=change_language, inputs=[demo], outputs=[], queue=False, api_name=False)
        
        with gr.Row():
            with gr.Column(scale=0.5):
                gr.Examples(
                    label = get_text_lang("examples_short_prompts"),
                    examples = short_prompts_examples,
                    inputs = [text_gl],
                    outputs = [max_length, repetition_penalty, temperature],
                    fn = parameters_default,
                    run_on_click = True
                )
                gr.Examples(
                    label = get_text_lang("examples_few_shot"),
                    examples = few_shot_prompts_examples,
                    inputs = [text_gl],
                    outputs = [max_length, repetition_penalty, temperature],
                    fn = parameters_fewshot_prompt,
                    run_on_click = True
                )

    demo.launch()

if __name__ == "__main__":
    gradio_app()