CoolFace
Apppublic

projecte-aina/EADOP-RAG

sourceHugging Faceapache-2.0updated 2y agoView on Hugging Face
2likes
app.py261 linesDownload Raw Back to root
1import os2import gradio as gr3from gradio.components import Textbox, Button, Slider, Checkbox4from AinaTheme import theme5from urllib.error import HTTPError6 7from rag import RAG8from utils import setup9 10MAX_NEW_TOKENS = 70011SHOW_MODEL_PARAMETERS_IN_UI = os.environ.get("SHOW_MODEL_PARAMETERS_IN_UI", default="True") == "True"12 13setup()14 15 16rag = RAG(17    hf_token=os.getenv("HF_TOKEN"),18    embeddings_model=os.getenv("EMBEDDINGS"), 19    model_name=os.getenv("MODEL"),   20    rerank_model=os.getenv("RERANK_MODEL"),21    rerank_number_contexts=int(os.getenv("RERANK_NUMBER_CONTEXTS"))22)23 24 25def generate(prompt, model_parameters):26    try:27        output, context, source = rag.get_response(prompt, model_parameters)28        return output, context, source29    except HTTPError as err:30        if err.code == 400:31            gr.Warning(32                "The inference endpoint is only available Monday through Friday, from 08:00 to 20:00 CET."33            )34    except:35        gr.Warning(36            "Inference endpoint is not available right now. Please try again later."37        )38    return None, None, None39 40 41def submit_input(input_, num_chunks, max_new_tokens, repetition_penalty, top_k, top_p, do_sample, temperature):42    if input_.strip() == "":43        gr.Warning("Not possible to inference an empty input")44        return None45 46 47    model_parameters = {48        "NUM_CHUNKS": num_chunks,49        "max_new_tokens": max_new_tokens,50        "repetition_penalty": repetition_penalty,51        "top_k": top_k,52        "top_p": top_p,53        "do_sample": do_sample,54        "temperature": temperature55    }56 57    output, context, source = generate(input_, model_parameters)58    sources_markup = ""59 60    for url in source:61        sources_markup += f'<a href="{url}" target="_blank">{url}</a><br>'62 63    return output, sources_markup, context  64    # return output.strip(), sources_markup, context65 66 67def change_interactive(text):68    if len(text) == 0:69        return gr.update(interactive=True), gr.update(interactive=False)70    return gr.update(interactive=True), gr.update(interactive=True)71 72 73def clear():74    return (75        None, 76        None,77        None,78        None,79        gr.Slider(value=2.0),80        gr.Slider(value=MAX_NEW_TOKENS),81        gr.Slider(value=1.0),82        gr.Slider(value=50),83        gr.Slider(value=0.99),84        gr.Checkbox(value=False),85        gr.Slider(value=0.35),86    )87 88 89def gradio_app():90    with gr.Blocks(theme=theme) as demo:91        with gr.Row():92            with gr.Column(scale=0.1):93                gr.Image("rag_image.jpg", elem_id="flor-banner", scale=1, height=256, width=256, show_label=False, show_download_button = False, show_share_button = False)94            with gr.Column():95                gr.Markdown(96                    """# Demo de Retrieval-Augmented Generation per documents legals97                    🔍 **Retrieval-Augmented Generation** (RAG) és una tecnologia d'IA que permet interrogar un repositori de documents amb preguntes 98                    en llenguatge natural, i combina tècniques de recuperació d'informació avançades amb models generatius per redactar una resposta 99                    fent servir només la informació existent en els documents del repositori. 100                        101                    🎯 **Objectiu:** Aquest és un demostrador amb la normativa vigent publicada al Diari Oficial de la Generalitat de Catalunya, en el 102                    repositori del EADOP (Entitat Autònoma del Diari Oficial i de Publicacions). Aquesta versió explora prop de 2000 documents en català, 103                    i genera la resposta fent servir el model Salamandra-7b-aligned-EADOP, el model BSC-LT/salamandra-7b-instruct alineat amb el dataset de alinia/EADOP-RAG-out-of-domain. 104                    105                    ⚠️ **Advertencies**: Aquesta versió és experimental. El contingut generat per aquest model no està supervisat i pot ser incorrecte. 106                    Si us plau, tingueu-ho en compte quan exploreu aquest recurs.  El model en inferencia asociat a aquesta demo de desenvolupament no funciona continuament. Si vol fer proves, 107                    contacteu amb nosaltres a Langtech.108 109 110                    👀 **Mes informació en els informes de: ** [RAG](https://drive.google.com/file/d/11MgXQXAxfhkqbrx8syrKtmBrNP_6Qhx9/view?usp=sharing) i [Alineació](https://drive.google.com/file/d/1VUqHKO-gDmgMozK-Al83a2kh4Fr70pHh/view?usp=sharing) en pdf (ànglés).111                    """112                )113        with gr.Row(equal_height=True):114            with gr.Column(variant="panel"):115                input_ = Textbox(116                    lines=11,117                    label="Input",118                    placeholder="Quina és la finalitat del Servei Meteorològic de Catalunya?",119                    # value = "Quina és la finalitat del Servei Meteorològic de Catalunya?"120                )121                with gr.Row(variant="panel"):122                    clear_btn = Button(123                        "Clear",124                    )125                    submit_btn = Button("Submit", variant="primary", interactive=False)126 127                with gr.Row(variant="panel"):128                    with gr.Accordion("Model parameters", open=False, visible=SHOW_MODEL_PARAMETERS_IN_UI):129                        num_chunks = Slider(130                            minimum=1,131                            maximum=6,132                            step=1,133                            value=2,134                            label="Number of chunks"135                        )136                        max_new_tokens = Slider(137                            minimum=50,138                            maximum=2000,139                            step=1,140                            value=MAX_NEW_TOKENS,141                            label="Max tokens"142                        )143                        repetition_penalty = Slider(144                            minimum=0.1,145                            maximum=2.0,146                            step=0.1,147                            value=1.0,148                            label="Repetition penalty"149                        )150                        top_k = Slider(151                            minimum=1,152                            maximum=100,153                            step=1,154                            value=50,155                            label="Top k"156                        )157                        top_p = Slider(158                            minimum=0.01,159                            maximum=0.99,160                            value=0.99,161                            label="Top p"162                        )  163                        do_sample = Checkbox(164                            value=False, 165                            label="Do sample"166                        )167                        temperature = Slider(168                            minimum=0.1, 169                            maximum=1,170                            value=0.35,171                            label="Temperature"172                        )173 174                        parameters_compontents = [num_chunks, max_new_tokens, repetition_penalty, top_k, top_p, do_sample, temperature]175 176            with gr.Column(variant="panel"):177                output = Textbox(178                    lines=10, 179                    label="Output", 180                    interactive=False, 181                    show_copy_button=True182                )183                with gr.Accordion("Sources and context:", open=False):184                    source_context = gr.Markdown(185                        label="Sources",186                        show_label=False,187                    )188                    with gr.Accordion("See full context evaluation:", open=False):189                        context_evaluation = gr.Markdown(190                            label="Full context",191                            show_label=False,192                            # interactive=False, 193                            # autoscroll=False,194                            # show_copy_button=True195                        )196                197 198        input_.change(199            fn=change_interactive,200            inputs=[input_],201            outputs=[clear_btn, submit_btn],202            api_name=False,203        )204 205        input_.change(206            fn=None,207            inputs=[input_],208            api_name=False,209            js="""(i, m) => {210            document.getElementById('inputlenght').textContent = i.length + '  '211            document.getElementById('inputlenght').style.color =  (i.length > m) ? "#ef4444" : "";212        }""",213        )214 215        clear_btn.click(216            fn=clear, 217            inputs=[], 218            outputs=[input_, output, source_context, context_evaluation] + parameters_compontents,219              queue=False, 220              api_name=False221        )222        223        submit_btn.click(224            fn=submit_input, 225            inputs=[input_]+ parameters_compontents, 226            outputs=[output, source_context, context_evaluation],227            api_name="get-results"228        )229 230        with gr.Row():231            with gr.Column(scale=0.5):232                gr.Examples(233                    examples=[234                        ["""Què és l'EADOP (Entitat Autònoma del Diari Oficial i de Publicacions)?"""],235                    ],236                    inputs=input_,237                    outputs=[output, source_context, context_evaluation],238                    fn=submit_input,239                )240                gr.Examples(241                    examples=[242                        ["""Com es pot inscriure una persona al Registre de catalans i catalanes residents a l'exterior?"""],243                    ],244                    inputs=input_,245                    outputs=[output, source_context, context_evaluation],246                    fn=submit_input,247                )248                gr.Examples(249                    examples=[250                        ["""Quina és la finalitat del Servei Meterològic de Catalunya ?"""],251                    ],252                    inputs=input_,253                    outputs=[output, source_context, context_evaluation],254                    fn=submit_input,255                )256 257        demo.launch(show_api=True)258 259 260if __name__ == "__main__":261    gradio_app()