contenteaseAI commited on
Commit
1c38929
·
verified ·
1 Parent(s): 046d810

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -178
app.py CHANGED
@@ -1,179 +1,179 @@
1
- import spaces
2
- import json
3
- import subprocess
4
- from llama_cpp import Llama
5
- from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
6
- from llama_cpp_agent.providers import LlamaCppPythonProvider
7
- import gradio as gr
8
- from huggingface_hub import hf_hub_download
9
- import logging
10
- import time
11
-
12
- logging.basicConfig(level=logging.INFO)
13
- logger = logging.getLogger(__name__)
14
-
15
- repo_id = "QuantFactory/Meta-Llama-3-8B-Instruct-GGUF"
16
- filename = "Meta-Llama-3-8B-Instruct.Q8_0.gguf"
17
-
18
- def chunk_text(text, chunk_size=5000):
19
- """
20
- Splits the input text into chunks of specified size.
21
-
22
- Args:
23
- text (str): The input text to be chunked.
24
- chunk_size (int): The size of each chunk in tokens.
25
-
26
- Returns:
27
- list: A list of text chunks.
28
- """
29
- words = text.split()
30
- chunks = [' '.join(words[i:i + chunk_size]) for i in range(0, len(words), chunk_size)]
31
- return chunks
32
-
33
-
34
- try:
35
- start_time = time.time()
36
- logger.info("Downloading Model....")
37
-
38
- hf_hub_download(
39
- repo_id = repo_id ,
40
- filename = filename,
41
- local_dir="./model"
42
- )
43
-
44
- end_time = time.time()
45
- logger.info(f"Download complete. Time taken : {end_time - start_time} seconds.")
46
-
47
- except Exception as e:
48
- logger.error(f"Unable to download Model : {e}")
49
- raise
50
-
51
- llm = None
52
-
53
- @spaces.GPU(duration=120)
54
- def respond(message, history, max_tokens, temperature):
55
- """
56
- Generate a streaming response using the llama3-8b model with chunking.
57
-
58
- Args:
59
- message (str): The input message.
60
- history (list): The conversation history used by ChatInterface. - Not used.
61
- temperature (float): The temperature for generating the response.
62
- max_new_tokens (int): The maximum number of new tokens to generate.
63
-
64
- Returns:
65
- str: The generated response.
66
- """
67
-
68
- chat_template = MessagesFormatterType.LLAMA_3
69
-
70
- global llm
71
-
72
- start_time = time.time()
73
- logging.info("Loading Model...")
74
-
75
- if llm is None:
76
- model = Llama(
77
- model_path=f"models/{filename}",
78
- flash_attn=True,
79
- n_gpu_layers=-1,
80
- n_batch=1,
81
- n_ctx=8192,
82
- last_n_tokens = 0
83
- )
84
- llm = model
85
-
86
- end_time = time.time()
87
- logger.info(f"Model Loaded. Time taken : {end_time - start_time} seconds.")
88
-
89
- start_time = time.time()
90
- logger.info("Loading Provider and Agent for the Llama Model....")
91
-
92
- provider = LlamaCppPythonProvider(llm)
93
-
94
- SYS_PROMPT ="""
95
- Extract all relevant keywords and add quantity from the following text and format the result in nested JSON, ignoring personal details and focusing only on the scope of work as shown in the example:
96
- Good JSON example: {'lobby': {'frcm': {'replace': {'carpet': 1, 'carpet_pad': 1, 'base': 1, 'window_treatments': 1, 'artwork_and_decorative_accessories': 1, 'portable_lighting': 1, 'upholstered_furniture_and_decorative_pillows': 1, 'millwork': 1} } } }
97
- Bad JSON example: {'lobby': { 'frcm': { 'replace': [ 'carpet', 'carpet_pad', 'base', 'window_treatments', 'artwork_and_decorative_accessories', 'portable_lighting', 'upholstered_furniture_and_decorative_pillows', 'millwork'] } } }
98
- Make sure to fetch details from the provided text and ignore unnecessary information. The response should be in JSON format only, without any additional comments.
99
- """
100
-
101
- agent = LlamaCppAgent(
102
- provider,
103
- system_prompt=SYS_PROMPT,
104
- predefined_messages_formatter_type=chat_template,
105
- debug_output=True
106
- )
107
-
108
- settings = provider.get_provider_default_settings()
109
- settings.temperature = temperature
110
- settings.max_tokens = max_tokens
111
- settings.stream = True
112
-
113
- end_time = time.time()
114
- logger.info(f"Provider settings updated. Prompt Loaded.Time taken : {end_time - start_time} seconds.")
115
-
116
- chunks = chunk_text(message)
117
-
118
- start_time = time.time()
119
- logger.info("Generating responses...")
120
- for chunk in chunks:
121
- response = agent.get_chat_response(
122
- chunk,
123
- llm_sampling_settings=settings,
124
- returns_streaming_generator = False, #generate streamer
125
- print_output = False
126
- )
127
- logger.info(f"Responses generated. Time taken : {time.time() - start_time} seconds.")
128
-
129
- return response
130
-
131
- DESCRIPTION = '''
132
- <div>
133
- <h1 style="text-align: center;">ContenteaseAI custom trained model</h1>
134
- </div>
135
- '''
136
-
137
- LICENSE = """
138
- <p/>
139
- ---
140
- For more information, visit our [website](https://contentease.ai).
141
- """
142
-
143
- PLACEHOLDER = """
144
- <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
145
- <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">ContenteaseAI Custom AI trained model</h1>
146
- <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Enter the text extracted from the PDF:</p>
147
- </div>
148
- """
149
-
150
- css = """
151
- h1 {
152
- text-align: center;
153
- display: block;
154
- }
155
- """
156
- # Gradio block
157
- chatbot = gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
158
-
159
- with gr.Blocks(fill_height=True, css=css) as demo:
160
- gr.Markdown(DESCRIPTION)
161
-
162
- gr.ChatInterface(
163
- fn=respond,
164
- chatbot=chatbot,
165
- fill_height=True,
166
- additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
167
- additional_inputs=[
168
- gr.Slider(minimum=0, maximum=1, step=0.1, value=0.90, label="Temperature", render=False),
169
- gr.Slider(minimum=128, maximum=2000, step=1, value=1500, label="Max new tokens", render=False),
170
- ]
171
- )
172
-
173
- gr.Markdown(LICENSE)
174
-
175
- if __name__ == "__main__":
176
- try:
177
- demo.launch(show_error=True, debug = True)
178
- except Exception as e:
179
  logger.error(f"Error launching Gradio demo: {e}")
 
1
+ import spaces
2
+ import json
3
+ import subprocess
4
+ from llama_cpp import Llama
5
+ from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
6
+ from llama_cpp_agent.providers import LlamaCppPythonProvider
7
+ import gradio as gr
8
+ from huggingface_hub import hf_hub_download
9
+ import logging
10
+ import time
11
+
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ repo_id = "QuantFactory/Meta-Llama-3-8B-Instruct-GGUF"
16
+ filename = "Meta-Llama-3-8B-Instruct.Q8_0.gguf"
17
+
18
+ def chunk_text(text, chunk_size=5000):
19
+ """
20
+ Splits the input text into chunks of specified size.
21
+
22
+ Args:
23
+ text (str): The input text to be chunked.
24
+ chunk_size (int): The size of each chunk in tokens.
25
+
26
+ Returns:
27
+ list: A list of text chunks.
28
+ """
29
+ words = text.split()
30
+ chunks = [' '.join(words[i:i + chunk_size]) for i in range(0, len(words), chunk_size)]
31
+ return chunks
32
+
33
+
34
+ try:
35
+ start_time = time.time()
36
+ logger.info("Downloading Model....")
37
+
38
+ hf_hub_download(
39
+ repo_id = repo_id ,
40
+ filename = filename,
41
+ local_dir="./model"
42
+ )
43
+
44
+ end_time = time.time()
45
+ logger.info(f"Download complete. Time taken : {end_time - start_time} seconds.")
46
+
47
+ except Exception as e:
48
+ logger.error(f"Unable to download Model : {e}")
49
+ raise
50
+
51
+ llm = None
52
+
53
+ @spaces.GPU(duration=120)
54
+ def respond(message, history, max_tokens, temperature):
55
+ """
56
+ Generate a streaming response using the llama3-8b model with chunking.
57
+
58
+ Args:
59
+ message (str): The input message.
60
+ history (list): The conversation history used by ChatInterface. - Not used.
61
+ temperature (float): The temperature for generating the response.
62
+ max_new_tokens (int): The maximum number of new tokens to generate.
63
+
64
+ Returns:
65
+ str: The generated response.
66
+ """
67
+
68
+ chat_template = MessagesFormatterType.LLAMA_3
69
+
70
+ global llm
71
+
72
+ start_time = time.time()
73
+ logging.info("Loading Model...")
74
+
75
+ if llm is None:
76
+ model = Llama(
77
+ model_path=f"model/{filename}",
78
+ flash_attn=True,
79
+ n_gpu_layers=-1,
80
+ n_batch=1,
81
+ n_ctx=8192,
82
+ last_n_tokens = 0
83
+ )
84
+ llm = model
85
+
86
+ end_time = time.time()
87
+ logger.info(f"Model Loaded. Time taken : {end_time - start_time} seconds.")
88
+
89
+ start_time = time.time()
90
+ logger.info("Loading Provider and Agent for the Llama Model....")
91
+
92
+ provider = LlamaCppPythonProvider(llm)
93
+
94
+ SYS_PROMPT ="""
95
+ Extract all relevant keywords and add quantity from the following text and format the result in nested JSON, ignoring personal details and focusing only on the scope of work as shown in the example:
96
+ Good JSON example: {'lobby': {'frcm': {'replace': {'carpet': 1, 'carpet_pad': 1, 'base': 1, 'window_treatments': 1, 'artwork_and_decorative_accessories': 1, 'portable_lighting': 1, 'upholstered_furniture_and_decorative_pillows': 1, 'millwork': 1} } } }
97
+ Bad JSON example: {'lobby': { 'frcm': { 'replace': [ 'carpet', 'carpet_pad', 'base', 'window_treatments', 'artwork_and_decorative_accessories', 'portable_lighting', 'upholstered_furniture_and_decorative_pillows', 'millwork'] } } }
98
+ Make sure to fetch details from the provided text and ignore unnecessary information. The response should be in JSON format only, without any additional comments.
99
+ """
100
+
101
+ agent = LlamaCppAgent(
102
+ provider,
103
+ system_prompt=SYS_PROMPT,
104
+ predefined_messages_formatter_type=chat_template,
105
+ debug_output=True
106
+ )
107
+
108
+ settings = provider.get_provider_default_settings()
109
+ settings.temperature = temperature
110
+ settings.max_tokens = max_tokens
111
+ settings.stream = True
112
+
113
+ end_time = time.time()
114
+ logger.info(f"Provider settings updated. Prompt Loaded.Time taken : {end_time - start_time} seconds.")
115
+
116
+ chunks = chunk_text(message)
117
+
118
+ start_time = time.time()
119
+ logger.info("Generating responses...")
120
+ for chunk in chunks:
121
+ response = agent.get_chat_response(
122
+ chunk,
123
+ llm_sampling_settings=settings,
124
+ returns_streaming_generator = False, #generate streamer
125
+ print_output = False
126
+ )
127
+ logger.info(f"Responses generated. Time taken : {time.time() - start_time} seconds.")
128
+
129
+ return response
130
+
131
+ DESCRIPTION = '''
132
+ <div>
133
+ <h1 style="text-align: center;">ContenteaseAI custom trained model</h1>
134
+ </div>
135
+ '''
136
+
137
+ LICENSE = """
138
+ <p/>
139
+ ---
140
+ For more information, visit our [website](https://contentease.ai).
141
+ """
142
+
143
+ PLACEHOLDER = """
144
+ <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
145
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">ContenteaseAI Custom AI trained model</h1>
146
+ <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Enter the text extracted from the PDF:</p>
147
+ </div>
148
+ """
149
+
150
+ css = """
151
+ h1 {
152
+ text-align: center;
153
+ display: block;
154
+ }
155
+ """
156
+ # Gradio block
157
+ chatbot = gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
158
+
159
+ with gr.Blocks(fill_height=True, css=css) as demo:
160
+ gr.Markdown(DESCRIPTION)
161
+
162
+ gr.ChatInterface(
163
+ fn=respond,
164
+ chatbot=chatbot,
165
+ fill_height=True,
166
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
167
+ additional_inputs=[
168
+ gr.Slider(minimum=0, maximum=1, step=0.1, value=0.90, label="Temperature", render=False),
169
+ gr.Slider(minimum=128, maximum=2000, step=1, value=1500, label="Max new tokens", render=False),
170
+ ]
171
+ )
172
+
173
+ gr.Markdown(LICENSE)
174
+
175
+ if __name__ == "__main__":
176
+ try:
177
+ demo.launch(show_error=True, debug = True)
178
+ except Exception as e:
179
  logger.error(f"Error launching Gradio demo: {e}")