VenkateshRoshan commited on
Commit
262548b
·
1 Parent(s): 771d614

requirements updated

Browse files
Files changed (1) hide show
  1. app_hf.py +153 -121
app_hf.py CHANGED
@@ -8,13 +8,14 @@ import tarfile
8
  from typing import List, Tuple
9
  import boto3
10
  import logging
 
11
 
12
  # Set up logging
13
  logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
15
 
16
  class CustomerSupportBot:
17
- def __init__(self, model_path="models/customer_support_gpt"):
18
  """
19
  Initialize the customer support bot with the fine-tuned model.
20
 
@@ -22,40 +23,60 @@ class CustomerSupportBot:
22
  model_path (str): Path to the saved model and tokenizer
23
  """
24
  self.process = psutil.Process(os.getpid())
25
- self.model_path = model_path
26
- self.model_file_path = os.path.join(self.model_path, "model.tar.gz")
 
 
 
 
 
 
 
 
27
  self.s3 = boto3.client("s3")
28
  self.model_key = "models/model.tar.gz"
29
  self.bucket_name = "customer-support-gpt"
30
 
31
  # Download and load the model
32
- self.download_and_load_model()
 
 
 
 
33
 
34
  def download_and_load_model(self):
35
- # Check if the model directory exists
36
- if not os.path.exists(self.model_path):
37
- os.makedirs(self.model_path)
38
-
39
- # Download model.tar.gz from S3 if not already downloaded
40
- if not os.path.exists(self.model_file_path):
41
- print("Downloading model from S3...")
42
- self.s3.download_file(self.bucket_name, self.model_key, self.model_file_path)
43
- print("Download complete. Extracting model files...")
44
-
45
- # Extract the model files
46
- with tarfile.open(self.model_file_path, "r:gz") as tar:
47
- tar.extractall(self.model_path)
48
-
49
- # Load the model and tokenizer from extracted files
50
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
51
- self.model = AutoModelForCausalLM.from_pretrained(self.model_path)
52
- print("Model and tokenizer loaded successfully.")
53
-
54
- # Move model to GPU if available
55
- self.device = "cpu" #"cuda" if torch.cuda.is_available() else "cpu"
56
- self.model = self.model.to(self.device)
57
-
58
- print(f'Model loaded on device: {self.device}')
 
 
 
 
 
 
 
 
59
 
60
  def generate_response(self, message: str, max_length=100, temperature=0.7) -> str:
61
  try:
@@ -94,107 +115,118 @@ class CustomerSupportBot:
94
 
95
 
96
  def create_chat_interface():
97
- bot = CustomerSupportBot(model_path="/models")
98
-
99
- def predict(message: str, history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
100
- if not message:
101
- return "", history
102
-
103
- bot_response = bot.generate_response(message)
104
-
105
- # Log resource usage
106
- usage = bot.monitor_resources()
107
- print("Resource Usage:", usage)
108
 
109
- history.append((message, bot_response))
110
- return "", history
 
 
 
 
 
 
 
 
 
 
111
 
112
- # Create the Gradio interface with custom CSS
113
- with gr.Blocks(css="""
114
- .message-box {
115
- margin-bottom: 10px;
116
- }
117
- .button-row {
118
- display: flex;
119
- gap: 10px;
120
- margin-top: 10px;
121
- }
122
- """) as interface:
123
- gr.Markdown("# Customer Support Chatbot")
124
- gr.Markdown("Welcome! How can I assist you today?")
125
-
126
- chatbot = gr.Chatbot(
127
- label="Chat History",
128
- height=500,
129
- elem_classes="message-box",
130
- # type="messages"
131
- )
132
-
133
- with gr.Row():
134
- msg = gr.Textbox(
135
- label="Your Message",
136
- placeholder="Type your message here...",
137
- lines=2,
138
- elem_classes="message-box"
139
- )
140
-
141
- with gr.Row(elem_classes="button-row"):
142
- submit = gr.Button("Send Message", variant="primary")
143
- clear = gr.ClearButton([msg, chatbot], value="Clear Chat")
144
-
145
- # Add example queries in a separate row
146
- with gr.Row():
147
- gr.Examples(
148
- examples=[
149
- "How do I reset my password?",
150
- "What are your shipping policies?",
151
- "I want to return a product.",
152
- "How can I track my order?",
153
- "What payment methods do you accept?"
154
- ],
155
- inputs=msg,
156
- label="Example Questions"
157
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
- # Set up event handlers
160
- submit_click = submit.click(
161
- predict,
162
- inputs=[msg, chatbot],
163
- outputs=[msg, chatbot]
164
- )
165
-
166
- msg.submit(
167
- predict,
168
- inputs=[msg, chatbot],
169
- outputs=[msg, chatbot]
170
- )
171
-
172
- # Add keyboard shortcut for submit
173
- msg.change(lambda x: gr.update(interactive=bool(x.strip())), inputs=[msg], outputs=[submit])
174
 
175
- print("Interface created successfully.")
176
 
177
- # call the initial query function
178
- # run a query first how are you and predict the output
179
- print(predict("How are you", []))
180
 
181
- # run a command which checks the resource usage
182
- print(f'Bot Resource Usage : {bot.monitor_resources()}')
183
 
184
- # show full system usage
185
- print(f'CPU Percentage : {psutil.cpu_percent()}')
186
- print(f'RAM Usage : {psutil.virtual_memory()}')
187
- print(f'Swap Memory : {psutil.swap_memory()}')
188
 
189
- return interface
 
 
 
 
190
 
191
  if __name__ == "__main__":
192
- demo = create_chat_interface()
193
- print("Starting Gradio server...")
194
- demo.launch(
195
- share=False,
196
- server_name="0.0.0.0",
197
- server_port=7860, # Changed to 7860 for Gradio
198
- debug=True,
199
- inline=False
200
- )
 
 
 
 
 
8
  from typing import List, Tuple
9
  import boto3
10
  import logging
11
+ from pathlib import Path
12
 
13
  # Set up logging
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
  class CustomerSupportBot:
18
+ def __init__(self, model_path=None):
19
  """
20
  Initialize the customer support bot with the fine-tuned model.
21
 
 
23
  model_path (str): Path to the saved model and tokenizer
24
  """
25
  self.process = psutil.Process(os.getpid())
26
+
27
+ if model_path is None:
28
+ self.model_path = os.path.join(os.path.expanduser("~"), "customer_support_gpt")
29
+ else:
30
+ self.model_path = model_path
31
+
32
+
33
+ self.model_path = Path(self.model_path)
34
+ self.model_file_path = self.model_path / "model.tar.gz"
35
+
36
  self.s3 = boto3.client("s3")
37
  self.model_key = "models/model.tar.gz"
38
  self.bucket_name = "customer-support-gpt"
39
 
40
  # Download and load the model
41
+ try:
42
+ self.download_and_load_model()
43
+ except Exception as e:
44
+ logger.error(f"Failed to initialize model: {str(e)}")
45
+ raise
46
 
47
  def download_and_load_model(self):
48
+ try:
49
+ # Create model directory if it doesn't exist
50
+ self.model_path.mkdir(parents=True, exist_ok=True)
51
+ logger.info(f"Using model directory: {self.model_path}")
52
+
53
+ # Download model from S3 if needed
54
+ if not self.model_file_path.exists():
55
+ logger.info("Downloading model from S3...")
56
+ self.s3.download_file(self.bucket_name, self.model_key, str(self.model_file_path))
57
+ logger.info("Download complete. Extracting model files...")
58
+
59
+ # Extract the model files
60
+ with tarfile.open(self.model_file_path, "r:gz") as tar:
61
+ tar.extractall(str(self.model_path))
62
+
63
+ # Load the model and tokenizer
64
+ logger.info("Loading model and tokenizer...")
65
+ self.tokenizer = AutoTokenizer.from_pretrained(str(self.model_path))
66
+ self.model = AutoModelForCausalLM.from_pretrained(str(self.model_path))
67
+ logger.info("Model and tokenizer loaded successfully.")
68
+
69
+ # Move model to GPU if available
70
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
71
+ self.model = self.model.to(self.device)
72
+ logger.info(f'Model loaded on device: {self.device}')
73
+
74
+ except PermissionError as e:
75
+ logger.error(f"Permission error when accessing {self.model_path}: {str(e)}")
76
+ raise
77
+ except Exception as e:
78
+ logger.error(f"Error in download_and_load_model: {str(e)}")
79
+ raise
80
 
81
  def generate_response(self, message: str, max_length=100, temperature=0.7) -> str:
82
  try:
 
115
 
116
 
117
  def create_chat_interface():
118
+ try:
119
+ # Use a user-accessible directory for the model
120
+ user_model_path = os.path.join(os.path.expanduser("~"), "customer_support_models")
121
+ bot = CustomerSupportBot(model_path=user_model_path)
 
 
 
 
 
 
 
122
 
123
+ def predict(message: str, history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
124
+ if not message:
125
+ return "", history
126
+
127
+ bot_response = bot.generate_response(message)
128
+
129
+ # Log resource usage
130
+ usage = bot.monitor_resources()
131
+ print("Resource Usage:", usage)
132
+
133
+ history.append((message, bot_response))
134
+ return "", history
135
 
136
+ # Create the Gradio interface with custom CSS
137
+ with gr.Blocks(css="""
138
+ .message-box {
139
+ margin-bottom: 10px;
140
+ }
141
+ .button-row {
142
+ display: flex;
143
+ gap: 10px;
144
+ margin-top: 10px;
145
+ }
146
+ """) as interface:
147
+ gr.Markdown("# Customer Support Chatbot")
148
+ gr.Markdown("Welcome! How can I assist you today?")
149
+
150
+ chatbot = gr.Chatbot(
151
+ label="Chat History",
152
+ height=500,
153
+ elem_classes="message-box",
154
+ # type="messages"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  )
156
+
157
+ with gr.Row():
158
+ msg = gr.Textbox(
159
+ label="Your Message",
160
+ placeholder="Type your message here...",
161
+ lines=2,
162
+ elem_classes="message-box"
163
+ )
164
+
165
+ with gr.Row(elem_classes="button-row"):
166
+ submit = gr.Button("Send Message", variant="primary")
167
+ clear = gr.ClearButton([msg, chatbot], value="Clear Chat")
168
+
169
+ # Add example queries in a separate row
170
+ with gr.Row():
171
+ gr.Examples(
172
+ examples=[
173
+ "How do I reset my password?",
174
+ "What are your shipping policies?",
175
+ "I want to return a product.",
176
+ "How can I track my order?",
177
+ "What payment methods do you accept?"
178
+ ],
179
+ inputs=msg,
180
+ label="Example Questions"
181
+ )
182
 
183
+ # Set up event handlers
184
+ submit_click = submit.click(
185
+ predict,
186
+ inputs=[msg, chatbot],
187
+ outputs=[msg, chatbot]
188
+ )
189
+
190
+ msg.submit(
191
+ predict,
192
+ inputs=[msg, chatbot],
193
+ outputs=[msg, chatbot]
194
+ )
195
+
196
+ # Add keyboard shortcut for submit
197
+ msg.change(lambda x: gr.update(interactive=bool(x.strip())), inputs=[msg], outputs=[submit])
198
 
199
+ print("Interface created successfully.")
200
 
201
+ # call the initial query function
202
+ # run a query first how are you and predict the output
203
+ print(predict("How are you", []))
204
 
205
+ # run a command which checks the resource usage
206
+ print(f'Bot Resource Usage : {bot.monitor_resources()}')
207
 
208
+ # show full system usage
209
+ print(f'CPU Percentage : {psutil.cpu_percent()}')
210
+ print(f'RAM Usage : {psutil.virtual_memory()}')
211
+ print(f'Swap Memory : {psutil.swap_memory()}')
212
 
213
+ return interface
214
+
215
+ except Exception as e:
216
+ logger.error(f"Failed to create chat interface: {str(e)}")
217
+ raise
218
 
219
  if __name__ == "__main__":
220
+ try:
221
+ logger.info("Starting customer support bot application...")
222
+ demo = create_chat_interface()
223
+ demo.launch(
224
+ share=False,
225
+ server_name="0.0.0.0",
226
+ server_port=7860,
227
+ debug=True,
228
+ inline=False
229
+ )
230
+ except Exception as e:
231
+ logger.error(f"Application failed to start: {str(e)}")
232
+ raise