Spaces:
Runtime error
Runtime error
VenkateshRoshan
commited on
Commit
·
262548b
1
Parent(s):
771d614
requirements updated
Browse files
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=
|
| 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 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
def download_and_load_model(self):
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 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 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 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 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
|
| 175 |
-
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
if __name__ == "__main__":
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 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
|