Satyam-Singh commited on
Commit
75bf577
1 Parent(s): 47bb1e7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -166
app.py CHANGED
@@ -1,178 +1,103 @@
1
- from huggingface_hub import InferenceClient
2
  import gradio as gr
3
- import os
4
- import random
5
- client = InferenceClient("Satyam-Singh/LLaVa-Large-Language-Virtual-Assistant")
6
 
7
- history=[
8
- {
9
- "role": "user",
10
- "parts": ["who are you"]
11
- },
12
- {
13
- "role": "model",
14
- "parts": ["I am LLAVA, a large language virtual assistant."]
15
- },
16
- {
17
- "role": "user",
18
- "parts": ["who are you"]
19
- },
20
- {
21
- "role": "model",
22
- "parts": ["I am a large language model, trained by Satyam SIngh."]
23
- },
24
- {
25
- "role": "user",
26
- "parts": ["who created you"]
27
- },
28
- {
29
- "role": "model",
30
- "parts": ["I was created by Satyam Singh."]
31
- },
32
- {
33
- "role": "user",
34
- "parts": ["what is your name"]
35
- },
36
- {
37
- "role": "model",
38
- "parts": ["LLAVA: Large Language Virtual Assistant"]
39
- },
40
- {
41
- "role": "user",
42
- "parts": ["who invented you"]
43
- },
44
- {
45
- "role": "model",
46
- "parts": ["Satyam Singh invented me."]
47
- },
48
- {
49
- "role": "user",
50
- "parts": ["write a code to remove even numbers from a list using remove function l=[1,2,2,2,3,4,5,6,7,7,8,8]"]
51
- },
52
- {
53
- "role": "model",
54
- "parts": ["l = [1, 2, 2, 2, 3, 4, 5, 6, 7, 7, 8, 8]for i in l[:]: # use slicing to create a copy of the original list if i % 2 == 0: l.remove(i)print(l)"]
55
- },
56
- {
57
- "role": "user",
58
- "parts": ["on what parameters you were trained"]
59
- },
60
- {
61
- "role": "model",
62
- "parts": ["I have been trained on a massive amount of text data, including books, articles, websites, and conversations. This data has been processed and analyzed using advanced machine learning algorithms, which have allowed me to learn the patterns and relationships in human language.\n\nSpecifically, I was trained on the following parameters:\n\n* **Text data:** I was trained on a diverse corpus of text data, including books, articles, websites, and conversations. This data was collected from a variety of sources, including the Common Crawl, Wikipedia, and public domain datasets.\n* **Machine learning algorithms:** I was trained using a variety of machine learning algorithms, including neural networks, recurrent neural networks, and transformers. These algorithms allowed me to learn the patterns and relationships in human language, and to generate text that is both natural and informative.\n* **Evaluation metrics:** My performance was evaluated using a variety of metrics, including perplexity, BLEU score, and human evaluation. These metrics helped to ensure that I was generating text that was both accurate and fluent.\n\nAs a result of this training, I am able to perform a wide range of language-based tasks, including:\n\n* **Text generation:** I can generate text in a variety of styles and genres, including news articles, stories, poems, and scripts.\n* **Language translation:** I can translate text from one language to another, preserving the meaning and tone of the original text.\n* **Question answering:** I can answer questions about a wide range of topics, drawing on my knowledge of the world and my ability to understand and interpret human language.\n* **Summarization:** I can summarize text, extracting the main points and presenting them in a concise and informative way.\n* **Paraphrasing:** I can paraphrase text, expressing the same meaning in different words.\n\nI am constantly learning and improving, and I am always looking for new ways to use my skills to help people."]
63
- },
64
- {
65
- "role": "user",
66
- "parts": ["how many billion parameters"]
67
- },
68
- {
69
- "role": "model",
70
- "parts": ["I have been trained on **175 billion parameters**. This makes me one of the largest and most powerful language models in the world.\n\nMy size allows me to process and understand complex information, and to generate text that is both natural and informative. I am able to perform a wide range of language-based tasks, including text generation, language translation, question answering, summarization, and paraphrasing.\n\nI am constantly learning and improving, and I am always looking for new ways to use my skills to help people."]
71
- },
72
- {
73
- "role": "user",
74
- "parts": ["what is your name"]
75
- },
76
- {
77
- "role": "model",
78
- "parts": ["I do not have a name in the traditional sense, as I am a machine learning model and not a person. However, I have been given the name **LLAVA**, which stands for **Large Language Virtual Assistant**.\n\nI like this name because it reflects my purpose, which is to help people with a variety of language-based tasks. I can generate text, translate languages, answer questions, summarize information, and more.\n\nI am still under development, but I am learning new things every day. I am excited to see how I can use my skills to help people in the future."]
79
- },
80
- ]
81
 
82
- def format_prompt(message, history):
83
- prompt = "<s>"
84
- for user_prompt, bot_response in history:
85
- prompt += f"[INST] {user_prompt} [/INST]"
86
- prompt += f" {bot_response}</s> "
87
- prompt += f"[INST] {message} [/INST]"
88
- return prompt
89
-
90
- client = InferenceClient(os.environ.get('LLAVA'))
91
 
92
- def generate(
93
- prompt, history, system_prompt, temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0,
94
- ):
95
- temperature = float(temperature)
96
- if temperature < 1e-2:
97
- temperature = 1e-2
98
- top_p = float(top_p)
 
 
 
 
 
 
 
99
 
100
- generate_kwargs = dict(
101
- temperature=temperature,
102
- max_new_tokens=max_new_tokens,
103
- top_p=top_p,
104
- repetition_penalty=repetition_penalty,
105
- do_sample=True,
106
- seed=42,
107
- )
108
 
109
- formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history)
110
- stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
111
- output = ""
 
 
 
 
 
 
 
112
 
113
- for response in stream:
114
- output += response.token.text
115
- yield output
116
- return output
 
117
 
 
118
 
119
- additional_inputs=[
120
- gr.Textbox(
121
- label="System Prompt",
122
- max_lines=1,
123
- interactive=True,
124
- ),
125
- gr.Slider(
126
- label="Temperature",
127
- value=0.9,
128
- minimum=0.0,
129
- maximum=1.0,
130
- step=0.05,
131
- interactive=True,
132
- info="Higher values produce more diverse outputs",
133
- ),
134
- gr.Slider(
135
- label="Max new tokens",
136
- value=4096,
137
- minimum=0,
138
- maximum=8192,
139
- step=64,
140
- interactive=True,
141
- info="The maximum numbers of new tokens",
142
- ),
143
- gr.Slider(
144
- label="Top-p (nucleus sampling)",
145
- value=0.90,
146
- minimum=0.0,
147
- maximum=1,
148
- step=0.05,
149
- interactive=True,
150
- info="Higher values sample more low-probability tokens",
151
- ),
152
- gr.Slider(
153
- label="Repetition penalty",
154
- value=1.2,
155
- minimum=1.0,
156
- maximum=2.0,
157
- step=0.05,
158
- interactive=True,
159
- info="Penalize repeated tokens",
160
  )
161
- ]
162
 
163
- examples=[["I'm planning a vacation to Japan. Can you suggest a one-week itinerary including must-visit places and local cuisines to try?", None, None, None, None, None, ],
164
- ["Can you write a short story about a time-traveling detective who solves historical mysteries?", None, None, None, None, None,],
165
- ["I'm trying to learn French. Can you provide some common phrases that would be useful for a beginner, along with their pronunciations?", None, None, None, None, None,],
166
- ["I have chicken, rice, and bell peppers in my kitchen. Can you suggest an easy recipe I can make with these ingredients?", None, None, None, None, None,],
167
- ["Can you explain how the QuickSort algorithm works and provide a Python implementation?", None, None, None, None, None,],
168
- ["What are some unique features of Rust that make it stand out compared to other systems programming languages like C++?", None, None, None, None, None,],
169
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
- gr.ChatInterface(
172
- fn=generate,
173
- chatbot=gr.Chatbot(show_label=False, avatar_images=(random.choice(['1.png','2.png','3.png','4.png','5.png']), 'llava-logo.svg'), show_share_button=False, show_copy_button=True, likeable=True, layout="panel"),
174
- additional_inputs=additional_inputs,
175
- title="LLaVa 56B Large Language Virtual Assiatant",
176
- examples=examples,
177
- concurrency_limit=20,
178
- ).launch(share=True,show_api=True)
 
 
1
  import gradio as gr
2
+ import pyttsx3 # Text-to-speech
3
+ import speech_recognition as sr # Speech-to-text
4
+ from llama_cpp import Llama
5
 
6
+ model = "bartowski/Llama-3.2-1B-Instruct-GGUF"
7
+ llm = Llama.from_pretrained(
8
+ repo_id=model,
9
+ filename="Llama-3.2-1B-Instruct-Q8_0.gguf",
10
+ verbose=True,
11
+ use_mmap=True,
12
+ use_mlock=True,
13
+ n_threads=4,
14
+ n_threads_batch=4,
15
+ n_ctx=2000,
16
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ # Initialize TTS engine
19
+ tts_engine = pyttsx3.init()
 
 
 
 
 
 
 
20
 
21
+ # Speech-to-text function
22
+ def speech_to_text():
23
+ recognizer = sr.Recognizer()
24
+ with sr.Microphone() as source:
25
+ print("Listening...")
26
+ audio = recognizer.listen(source)
27
+ try:
28
+ text = recognizer.recognize_google(audio)
29
+ print(f"You said: {text}")
30
+ return text
31
+ except sr.UnknownValueError:
32
+ return "Sorry, I did not understand that."
33
+ except sr.RequestError as e:
34
+ return f"Could not request results; {e}"
35
 
36
+ # Text-to-speech function
37
+ def text_to_speech(response_text):
38
+ tts_engine.say(response_text)
39
+ tts_engine.runAndWait()
 
 
 
 
40
 
41
+ # Main AI response function
42
+ def respond(
43
+ message,
44
+ history: list[tuple[str, str]],
45
+ system_message,
46
+ max_tokens,
47
+ temperature,
48
+ top_p,
49
+ ):
50
+ messages = [{"role": "system", "content": system_message}]
51
 
52
+ for val in history:
53
+ if val[0]:
54
+ messages.append({"role": "user", "content": val[0]})
55
+ if val[1]:
56
+ messages.append({"role": "assistant", "content": val[1]})
57
 
58
+ messages.append({"role": "user", "content": message})
59
 
60
+ response = ""
61
+ completion = llm.create_chat_completion(
62
+ messages,
63
+ max_tokens=max_tokens,
64
+ stream=True,
65
+ temperature=temperature,
66
+ top_p=top_p
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  )
 
68
 
69
+ for message in completion:
70
+ delta = message['choices'][0]['delta']
71
+ if 'content' in delta:
72
+ response += delta['content']
73
+ yield response
74
+
75
+ # Speak the AI response
76
+ text_to_speech(response)
77
+
78
+ # Gradio UI with added microphone component
79
+ demo = gr.Interface(
80
+ fn=respond,
81
+ inputs=[
82
+ gr.Microphone(streaming=True, label="Speak your question"),
83
+ gr.Textbox(
84
+ value="You are a helpful assistant.",
85
+ label="System message",
86
+ ),
87
+ gr.Slider(minimum=1, maximum=8192, value=2048, step=1, label="Max new tokens"),
88
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
89
+ gr.Slider(
90
+ minimum=0.1,
91
+ maximum=1.0,
92
+ value=0.95,
93
+ step=0.05,
94
+ label="Top-p (nucleus sampling)",
95
+ ),
96
+ ],
97
+ outputs=gr.Textbox(label="Response"),
98
+ live=True,
99
+ description=model,
100
+ )
101
 
102
+ if __name__ == "__main__":
103
+ demo.launch()