paddle12 commited on
Commit
50b01c5
·
verified ·
1 Parent(s): 655da70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -33
app.py CHANGED
@@ -1,34 +1,147 @@
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- import pandas as pd
3
- import plotly.express as px
4
-
5
- def load_table(file):
6
- df = pd.read_excel(file.name) if file.name.endswith(".xlsx") else pd.read_csv(file.name)
7
- table_md = df.to_markdown(index=False)
8
- return table_md, df
9
-
10
- def visualize(df):
11
- if df is None or df.empty:
12
- return "No data to plot"
13
- fig = px.bar(df, x=df.columns[0], y=df.columns[1])
14
- return fig
15
-
16
- with gr.Blocks() as demo:
17
- gr.Markdown("## Selamat Datang di Tertata")
18
-
19
- with gr.Tab("1. Upload & Chat"):
20
- with gr.Row():
21
- with gr.Column(scale=1, min_width=300):
22
- file_input = gr.File(label="Upload file CSV/XLSX")
23
- chatbox = gr.Textbox(label="Masukkan pertanyaan Anda", placeholder="Tanyakan sesuatu...", lines=1)
24
- with gr.Column(scale=2, min_width=500, scrollable=True):
25
- table_output = gr.Textbox(label="Tabel (Markdown)", lines=20, interactive=False, show_copy_button=True)
26
- df_state = gr.State()
27
- file_input.change(fn=load_table, inputs=file_input, outputs=[table_output, df_state])
28
-
29
- with gr.Tab("2. Visualisasi"):
30
- vis_output = gr.Plot()
31
- vis_btn = gr.Button("Tampilkan Visualisasi")
32
- vis_btn.click(fn=visualize, inputs=df_state, outputs=vis_output)
33
-
34
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ history
3
+ blame
4
+ contribute
5
+ delete
6
+ 5 kB
7
+ import os
8
+ from collections.abc import Iterator
9
+ from threading import Thread
10
+
11
  import gradio as gr
12
+ import spaces
13
+ import torch
14
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
15
+
16
+ MAX_MAX_NEW_TOKENS = 2048
17
+ DEFAULT_MAX_NEW_TOKENS = 1024
18
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
19
+
20
+ DESCRIPTION = """\
21
+ # Llama-2 7B Chat
22
+ This Space demonstrates model [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta, a Llama 2 model with 7B parameters fine-tuned for chat instructions. Feel free to play with it, or duplicate to run generations without a queue! If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://huggingface.co/inference-endpoints).
23
+ 🔎 For more details about the Llama 2 family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/llama2).
24
+ 🔨 Looking for an even more powerful model? Check out the [13B version](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat) or the large [70B model demo](https://huggingface.co/spaces/ysharma/Explore_llamav2_with_TGI).
25
+ """
26
+
27
+ LICENSE = """
28
+ <p/>
29
+ ---
30
+ As a derivate work of [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta,
31
+ 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).
32
+ """
33
+
34
+ if not torch.cuda.is_available():
35
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
36
+
37
+
38
+ if torch.cuda.is_available():
39
+ model_id = "meta-llama/Llama-2-7b-chat-hf"
40
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
41
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
42
+ tokenizer.use_default_system_prompt = False
43
+
44
+
45
+ @spaces.GPU
46
+ def generate(
47
+ message: str,
48
+ chat_history: list[dict],
49
+ system_prompt: str = "",
50
+ max_new_tokens: int = 1024,
51
+ temperature: float = 0.6,
52
+ top_p: float = 0.9,
53
+ top_k: int = 50,
54
+ repetition_penalty: float = 1.2,
55
+ ) -> Iterator[str]:
56
+ conversation = []
57
+ if system_prompt:
58
+ conversation.append({"role": "system", "content": system_prompt})
59
+ conversation += chat_history
60
+ conversation.append({"role": "user", "content": message})
61
+
62
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
63
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
64
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
65
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
66
+ input_ids = input_ids.to(model.device)
67
+
68
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
69
+ generate_kwargs = dict(
70
+ {"input_ids": input_ids},
71
+ streamer=streamer,
72
+ max_new_tokens=max_new_tokens,
73
+ do_sample=True,
74
+ top_p=top_p,
75
+ top_k=top_k,
76
+ temperature=temperature,
77
+ num_beams=1,
78
+ repetition_penalty=repetition_penalty,
79
+ )
80
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
81
+ t.start()
82
+
83
+ outputs = []
84
+ for text in streamer:
85
+ outputs.append(text)
86
+ yield "".join(outputs)
87
+
88
+
89
+ chat_interface = gr.ChatInterface(
90
+ fn=generate,
91
+ additional_inputs=[
92
+ gr.Textbox(label="System prompt", lines=6),
93
+ gr.Slider(
94
+ label="Max new tokens",
95
+ minimum=1,
96
+ maximum=MAX_MAX_NEW_TOKENS,
97
+ step=1,
98
+ value=DEFAULT_MAX_NEW_TOKENS,
99
+ ),
100
+ gr.Slider(
101
+ label="Temperature",
102
+ minimum=0.1,
103
+ maximum=4.0,
104
+ step=0.1,
105
+ value=0.6,
106
+ ),
107
+ gr.Slider(
108
+ label="Top-p (nucleus sampling)",
109
+ minimum=0.05,
110
+ maximum=1.0,
111
+ step=0.05,
112
+ value=0.9,
113
+ ),
114
+ gr.Slider(
115
+ label="Top-k",
116
+ minimum=1,
117
+ maximum=1000,
118
+ step=1,
119
+ value=50,
120
+ ),
121
+ gr.Slider(
122
+ label="Repetition penalty",
123
+ minimum=1.0,
124
+ maximum=2.0,
125
+ step=0.05,
126
+ value=1.2,
127
+ ),
128
+ ],
129
+ stop_btn=None,
130
+ examples=[
131
+ ["Hello there! How are you doing?"],
132
+ ["Can you explain briefly to me what is the Python programming language?"],
133
+ ["Explain the plot of Cinderella in a sentence."],
134
+ ["How many hours does it take a man to eat a Helicopter?"],
135
+ ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
136
+ ],
137
+ cache_examples=False,
138
+ type="messages",
139
+ )
140
+
141
+ # with gr.Blocks(css_paths="style.css", fill_height=True) as demo:
142
+ # gr.Markdown(DESCRIPTION)
143
+ # chat_interface.render()
144
+ # gr.Markdown(LICENSE)
145
+
146
+ if __name__ == "__main__":
147
+ demo.queue(max_size=20).launch()