Can you fix this code for me? I'm not sure what's wrong with it.

import sys
import os
import subprocess
import webbrowser
import json
import html
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QTextEdit,
    QLineEdit, QPushButton, QMessageBox
)
from PyQt5.QtCore import Qt, QObject, QThread, pyqtSignal
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# Set the offload directory
offload_dir = "F:\\offload\\"
os.makedirs(offload_dir, exist_ok=True)

# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-7b")

# Load model with offloading to CPU or disk using accelerate
model = AutoModelForCausalLM.from_pretrained(
    "tiiuae/falcon-7b",
    device_map="auto",  # Automatically place layers on GPU/CPU
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    offload_folder=offload_dir  # Enable offloading to the specified directory
)

print("Model loaded successfully!")

class Worker(QObject):
    finished = pyqtSignal(str)
    error = pyqtSignal(str)
    
    def __init__(self, model, tokenizer, context, user_input):
        super().__init__()
        self.model = model
        self.tokenizer = tokenizer
        self.context = context
        self.user_input = user_input

    def run(self):
        try:
            print("Starting to generate response...")  # Debugging
            prompt = self.context + f"You: {self.user_input}\nAssistant:"
            print(f"Prompt: {prompt}")  # Debugging
        
            inputs = self.tokenizer(prompt, return_tensors="pt").to(self.model.device)
            print("Inputs tokenized.")  # Debugging
        
            outputs = self.model.generate(
                **inputs,
                max_new_tokens=50,  # Reducing token count
                temperature=0.7,
                top_p=0.9,
                do_sample=True,
                eos_token_id=self.tokenizer.eos_token_id
            )
        
            response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
            print(f"Raw response: {response}")  # Debugging
        
            response = response[len(prompt):].strip()
            print(f"Assistant response: {response}")  # Debugging
        
            # Emit the response
            self.finished.emit(response)
        
        except Exception as e:
            print(f"Error during generation: {e}")
            self.error.emit(f"Error during generation: {e}")


class ChatbotGUI(QWidget):
    def __init__(self):
        super().__init__()
        self.context = ""
        self.init_llm()
        self.init_ui()
        self.load_context()

    def init_llm(self):
        try:
            # Replace 'tiiuae/falcon-7b' with your model path or name
            self.tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-7b", clean_up_tokenization_spaces=True)
            self.model = AutoModelForCausalLM.from_pretrained(
                "tiiuae/falcon-7b",
                device_map="auto",
                torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
                low_cpu_mem_usage=True
            )
            print("Model loaded successfully.")
        except Exception as e:
            QMessageBox.critical(self, "Model Loading Error", f"Failed to load the model: {e}")
            sys.exit(1)

    def init_ui(self):
        self.setWindowTitle('Local AI Assistant')
        self.setGeometry(100, 100, 600, 800)
        
        # Apply stylesheet for professional look
        self.setStyleSheet("""
            QWidget {
                background-color: #2e2e2e;
                color: #ffffff;
                font-family: Arial;
                font-size: 14px;
            }
            QLineEdit {
                padding: 10px;
                border: 2px solid #555;
                border-radius: 5px;
                background-color: #3e3e3e;
                color: #fff;
            }
            QPushButton {
                padding: 10px;
                background-color: #555;
                border: none;
                border-radius: 5px;
                color: #fff;
            }
            QPushButton:hover {
                background-color: #666;
            }
            QTextEdit {
                background-color: #1e1e1e;
                border: 2px solid #555;
                border-radius: 5px;
                padding: 10px;
                color: #fff;
            }
        """)

        layout = QVBoxLayout()

        # Chat history display
        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        layout.addWidget(self.chat_display)

        # Input field
        self.input_field = QLineEdit()
        self.input_field.setPlaceholderText('Type your message here...')
        self.input_field.returnPressed.connect(self.handle_send)  # Connect Enter key
        layout.addWidget(self.input_field)

        # Send button
        self.send_button = QPushButton('Send')
        self.send_button.clicked.connect(self.handle_send)
        layout.addWidget(self.send_button)

        self.setLayout(layout)

    def handle_send(self):
        user_input = self.input_field.text().strip()
        if user_input:
            self.chat_display.append(f"<b>You:</b> {self.escape_html(user_input)}")
            self.input_field.clear()
            self.chat_display.append(f"<b>Assistant:</b> Generating response...")
            self.generate_response(user_input)

    def generate_response(self, user_input):
        # Create a QThread
        self.thread = QThread()
        # Create a worker object
        self.worker = Worker(self.model, self.tokenizer, self.context, user_input)
        # Move the worker to the thread
        self.worker.moveToThread(self.thread)
        # Connect signals and slots
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.handle_response)
        self.worker.error.connect(self.handle_error)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        # Start the thread
        self.thread.start()

    def handle_response(self, response):
        self.chat_display.append(f"<b>Assistant:</b> {self.escape_html(response)}")
        self.context += f"You: {self.worker.user_input}\n"
        self.context += f"Assistant: {response}\n"

    def handle_error(self, error_message):
        self.chat_display.append(f"<b>Assistant:</b> Error: {self.escape_html(error_message)}")
        self.context += f"Assistant: Error: {error_message}\n"

    def open_file(self, file_path):
        try:
            if os.path.exists(file_path):
                if sys.platform.startswith('darwin'):
                    subprocess.call(('open', file_path))
                elif os.name == 'nt':
                    os.startfile(file_path)
                elif os.name == 'posix':
                    subprocess.call(('xdg-open', file_path))
                return f"Opened {file_path}."
            else:
                return "File does not exist."
        except Exception as e:
            return f"Error opening file: {e}"

    def execute_program(self, program_path):
        try:
            if os.path.exists(program_path):
                subprocess.Popen([program_path])
                return f"Executed {program_path}."
            else:
                return "Program does not exist."
        except Exception as e:
            return f"Error executing program: {e}"

    def open_website(self, url):
        try:
            if not url.startswith(('http://', 'https://')):
                url = 'http://' + url
            webbrowser.open(url)
            return f"Opened {url} in your default browser."
        except Exception as e:
            return f"Error opening website: {e}"

    def save_context(self):
        try:
            with open('context.json', 'w') as f:
                json.dump(self.context, f)
        except Exception as e:
            print(f"Error saving context: {e}")

    def load_context(self):
        try:
            if os.path.exists('context.json'):
                with open('context.json', 'r') as f:
                    self.context = json.load(f)
                    self.chat_display.append("<i>Assistant:</i> Context loaded.")
        except Exception as e:
            print(f"Error loading context: {e}")

    def closeEvent(self, event):
        self.save_context()
        event.accept()

    def escape_html(self, text):
        """Escape HTML to prevent formatting issues."""
        return html.escape(text).replace('\n', '<br>')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = ChatbotGUI()
    gui.show()
    sys.exit(app.exec_())