File size: 1,937 Bytes
b5ab706
 
 
95f51ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5ab706
 
95f51ef
 
b5ab706
95f51ef
 
 
b5ab706
95f51ef
b5ab706
95f51ef
b5ab706
95f51ef
 
 
 
b5ab706
 
 
 
 
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
import gradio as gr
from huggingface_hub import InferenceClient

# Initialize the inference client for AraT5
# Make sure you have HF_TOKEN in your environment if the model requires auth
client = InferenceClient(model="UBC-NLP/AraT5v2-base-1024")

def format_history(history, user_message, system_message):
    """
    Format chat history into a single T5-style input string.
    AraT5 is not a chat model, so we need to combine conversation turns into plain text.
    """
    conversation = f"system: {system_message}\n"
    for user, bot in history:
        if user:
            conversation += f"user: {user}\n"
        if bot:
            conversation += f"assistant: {bot}\n"
    conversation += f"user: {user_message}\nassistant:"
    return conversation

def respond(message, history, system_message, max_tokens, temperature, top_p):
    """
    Handle user input, format it for AraT5, and get a generated response.
    """
    # Format the history into one text prompt
    prompt = format_history(history, message, system_message)

    # Stream the model's output
    response_text = ""
    for chunk in client.text_generation(
        prompt,
        max_new_tokens=max_tokens,
        temperature=temperature,
        top_p=top_p,
        stream=True,
        repetition_penalty=1.1
    ):
        token = chunk.token.text
        response_text += token
        yield response_text

# Create the Gradio Chat Interface
demo = gr.ChatInterface(
    fn=respond,
    additional_inputs=[
        gr.Textbox(value="أنت مساعد ذكي تجيب باللغة العربية.", label="System message"),
        gr.Slider(minimum=1, maximum=512, value=256, step=1, label="Max new tokens"),
        gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
        gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p (nucleus sampling)"),
    ],
)

if __name__ == "__main__":
    demo.launch()