File size: 8,973 Bytes
a9292a1
 
 
 
 
 
 
 
 
 
 
 
9a18c52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9292a1
 
 
 
 
 
 
c0e1898
a9292a1
 
 
 
9a18c52
a9292a1
 
 
 
 
98ce77a
a9292a1
 
 
9a18c52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9292a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fd33ab
a9292a1
 
 
2fd33ab
a9292a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a18c52
a9292a1
 
 
 
 
 
 
 
 
 
a3365f9
a9292a1
 
 
 
9a18c52
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
"""
File: app.py

Description: Using a large language model for translation.

Author: Didier Guillevic
Date: 2024-09-17
"""
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

import gradio as gr

#import spaces
#import torch
#import transformers
#from transformers import TextIteratorStreamer
#from threading import Thread
#from model_llm import tokenizer, model

import os
from mistralai import Mistral

#
# Mistral AI client
#
api_key = os.environ["MISTRAL_API_KEY"]
client = Mistral(api_key=api_key)
model_id = "mistral-large-latest" # 128k context window


#
# Default instruction: translate given text
#
translation_instruction = (
    "You will be given a text below. First detect the language of the text. "
    "Next, please translate the given text into English. "
    "Simply translate the text. Do not include facts not contained in the "
    "given text below. Text:\n\n"
)

#
# Generate a response using MistralAI API
#
def generate_chat_response_streaming(
        input_text,
        chat_history=None,
        instruction_message=translation_instruction,
        max_new_tokens=1_024,
        temperature=0.0
    ):
    """Given some input from the user (and a chat history), generate a response"""

    # messages up to now
    messages = []
    if not chat_history:
        messages.append({'role': 'user', 'content': instruction_message + ' ' + input_text})
    else:
        for input, response in chat_history:
            messages.append({"role": "user", "content": input})
            messages.append({"role": "assistant", "content": response})
        messages.append({'role': 'user', 'content': input_text})
    logger.info(messages)

    # generate response
    
    # Yield the model response as the tokens are being generated
    stream_reponse = client.chat.stream(model=model_id, messages=messages)
    model_response = ""
    for chunk in stream_reponse:
        model_response += chunk.data.choices[0].delta.content
        yield model_response


#
# Generate a response given some user input and optional chat history
#
#@spaces.GPU
def generate_chat_response_streaming__(
        input_text,
        chat_history=None,
        instruction_message=translation_instruction,
        max_new_tokens=1_024,
        temperature=0.0
    ):
    """Given some input from the user (and a chat history), generate a response"""
    
    # Conversation up to now
    conversation = []
    if not chat_history:
        conversation.append({'role': 'user', 'content': instruction_message + ' ' + input_text})
    else:
        for input, response in chat_history:
            conversation.append({"role": "user", "content": input})
            conversation.append({"role": "assistant", "content": response})
        conversation.append({'role': 'user', 'content': input_text})
    logger.info(conversation)
    
    # Model prompt (specific to a given model)
    model_prompt = tokenizer.apply_chat_template(
        conversation,
        add_generation_prompt=True,
        tokenize=False, # We just want the formatted text
    )

    # Model inputs
    model_inputs = tokenizer([model_prompt], return_tensors='pt').to(model.device)

    # Streamer
    streamer = TextIteratorStreamer(
        tokenizer, timeout=100, skip_prompt=True, skip_special_tokens=True)
    
    # Generation (one token at a time)
    generation_kwargs = dict(
        model_inputs,
        streamer=streamer,
        max_new_tokens=max_new_tokens,
        do_sample=(True if temperature > 0 else False)
    )
    if temperature > 0.0:
        generation_kwargs['temperature'] = temperature
    
    with torch.no_grad():
        thread = Thread(target=model.generate, kwargs=generation_kwargs)
        thread.start()

        # Yield the model response as the tokens are being generated
        model_response = ""
        for new_text in streamer:
            model_response += new_text
            yield model_response


#
# User interface
#
with gr.Blocks() as demo:

    gr.Markdown("""
        ## Text translation using a "standard" Large Language Model (LLM)
    """)
    # User interface
    chatbot = gr.Chatbot(height=400, render=False)
    textbox = gr.Textbox(
        placeholder="Enter text to translate",
        container=False,
        scale=7, lines=1, render=False)
    
    # Additional inputs
    instruction_message = gr.Textbox(
        lines=2,
        value=translation_instruction,
        label="Instruction",
        render=False
    )
    max_new_tokens = gr.Slider(
        minimum=128, maximum=2_048, value=1_024, step=32, label="max new tokens",
        render=False
    )
    temperature = gr.Slider(
        minimum=0.0, maximum=1.0, value=0.0, step=0.1, label="temperature",
        render=False
    )
    
    # Examples
    examples = [
        ["ریچارد مور، رئیس سازمان مخفی اطلاعاتی بریتانیا (ام‌آی‌۶) در دیدار ویلیام برنز، رئیس سازمان اطلاعات مرکزی آمریکا (سیا) گفت همچنان احتمال اقدام ایران علیه اسرائیل در واکنش به ترور اسماعیل هنیه، رهبر حماس وجود دارد. آقای برنز نیز در این دیدار فاش کرد که در سال اول جنگ اوکراین، «خطر واقعی» وجود داشت که روسیه به استفاده از «تسلیحات هسته‌ای تاکتیکی» متوسل شود. این دو مقام امنیتی هشدار دادند که «نظم جهانی» از زمان جنگ سرد تا کنون تا این حد «در معرض تهدید» نبوده است.",],
        ["Clément Delangue est, avec Julien Chaumond et Thomas Wolf, l’un des trois Français cofondateurs de Hugging Face, une start-up d’intelligence artificielle (IA) de premier plan. Valorisée à 4,2 milliards d’euros après avoir levé près de 450 millions d’euros depuis sa création en 2016, cette société de droit américain est connue comme la plate-forme de référence où développeurs et entreprises publient des outils et des modèles pour faire de l’IA en open source, c’est-à-dire accessible gratuitement et modifiable.",],
        ["يُعد تفشي مرض جدري القردة قضية صحية عالمية خطيرة، ومن المهم محاولة منع انتشاره للحفاظ على سلامة الناس وتجنب العدوى. د. صموئيل بولاند، مدير الحوادث الخاصة بمرض الجدري في المكتب الإقليمي لمنظمة الصحة العالمية في أفريقيا، يتحدث من كينشاسا في جمهورية الكونغو الديمقراطية، ولديه بعض النصائح البسيطة التي يمكن للناس اتباعها لتقليل خطر انتشار المرض.",],
        ["【ワシントン=冨山優介】米ボーイングの新型宇宙船「スターライナー」は7日午前0時(日本時間7日午後1時)過ぎ、米ニューメキシコ州のホワイトサンズ宇宙港に着地し、地球に帰還した。スターライナーは米宇宙飛行士2人を乗せて6月に打ち上げられ、国際宇宙ステーション(ISS)に接続したが、機体のトラブルが解決できず、無人でISSから離脱した。",],
        ["張先生稱,奇瑞已經凖備在西班牙生產汽車,並決心採取「本地化」的方式進入歐洲市場。此外,他也否認該公司的出口受益於不公平補貼。奇瑞成立於1997年,是中國最大的汽車公司之一。它已經是中國最大的汽車出口商,並且制定了進一步擴張的野心勃勃的計劃。",],
        ["ברוכה הבאה, קיטי: בית הקפה החדש בלוס אנג'לס החתולה האהובה והחברים שלה מקבלים בית קפה משלהם בשדרות יוניברסל סיטי, שם תוכלו למצוא מגוון של פינוקים מתוקים – החל ממשקאות ועד עוגות",],
    ]

    # User interface
    gr.ChatInterface(
        fn=generate_chat_response_streaming, # by default takes 2 parameters: message, history + additional inputs
        chatbot=chatbot,
        textbox=textbox,
        #clear_btn=None,  # Unfortunately, clear_btn also reset the additional inputs. Hence disabling for now.
        examples=examples,
        cache_examples=False,
        retry_btn="Retry",
        undo_btn="Undo",
        clear_btn="Clear",
        stop_btn="Stop",
        additional_inputs=[instruction_message, max_new_tokens, temperature],
        fill_height=True
    )

    with gr.Accordion("Documentation", open=False):
        gr.Markdown("""
            - Model: using a large language model from Mistral AI
            - Most examples are copy/pasted from BBC news international web sites.
        """)

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