Help me to fix the error of the following code: " import os import time import torch…
- User
Help me to fix the error of the following code: " import os import time import torch from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig import gradio as gr from threading import Thread from PyPDF2 import PdfReader import pandas as pd # For Excel generation
MODEL_PATH = r"C:\Users\shermanhonsf\Desktop\Python\llama_develop\model\Llama3.2-1B-Instruct-HF-Model"
TITLE = """ Chat with Llama 3.2 1B """
PLACEHOLDER = """ Hi, I'm Llama. Ask me anything or upload a PDF to chat about its content. You can also ask me to generate an Excel file. """
CSS = """ .duplicate-button { margin: auto !important; color: white !important; background: black !important; border-radius: 100vh !important; } h3 { text-align: center; } """
device = "cuda" if torch.cuda.is_available() else "cpu"
quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4" )
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH) model = AutoModelForCausalLM.from_pretrained( MODEL_PATH, torch_dtype=torch.bfloat16, device_map="auto", # quantization_config=quantization_config )
model.to(device)
def extract_pdf_text(pdf_path): try: reader = PdfReader(pdf_path) text = "" for page in reader.pages: text += page.extract_text() return text except Exception as e: return f"Error reading PDF: {e}"
def process_llm_output_to_excel(llm_output): """ Convert the LLM-generated text into a structured DataFrame for Excel. Assumes the LLM output is a numbered list or similar structured text. """ try: # Split the LLM output into lines lines = llm_output.strip().split("\n") data = []
codefor line in lines: # Extract step number and description parts = line.split(".", 1) if len(parts) == 2: step_number, description = parts[0].strip(), parts[1].strip() data.append({"Step Number": step_number, "Description": description}) # Convert to DataFrame df = pd.DataFrame(data) return df except Exception as e: print(f"Error processing LLM output to Excel: {e}") return Nonedef save_excel(df, file_name="generated_data.xlsx"): """Save a DataFrame to an Excel file.""" excel_file_path = file_name df.to_excel(excel_file_path, index=False) return excel_file_path
def stream_chat(message: str, history: list, system_prompt: str = 'You are a helpful assistant', temperature: float = 0.8, max_new_tokens: int = 1024, top_p: float = 1.0, top_k: int = 20, penalty: float = 1.2, pdf_text: str = ""): print(f'message: {message}') print(f'history: {history}') print(f'system_prompt: {system_prompt}') print(f'temperature: {temperature}') print(f'max_new_tokens: {max_new_tokens}') print(f'top_p: {top_p}') print(f'top_k: {top_k}') print(f'penalty: {penalty}') print(f'Message: {message}') print(f'History: {history}') print(f'PDF Text: {pdf_text}')
- Assistant