File size: 3,897 Bytes
173046e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import spaces

title = """# 🙋🏻‍♂️Welcome to 🌟Tonic's ☯️🧑‍💻Yi-Coder-9B-Chat Demo!"""
description = """Yi-Coder-9B-Chat is a 9B parameter model fine-tuned for coding tasks. This demo showcases its ability to generate code based on your prompts. Yi-Coder is a series of open-source code language models that delivers state-of-the-art coding performance with fewer than 10 billion parameters. Excelling in long-context understanding with a maximum context length of 128K tokens. - Supporting 52 major programming languages:
```bash
  'java', 'markdown', 'python', 'php', 'javascript', 'c++', 'c#', 'c', 'typescript', 'html', 'go', 'java_server_pages', 'dart', 'objective-c', 'kotlin', 'tex', 'swift', 'ruby', 'sql', 'rust', 'css', 'yaml', 'matlab', 'lua', 'json', 'shell', 'visual_basic', 'scala', 'rmarkdown', 'pascal', 'fortran', 'haskell', 'assembly', 'perl', 'julia', 'cmake', 'groovy', 'ocaml', 'powershell', 'elixir', 'clojure', 'makefile', 'coffeescript', 'erlang', 'lisp', 'toml', 'batchfile', 'cobol', 'dockerfile', 'r', 'prolog', 'verilog'
  ```
### Join us : 
🌟TeamTonic🌟 is always making cool demos! Join our active builder's 🛠️community 👻 [![Join us on Discord](https://img.shields.io/discord/1109943800132010065?label=Discord&logo=discord&style=flat-square)](https://discord.gg/GWpVpekp) On 🤗Huggingface:[MultiTransformer](https://huggingface.co/MultiTransformer) On 🌐Github: [Tonic-AI](https://github.com/tonic-ai) & contribute to🌟 [Build Tonic](https://git.tonic-ai.com/contribute)🤗Big thanks to Yuvi Sharma and all the folks at huggingface for the community grant 🤗
"""

# Define the device and model path
device = "cuda" if torch.cuda.is_available() else "cpu"
model_path = "01-ai/Yi-Coder-9B-Chat"

# Load the tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto").eval()

@spaces.GPU
def generate_code(system_prompt, user_prompt, max_length):
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ]
    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )
    model_inputs = tokenizer([text], return_tensors="pt").to(device)

    generated_ids = model.generate(
        model_inputs.input_ids,
        max_new_tokens=max_length,
        eos_token_id=tokenizer.eos_token_id  
    )
    generated_ids = [
        output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
    ]

    response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
    return response

def gradio_interface():
    with gr.Blocks() as interface:
        gr.Markdown(title)
        gr.Markdown(description)

        system_prompt_input = gr.Textbox(
            label="☯️Yinstruction:",
            value="You are a helpful coding assistant. Provide clear and concise code examples.",
            lines=2
        )
        user_prompt_input = gr.Code(
            label="🤔Coding Question",
            value="Write a quick sort algorithm in Python.",
            language="python",
            lines=15
        )
        code_output = gr.Code(label="☯️Yi-Coder-7B", language='python', lines=20, interactive=True)
        max_length_slider = gr.Slider(minimum=1, maximum=1800, value=650, label="Max Token Length")

        generate_button = gr.Button("Generate Code")
        generate_button.click(
            generate_code,
            inputs=[system_prompt_input, user_prompt_input, max_length_slider],
            outputs=code_output
        )

    return interface

if __name__ == "__main__":
    interface = gradio_interface()
    interface.launch()