Spaces:
Configuration error
Configuration error
| import os | |
| from threading import Thread | |
| from typing import Iterator | |
| import gradio as gr | |
| import spaces | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer | |
| MAX_MAX_NEW_TOKENS = 1024 | |
| DEFAULT_MAX_NEW_TOKENS = 256 | |
| MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096")) | |
| DESCRIPTION = """\ | |
| # தமிழ் AI உதவியாளர் | |
| இந்தப் பயன்பாட்டு விளக்கம் அன்றாட வாழ்க்கைக்கான AI உதவியாளருக்காக Tamil Llama-2 7b மாதிரியில் இருந்து செய்யப்படுகிறது. | |
| (This Space demonstrates the Tamil Llama-2 7b [model](https://huggingface.co/abhinand/tamil-llama-7b-instruct-v0.1) as a daily life AI assistant.) | |
| """ | |
| LICENSE = """ | |
| <p/> | |
| --- | |
| As a derivate work of [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta, | |
| this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/USE_POLICY.md). | |
| """ | |
| SYSTEM_PROMPT = "ஒரு பணியை எவ்வாறு நிறைவேற்ற வேண்டும் என்று கூறும் அறிவுரை கீழே உள்ளது. வேண்டுகோளைப் பொருத்தமாக நிறைவு செய்கின்ற பதில் ஒன்றை எழுதுக." | |
| PROMPT_TEMPLATE = """{% if messages[0]['role'] == 'system' %}{{ messages[0]['content'] + '\n\n' }}{% endif %}### Instruction:\nநீங்கள் பயனருடன் தொடர்பு கொள்ளும் ஒரு AI உதவியாளர். நீங்கள் பயனருடன் இதுவரை பேசியவை இங்கே உள்ளன:\n\n{% for message in messages %}{% if message['role'] == 'user' %}{{ '\nUser: ' + message['content'] + '\n'}}{% elif message['role'] == 'assistant' %}{{ '\nAI: ' + message['content'] + '\n'}}{% endif %}{% endfor %}\n\nஒரு AI உதவியாளராக, உங்கள் அடுத்த பதிலை உரையாடலில் எழுதவும். ஒரே ஒரு பதிலை மட்டும் எழுதுங்கள்.\n\n### Response:\n""" | |
| if not torch.cuda.is_available(): | |
| DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>" | |
| if torch.cuda.is_available(): | |
| model_id = "abhinand/tamil-llama-7b-instruct-v0.1" | |
| model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto") | |
| tokenizer = AutoTokenizer.from_pretrained(model_id) | |
| tokenizer.chat_template = PROMPT_TEMPLATE | |
| tokenizer.use_default_system_prompt = False | |
| def generate( | |
| message: str, | |
| chat_history: list[tuple[str, str]], | |
| max_new_tokens: int = 1024, | |
| temperature: float = 0.6, | |
| top_p: float = 0.9, | |
| top_k: int = 50, | |
| repetition_penalty: float = 1.2, | |
| ) -> Iterator[str]: | |
| print("chat history: ", chat_history) | |
| conversation = [] | |
| conversation.append({"role": "system", "content": SYSTEM_PROMPT}) | |
| for user, assistant in chat_history: | |
| conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}]) | |
| conversation.append({"role": "user", "content": message}) | |
| print(tokenizer.apply_chat_template(conversation, tokenize=False)) | |
| print("conversation: ", conversation) | |
| input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt") | |
| if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH: | |
| input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:] | |
| gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.") | |
| input_ids = input_ids.to(model.device) | |
| streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True) | |
| generate_kwargs = dict( | |
| {"input_ids": input_ids}, | |
| streamer=streamer, | |
| max_new_tokens=max_new_tokens, | |
| do_sample=True, | |
| top_p=top_p, | |
| top_k=top_k, | |
| temperature=temperature, | |
| num_beams=1, | |
| repetition_penalty=repetition_penalty, | |
| ) | |
| t = Thread(target=model.generate, kwargs=generate_kwargs) | |
| t.start() | |
| outputs = [] | |
| for text in streamer: | |
| outputs.append(text) | |
| yield "".join(outputs) | |
| examples = [ | |
| ["சீக்கிரம் தூங்குவது எப்படி?"], | |
| ["என் முதலாளி என்னை மிகவும் கட்டுப்படுத்துகிறார், நான் என்ன செய்ய வேண்டும்?"], | |
| ["திருமணத்திற்குச் செல்ல நான் என்ன உடை அணிய வேண்டும்?"], | |
| ["வரலாற்றில் இருந்து தெரிந்துகொள்ள வேண்டிய சில முக்கியமான காலகட்டங்கள் என்ன?"], | |
| ["நன்றாக சம்பாதிக்க வேண்டும், ஆனால் மகிழ்ச்சியாக இருக்க வேண்டும். அதற்கு என்ன தொழில் செய்யலாம்?"], | |
| ] | |
| with gr.Blocks(css="style.css") as demo: | |
| gr.Markdown(DESCRIPTION) | |
| chatbot = gr.Chatbot() | |
| msg = gr.Textbox(label="உங்கள் செய்தியை உள்ளிடுக / Enter your message") | |
| submit_btn = gr.Button("சமர்ப்பி / Submit") | |
| clear = gr.Button("அழி / Clear") | |
| def user(user_message, history): | |
| return "", history + [[user_message, None]] | |
| def bot(history, max_new_tokens, temperature, top_p, top_k, repetition_penalty): | |
| user_message = history[-1][0] | |
| chat_history = [(msg[0], msg[1]) for msg in history[:-1]] | |
| bot_message = "" | |
| for response in generate(user_message, chat_history, max_new_tokens, temperature, top_p, top_k, repetition_penalty): | |
| bot_message = response | |
| history[-1][1] = bot_message | |
| yield history | |
| gr.Examples(examples=examples, inputs=[msg], label="எடுத்துக்காட்டுகள் / Examples") | |
| with gr.Accordion("மேம்பட்ட விருப்பங்கள் / Advanced Options", open=False): | |
| max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS) | |
| temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6) | |
| top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9) | |
| top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50) | |
| repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2) | |
| submit_btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then( | |
| bot, | |
| [chatbot, max_new_tokens, temperature, top_p, top_k, repetition_penalty], | |
| chatbot, | |
| ) | |
| msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then( | |
| bot, | |
| [chatbot, max_new_tokens, temperature, top_p, top_k, repetition_penalty], | |
| chatbot, | |
| ) | |
| clear.click(lambda: None, None, chatbot, queue=False) | |
| gr.Markdown(LICENSE) | |
| if __name__ == "__main__": | |
| demo.queue(max_size=20).launch() | |