File size: 2,333 Bytes
103a375
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from dotenv import load_dotenv
import numpy as np
from huggingface_hub import snapshot_download 
from llama_cpp import Llama
import gradio as gr

load_dotenv()

task_asr=os.getenv('TASK_TXTGEN')
model_id=os.getenv('MODEL_MISTRAL')
model_file=os.getenv('MODEL_MISTRAL_FILE')

cached_file=snapshot_download(
      repo_id=model_id,
      allow_patterns=model_file,
      local_dir=None
    )

def get_cached_file():
    return cached_file

llm = Llama(
    model_path=cached_file + "/" + model_file,
    verbose=False
    )

B_INST, E_INST = "<s>[INST]", "[/INST]"
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
DEFAULT_SYSTEM_PROMPT = """\
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.

Correct the grammar in the user text.

"""

SYSTEM_PROMPT = B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS

def get_prompt(instruction):
    prompt_template =  B_INST + SYSTEM_PROMPT + instruction + E_INST
    return prompt_template

def improve_grammar(text_input):
    #https://huggingface.co/mzbac/mistral-grammar
    #https://llama-cpp-python.readthedocs.io/en/latest/

    input_prompt = get_prompt(text_input)

    text_output = llm(
        input_prompt,
        temperature=0.0,
        top_p=0.1,
        top_k=40,
        repeat_penalty=1.1,
        max_tokens=2048,
#        n_ctx=2048,
        echo=False
    )
    return text_output['choices'][0]['text']

if __name__ == "__main__":
    with gr.Blocks() as demo:
      mytextinput = gr.Textbox("This is a test box.")
      b1 = gr.Button("Click to improve text")
      mytextimproved = gr.Textbox(
        label="Improved text"
      )
      b1.click(
         fn=improve_grammar,
         inputs=mytextinput,
         outputs=mytextimproved
      )
 
    demo.queue() 
    demo.launch(
        share=False, 
        server_name=os.getenv('GRADIO_SERVER_IP'), 
        server_port=int(os.getenv('GRADIO_SERVER_PORT'))
    )