jeon commited on
Commit
6071116
โ€ข
1 Parent(s): 1dc5e11
Files changed (3) hide show
  1. app.py +104 -42
  2. hugging-face-korea.png +0 -0
  3. theme_dropdown.py +0 -57
app.py CHANGED
@@ -1,58 +1,120 @@
1
- import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- from theme_dropdown import create_theme_dropdown # noqa: F401
 
4
 
5
- import gradio as gr
6
 
7
- dropdown, js = create_theme_dropdown()
8
 
9
- with gr.Blocks(theme='pseudolab/huggingface-korea-theme') as demo:
10
- with gr.Row():
11
- with gr.Column(scale=10):
12
- gr.Markdown(
13
- """
14
- thank you for dong wook
15
- """
16
- )
17
 
 
 
 
18
 
19
- dropdown.change(None, dropdown, None, _js=js)
 
 
 
 
20
 
 
 
21
 
22
- name = gr.Textbox(
23
- label="Name",
24
- info="Full name, including middle name. No special characters.",
25
- placeholder="Jini77",
26
- value="Jini77",
27
- interactive=True,
28
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
 
 
30
 
31
- def go(*args):
32
- time.sleep(3)
33
- return "https://huggingface.co/spaces/pseudolab/interviewer_chat/blob/main/hugging-face-korea.png"
34
 
35
- def clear():
36
- time.sleep(0.2)
37
- return None
38
 
39
- with gr.Row():
40
- with gr.Column(scale=2):
41
- chatbot = gr.Chatbot([("Hello", "Hi")], label="Chatbot")
42
- chat_btn = gr.Button("Add messages")
43
 
44
- def chat(history):
45
- time.sleep(2)
46
- yield [["How are you?", "I am good."]]
47
 
48
- chat_btn.click(
49
- lambda history: history
50
- + [["How are you?", "I am good."]]
51
- + (time.sleep(2) or []),
52
- chatbot,
53
- chatbot,
54
- )
55
 
 
 
 
 
 
 
 
 
 
56
 
57
- if __name__ == "__main__":
58
- demo.queue().launch()
 
1
+ from transformers import AutoConfig, AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForCausalLM, MistralForCausalLM
2
+ from peft import PeftModel, PeftConfig
3
+ import torch
4
+ import gradio as gr
5
+ import random
6
+ from textwrap import wrap
7
+
8
+
9
+ # Functions to Wrap the Prompt Correctly
10
+ def wrap_text(text, width=90):
11
+ lines = text.split('\n')
12
+ wrapped_lines = [textwrap.fill(line, width=width) for line in lines]
13
+ wrapped_text = '\n'.join(wrapped_lines)
14
+ return wrapped_text
15
+
16
+
17
+ def multimodal_prompt(user_input, system_prompt="You are an expert medical analyst:"):
18
+ """
19
+ Generates text using a large language model, given a user input and a system prompt.
20
+ Args:
21
+ user_input: The user's input text to generate a response for.
22
+ system_prompt: Optional system prompt.
23
+ Returns:
24
+ A string containing the generated text.
25
+ """
26
+ # Combine user input and system prompt
27
+ formatted_input = f"<s>[INST]{system_prompt} {user_input}[/INST]"
28
+
29
+ # Encode the input text
30
+ encodeds = tokenizer(formatted_input, return_tensors="pt", add_special_tokens=False)
31
+ model_inputs = encodeds.to(device)
32
+
33
+ # Generate a response using the model
34
+ output = model.generate(
35
+ **model_inputs,
36
+ max_length=max_length,
37
+ use_cache=True,
38
+ early_stopping=True,
39
+ bos_token_id=model.config.bos_token_id,
40
+ eos_token_id=model.config.eos_token_id,
41
+ pad_token_id=model.config.eos_token_id,
42
+ temperature=0.1,
43
+ do_sample=True
44
+ )
45
 
46
+ # Decode the response
47
+ response_text = tokenizer.decode(output[0], skip_special_tokens=True)
48
 
49
+ return response_text
50
 
 
51
 
52
+ # Define the device
53
+ device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
54
 
55
+ # Use the base model's ID
56
+ base_model_id = "mistralai/Mistral-7B-v0.1"
57
+ model_directory = "Tonic/mistralmed"
58
 
59
+ # Instantiate the Tokenizer
60
+ tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", trust_remote_code=True, padding_side="left")
61
+ # tokenizer = AutoTokenizer.from_pretrained("Tonic/mistralmed", trust_remote_code=True, padding_side="left")
62
+ tokenizer.pad_token = tokenizer.eos_token
63
+ tokenizer.padding_side = 'left'
64
 
65
+ # Specify the configuration class for the model
66
+ # model_config = AutoConfig.from_pretrained(base_model_id)
67
 
68
+ # Load the PEFT model with the specified configuration
69
+ # peft_model = AutoModelForCausalLM.from_pretrained(base_model_id, config=model_config)
70
+
71
+ # Load the PEFT model
72
+ peft_config = PeftConfig.from_pretrained("Tonic/mistralmed", token="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")
73
+ peft_model = MistralForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", trust_remote_code=True)
74
+ peft_model = PeftModel.from_pretrained(peft_model, "Tonic/mistralmed", token="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")
75
+
76
+
77
+ class ChatBot:
78
+ def __init__(self):
79
+ self.history = []
80
+
81
+
82
+ class ChatBot:
83
+ def __init__(self):
84
+ # Initialize the ChatBot class with an empty history
85
+ self.history = []
86
+
87
+ def predict(self, user_input, system_prompt="You are an expert medical analyst:"):
88
+ # Combine the user's input with the system prompt
89
+ formatted_input = f"<s>[INST]{system_prompt} {user_input}[/INST]"
90
+
91
+ # Encode the formatted input using the tokenizer
92
+ user_input_ids = tokenizer.encode(formatted_input, return_tensors="pt")
93
 
94
+ # Generate a response using the PEFT model
95
+ response = peft_model.generate(input_ids=user_input_ids, max_length=512, pad_token_id=tokenizer.eos_token_id)
96
 
97
+ # Decode the generated response to text
98
+ response_text = tokenizer.decode(response[0], skip_special_tokens=True)
 
99
 
100
+ return response_text # Return the generated response
 
 
101
 
 
 
 
 
102
 
103
+ bot = ChatBot()
 
 
104
 
105
+ title = "์ž์†Œ์„œ๊ธฐ๋ฐ˜ ๋ฉด์ ‘ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ chat bot (this template based on Tonic's MistralMed Chat)"
106
+ #description = "์ด ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•˜์—ฌ ํ˜„์žฌ ๋ชจ๋ธ์„ ํ…Œ์ŠคํŠธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. [(Tonic/MistralMed)](https://huggingface.co/Tonic/MistralMed) ๋˜๋Š” ์ด ๊ณต๊ฐ„์„ ๋ณต์ œํ•˜๊ณ  ๋กœ์ปฌ ๋˜๋Š” ๐Ÿค—HuggingFace์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. [Discord์—์„œ ํ•จ๊ป˜ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด Discord์— ๊ฐ€์ž…ํ•˜์‹ญ์‹œ์˜ค](https://discord.gg/VqTxc76K3u). You can use this Space to test out the current model [(Tonic/MistralMed)](https://huggingface.co/Tonic/MistralMed) or duplicate this Space and use it locally or on ๐Ÿค—HuggingFace. [Join me on Discord to build together](https://discord.gg/VqTxc76K3u)."
107
+ #examples = [["[Question:] What is the proper treatment for buccal herpes?",
108
+ # "You are a medicine and public health expert, you will receive a question, answer the question, and provide a complete answer"]]
 
 
 
109
 
110
+ iface = gr.Interface(
111
+ fn=bot.predict,
112
+ title=title,
113
+ description=description,
114
+ examples=examples,
115
+ inputs=["text", "text"], # Take user input and system prompt separately
116
+ outputs="text",
117
+ theme="ParityError/Anime"
118
+ )
119
 
120
+ iface.launch()
 
hugging-face-korea.png DELETED
Binary file (7.98 kB)
 
theme_dropdown.py DELETED
@@ -1,57 +0,0 @@
1
- import os
2
- import pathlib
3
-
4
- from gradio.themes.utils import ThemeAsset
5
-
6
-
7
- def create_theme_dropdown():
8
- import gradio as gr
9
-
10
- asset_path = pathlib.Path(__file__).parent / "themes"
11
- themes = []
12
- for theme_asset in os.listdir(str(asset_path)):
13
- themes.append(
14
- (ThemeAsset(theme_asset), gr.Theme.load(str(asset_path / theme_asset)))
15
- )
16
-
17
- def make_else_if(theme_asset):
18
- return f"""
19
- else if (theme == '{str(theme_asset[0].version)}') {{
20
- var theme_css = `{theme_asset[1]._get_theme_css()}`
21
- }}"""
22
-
23
- head, tail = themes[0], themes[1:]
24
- if_statement = f"""
25
- if (theme == "{str(head[0].version)}") {{
26
- var theme_css = `{head[1]._get_theme_css()}`
27
- }} {" ".join(make_else_if(t) for t in tail)}
28
- """
29
-
30
- latest_to_oldest = sorted([t[0] for t in themes], key=lambda asset: asset.version)[
31
- ::-1
32
- ]
33
- latest_to_oldest = [str(t.version) for t in latest_to_oldest]
34
-
35
- component = gr.Dropdown(
36
- choices=latest_to_oldest,
37
- value=latest_to_oldest[0],
38
- render=False,
39
- label="Select Version",
40
- )
41
-
42
- return (
43
- component,
44
- f"""
45
- (theme) => {{
46
- if (!document.querySelector('.theme-css')) {{
47
- var theme_elem = document.createElement('style');
48
- theme_elem.classList.add('theme-css');
49
- document.head.appendChild(theme_elem);
50
- }} else {{
51
- var theme_elem = document.querySelector('.theme-css');
52
- }}
53
- {if_statement}
54
- theme_elem.innerHTML = theme_css;
55
- }}
56
- """,
57
- )