I want to write a python program with gradio that can let the LLM generate excel file…
- User
I want to write a python program with gradio that can let the LLM generate excel file with the process as follow:
- LLM will generate the csv format text as user required
- The program will detect the LLM generated output, then convert to excel format
- Have a convert to excel button that can let the user to choose to convert the llm output to excel file if he want
My program: " import os import time import pandas as pd import re from io import StringIO import torch from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig import gradio as gr from threading import Thread from PyPDF2 import PdfReader # Import PyPDF2 for PDF text extraction
MODEL_PATH = r"C:\Users\shermanhonsf\Desktop\Python\llama_develop\model\Llama3.1-8B-Instruct-HF-Model" # Your model path
TITLE = """ Chat with Llama 3.2 1B """
PLACEHOLDER = """ Hi, I'm Llama. Ask me anything or upload a PDF to chat about its content. """
CSS = """ .duplicate-button { margin: auto !important; color: white !important; background: black !important; border-radius: 100vh !important; } h3 { text-align: center; } """
Set the device to "cuda" if you have a compatible GPU, otherwise "cpu"
device = "cuda" if torch.cuda.is_available() else "cpu"
Configure quantization if needed (optional)
quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4" )
Load the tokenizer and model from the local directory
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH) model = AutoModelForCausalLM.from_pretrained( MODEL_PATH, torch_dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config )
Move the model to the appropriate device
model.to(device)
def extract_pdf_text(pdf_path): """Extract all text from a PDF file.""" 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}"
Function to extract CSV data from LLM output
def extract_csv_data(llm_output): # Define start and end markers for the CSV content start_marker = "#START_CSV" end_marker = "#END_CSV"
code# Locate the markers in the LLM output start_index = llm_output.find(start_marker) end_index = llm_output.find(end_marker) if start_index == -1 or end_index == -1: print("CSV markers not found in the output.") return None # Extract the CSV content between the markers csv_content = llm_output[start_index + len(start_marker):end_index].strip() return csv_content - Assistant