import gradio as gr import os import pandas as pd import tempfile import json import logging from dotenv import load_dotenv from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_huggingface import HuggingFaceEndpoint from langchain_core.runnables import RunnablePassthrough, RunnableLambda from langchain.callbacks.base import BaseCallbackHandler from typing import List, Dict, Any, Optional # Set up logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # Load environment variables from .env file load_dotenv() # Get the Hugging Face token from environment variables hf_token = os.getenv("HUGGINGFACE_TOKEN") # Default model parameters MODEL_DEFAULTS = { "max_new_tokens": 256, "temperature": 0.05, "top_p": 0.9, "repetition_penalty": 1.2, "timeout": 30, } # Initialize the LangChain HuggingFace endpoint with a larger model def create_llm(temperature=None, max_tokens=None, timeout=None): """Create LLM with specified parameters or use defaults""" # Use provided values or defaults params = MODEL_DEFAULTS.copy() if temperature is not None: params["temperature"] = float(temperature) if max_tokens is not None: params["max_new_tokens"] = int(max_tokens) if timeout is not None: params["timeout"] = int(timeout) logger.info(f"Creating LLM with parameters: {params}") return HuggingFaceEndpoint( endpoint_url="https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2", huggingfacehub_api_token=hf_token, **params ) # Initialize with default parameters llm = create_llm() # Custom output parser for categories class CategoryOutputParser: """Parser that extracts categories from LLM output""" def __init__(self, valid_categories: List[str]): self.valid_categories = valid_categories def parse(self, text: str) -> List[str]: """Parse the LLM output and extract valid categories.""" # Split output into lines and strip whitespace lines = [line.strip() for line in text.strip().split("\n") if line.strip()] results = [] logger.debug(f"Raw lines from LLM: {lines}") for line in lines: # Check if the model responded with "None" if line.lower() == "none": results.append("No Category") continue # Check for exact category match if line in self.valid_categories: results.append(line) continue # Check for case-insensitive match for category in self.valid_categories: if category.lower() == line.lower(): results.append(category) # Use the correct case break else: # No direct match found # Try to find category in line matched = False for category in self.valid_categories: if category in line: results.append(category) matched = True break # If no match found, use default if not matched and self.valid_categories: logger.warning(f"Could not extract valid category from: '{line}', using default") results.append(self.valid_categories[0]) return results # Custom logging callback handler class LoggingCallbackHandler(BaseCallbackHandler): """Simple handler that just logs LLM inputs and outputs""" def __init__(self): super().__init__() def on_llm_start(self, serialized, prompts, **kwargs): """Log when LLM starts.""" for i, prompt in enumerate(prompts): logger.debug(f"LLM Prompt {i}: {prompt}") def on_llm_end(self, response, **kwargs): """Log when LLM ends.""" logger.debug(f"LLM Response: {response.generations[0][0].text}") # Empty implementations for other required methods def on_llm_error(self, error, **kwargs): pass def on_chain_start(self, serialized, inputs, **kwargs): pass def on_chain_end(self, outputs, **kwargs): pass def on_chain_error(self, error, **kwargs): pass def on_tool_start(self, serialized, input_str, **kwargs): pass def on_tool_end(self, output, **kwargs): pass def on_tool_error(self, error, **kwargs): pass def on_text(self, text, **kwargs): pass def on_retriever_start(self, serialized, query, **kwargs): pass def on_retriever_end(self, documents, **kwargs): pass def on_retriever_error(self, error, **kwargs): pass def on_agent_action(self, action, **kwargs): pass def on_agent_finish(self, finish, **kwargs): pass # Create a single text categorization chain with modern LangChain def create_single_categorization_chain(valid_categories): """Create a chain for single text categorization using modern LangChain""" # Create a comprehensive system prompt system_template = """You are an expert text categorization system that assigns exactly ONE category to each input text. STRICT RULES: 1. You MUST choose one category from the EXACT list provided, OR respond with "None" if no category fits 2. You MUST return ONLY the category name (or "None") with no other text 3. No explanations, no reasoning, no conversation 4. You CANNOT create new categories 5. Only use "None" when text clearly doesn't fit ANY category - if uncertain between categories, choose the most similar one""" # Create a clear human prompt human_template = """AVAILABLE CATEGORIES: {categories} EXAMPLE CATEGORIZATIONS: {examples} TEXT TO CATEGORIZE: "{text}" YOUR RESPONSE (ONLY the category name or "None" if no category fits):""" # Combine into a chat prompt prompt = ChatPromptTemplate.from_messages([ ("system", system_template), ("human", human_template) ]) # Format categories as a bulleted list def format_categories(categories): return "\n".join([f"- {cat}" for cat in categories]) # Create the chain using modern LangChain chain = ( # Input processing { "categories": lambda x: format_categories(valid_categories), "examples": lambda x: x["examples"], "text": lambda x: x["text"] } | prompt # Pass to prompt template | llm # Pass to LLM | StrOutputParser() # Parse the output to string ) return chain, system_template, human_template # Create a batch text categorization chain with modern LangChain def create_batch_categorization_chain(valid_categories): """Create a chain for batch text categorization using modern LangChain""" # Create a comprehensive system prompt system_template = """You are an expert text categorization system that assigns exactly ONE category to each input text. STRICT RULES: 1. You MUST choose one category from the EXACT list provided, OR respond with "None" if no category fits 2. You MUST return ONLY the category names (or "None"), one per line 3. No numbers, no explanations, no reasoning, no conversation 4. Return exactly ONE category per text, in the SAME ORDER as the input 5. You CANNOT create new categories 6. Only use "None" when text clearly doesn't fit ANY category - if uncertain between categories, choose the most similar one""" # Create a clear human prompt human_template = """AVAILABLE CATEGORIES: {categories} EXAMPLE CATEGORIZATIONS: {examples} TEXTS TO CATEGORIZE: {texts} YOUR RESPONSE (ONE category name per line or "None" if no category fits, same order as input):""" # Combine into a chat prompt prompt = ChatPromptTemplate.from_messages([ ("system", system_template), ("human", human_template) ]) # Format categories as a bulleted list def format_categories(categories): return "\n".join([f"- {cat}" for cat in categories]) # Create the chain using modern LangChain chain = ( # Input processing { "categories": lambda x: format_categories(valid_categories), "examples": lambda x: x["examples"], "texts": lambda x: x["texts"] } | prompt # Pass to prompt template | llm # Pass to LLM | StrOutputParser() # Parse the output to string ) return chain, system_template, human_template class CategoryApp: def __init__(self): self.examples = [] self.dataset = None self.dataset_path = None self.input_column = None self.output_column = None self.valid_categories = [] self.last_system_prompt = "" self.last_user_prompt = "" # Model parameters self.model_temperature = MODEL_DEFAULTS["temperature"] self.model_max_tokens = MODEL_DEFAULTS["max_new_tokens"] self.model_timeout = MODEL_DEFAULTS["timeout"] # Enhanced default examples for better categorization (not loaded automatically) self.default_examples = [ {"text": "I absolutely love this product! It's changed my life.", "category": "Positive"}, {"text": "This has been a wonderful experience overall.", "category": "Positive"}, {"text": "The quality exceeded my expectations in every way.", "category": "Positive"}, {"text": "This is awful and doesn't work properly.", "category": "Negative"}, {"text": "Disappointed with the performance and reliability.", "category": "Negative"}, {"text": "Waste of money, I regret purchasing this item.", "category": "Negative"}, {"text": "How do I reset my password?", "category": "Question"}, {"text": "Can you tell me what the return policy is?", "category": "Question"}, {"text": "When will the next version be released?", "category": "Question"}, {"text": "The store is open from 9am to 5pm on weekdays.", "category": "Information"}, {"text": "This product contains 3 grams of sugar per serving.", "category": "Information"}, {"text": "The meeting will be held in Room 302 at 2pm.", "category": "Information"}, {"text": "I need help with setting up my account.", "category": "Support"}, {"text": "My order hasn't arrived yet, can you help track it?", "category": "Support"}, {"text": "The application keeps crashing when I try to save.", "category": "Support"}, {"text": "Colorless green ideas sleep furiously.", "category": "No Category"}, {"text": "XYZ123 qwerty asdfg hjkl zxcvb.", "category": "No Category"}, {"text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "category": "No Category"} ] # No longer automatically loading default examples # self._load_default_examples() def _load_default_examples(self): """Load default examples to help users get started - now only used if manually called""" if not self.examples: # Only load if no examples exist logger.info("Loading default examples") self.examples = self.default_examples.copy() self.valid_categories = sorted(set([ex['category'] for ex in self.examples])) logger.info(f"Loaded {len(self.examples)} default examples with categories: {self.valid_categories}") def load_default_examples(self): """Public method to manually load default examples if desired""" self._load_default_examples() examples_str = self.get_examples_str() return f"Loaded {len(self.examples)} default examples with categories: {self.valid_categories}\n\n{examples_str}" def add_example(self, text, category): """Add a new example with its corresponding category""" if text and category: self.examples.append({"text": text, "category": category}) # Update valid categories self.valid_categories = sorted(set([ex['category'] for ex in self.examples])) examples_str = self.get_examples_str() return f"Example added! Current examples:\n{examples_str}", "" return "Please provide both text and category", "" def get_examples_str(self): """Get a string representation of all examples""" return "\n".join([f"Example {i+1}: '{ex['text']}' => Category: '{ex['category']}'" for i, ex in enumerate(self.examples)]) def import_examples(self, file): """Import examples from a CSV, Excel, or JSON file""" if file is None: return "No file uploaded." try: # Handle the file based on what Gradio provides file_path = file.name # Determine file type and read accordingly if file_path.lower().endswith('.json'): # Import from JSON (exported examples) with open(file_path, 'r') as f: imported_examples = json.load(f) # Validate the imported examples if not isinstance(imported_examples, list): return "Invalid JSON format. Expected a list of examples." count = 0 for example in imported_examples: if isinstance(example, dict) and 'text' in example and 'category' in example: self.examples.append(example) count += 1 # Update valid categories self.valid_categories = sorted(set([ex['category'] for ex in self.examples])) examples_str = self.get_examples_str() return f"Imported {count} examples from JSON successfully!\n\nCurrent examples:\n{examples_str}" # For CSV and Excel files, try to determine the format try: if file_path.lower().endswith('.csv'): df = pd.read_csv(file_path) elif file_path.lower().endswith(('.xlsx', '.xls')): df = pd.read_excel(file_path) else: # Try to infer the file type try: # First try as CSV df = pd.read_csv(file_path) except Exception: try: # Then try as Excel df = pd.read_excel(file_path) except Exception: return "Unsupported file format. Please upload a CSV, Excel, or JSON file." # Check if the file has the required columns if len(df.columns) < 2: return "File must have at least 2 columns: text and category." # Assume the first column is text and the second is category text_col = df.columns[0] category_col = df.columns[1] # Add each row as an example count = 0 for _, row in df.iterrows(): text = str(row[text_col]) category = str(row[category_col]) if text and category and pd.notna(text) and pd.notna(category): self.examples.append({"text": text, "category": category}) count += 1 # Update valid categories self.valid_categories = sorted(set([ex['category'] for ex in self.examples])) examples_str = self.get_examples_str() return f"Imported {count} examples successfully!\n\nCurrent examples:\n{examples_str}" except Exception as e: return f"Error processing file: {str(e)}" except Exception as e: return f"Error importing examples: {str(e)}" def import_dataset(self, file): """Import a dataset from a CSV or Excel file""" if file is None: logger.warning("No file uploaded for dataset import") return "No file uploaded.", [], [] try: # Handle the file based on what Gradio provides file_path = file.name logger.info(f"Importing dataset from file: {file_path}") # Determine file type and read accordingly if file_path.lower().endswith('.csv'): logger.info(f"Detected CSV file format") df = pd.read_csv(file_path) elif file_path.lower().endswith(('.xlsx', '.xls')): logger.info(f"Detected Excel file format") df = pd.read_excel(file_path) else: # Try to infer the file type logger.info(f"Trying to infer file format") try: # First try as CSV df = pd.read_csv(file_path) logger.info(f"Successfully read as CSV") except Exception as e: logger.info(f"Failed to read as CSV: {str(e)}") try: # Then try as Excel df = pd.read_excel(file_path) logger.info(f"Successfully read as Excel") except Exception as e: logger.error(f"Failed to read file as CSV or Excel: {str(e)}") return "Unsupported file format. Please upload a CSV or Excel file.", [], [] # Store the dataset self.dataset = df self.dataset_path = file_path # Get column names for selection dropdowns columns = df.columns.tolist() logger.info(f"Extracted columns: {columns}") # Create a preview of the dataframe preview = df.head(5).to_string(index=False) # Create output column list output_columns = list(columns) # Convert to list to ensure it's a fresh copy output_columns.append("New Category Column") logger.info(f"Output columns (with New Category): {output_columns}") # Return the values for the UI components message = f"Dataset imported successfully!\n\nPreview:\n{preview}" return message, columns, output_columns except Exception as e: logger.error(f"Error importing dataset: {str(e)}") return f"Error importing dataset: {str(e)}", [], [] def set_columns(self, input_col, output_col): """Set the input and output columns for the dataset""" logger.info(f"Setting columns - Input: '{input_col}', Output: '{output_col}'") if self.dataset is None: logger.warning("Dataset not imported yet") return "Please import a dataset first." if not input_col: logger.warning("No input column selected") return "Please select an input column." if not output_col: logger.warning("No output column provided") return "Please provide an output column name." if input_col == output_col: logger.warning("Input and output columns are the same") return "Input and output columns must be different." # Store the selected columns self.input_column = input_col self.output_column = output_col logger.info(f"Columns set to - Input: '{self.input_column}', Output: '{self.output_column}'") # Create the output column if it doesn't exist if output_col not in self.dataset.columns: logger.info(f"Creating new output column: '{output_col}'") self.dataset[output_col] = "" return f"✅ Columns set successfully!\n\nInput Column: '{input_col}'\nOutput Column: '{output_col}' (new column created)" logger.info(f"Using existing output column: '{output_col}'") return f"✅ Columns set successfully!\n\nInput Column: '{input_col}'\nOutput Column: '{output_col}'" def update_model_parameters(self, temperature, max_tokens, timeout): """Update the model parameters for inference""" try: # Validate and convert parameters if temperature: temp = float(temperature) if 0.0 <= temp <= 1.0: self.model_temperature = temp else: return "Temperature must be between 0.0 and 1.0" if max_tokens: tokens = int(max_tokens) if 1 <= tokens <= 2048: self.model_max_tokens = tokens else: return "Max tokens must be between 1 and 2048" if timeout: to = int(timeout) if 5 <= to <= 300: self.model_timeout = to else: return "Timeout must be between 5 and 300 seconds" # Create a new LLM with updated parameters global llm llm = create_llm( temperature=self.model_temperature, max_tokens=self.model_max_tokens, timeout=self.model_timeout ) return f"✅ Model parameters updated successfully!\n\nTemperature: {self.model_temperature}\nMax Tokens: {self.model_max_tokens}\nTimeout: {self.model_timeout} seconds" except ValueError as e: logger.error(f"Parameter validation error: {str(e)}") return f"Error: Invalid parameter format. Please enter valid numbers." except Exception as e: logger.error(f"Error updating model parameters: {str(e)}") return f"Error updating parameters: {str(e)}" def categorize(self, text): """Categorize new text based on examples using the LLM""" if not self.examples: logger.warning("No examples provided for categorization") return "No examples available. Please add examples first by:\n1. Adding them manually in the 'Add Examples' tab\n2. Importing from a file\n3. Clicking the 'Load Default Examples' button" if not text or text.strip() == "": logger.warning("Empty text provided for categorization") return "Please enter text to categorize." # Update valid categories self.valid_categories = sorted(set([ex['category'] for ex in self.examples])) logger.info(f"Categorizing text with categories: {self.valid_categories}") # For performance reasons, limit to 30 examples in the actual prompt examples_limit = 30 using_all_examples = len(self.examples) <= examples_limit examples_for_prompt = self.examples if using_all_examples else self.examples[:examples_limit] # Format examples for the prompt formatted_examples = "\n".join([ f"Text: \"{ex['text']}\" → Category: {ex['category']}" for ex in examples_for_prompt ]) # Add note about hidden examples if needed if not using_all_examples: formatted_examples += f"\n\n[Note: Showing {examples_limit} of {len(self.examples)} examples]" # Format categories as a bulleted list formatted_categories = "\n".join([f"- {cat}" for cat in self.valid_categories]) # Create the chain and get prompt templates chain, system_template, human_template = create_single_categorization_chain(self.valid_categories) # Store prompts for display self.last_system_prompt = system_template self.last_user_prompt = human_template.format( categories=formatted_categories, examples=formatted_examples, text=text ) # Set up the callback callback = LoggingCallbackHandler() try: # Run the chain logger.info(f"Sending text for categorization: '{text[:50]}...'") result = chain.invoke( { "examples": formatted_examples, "text": text }, config={"callbacks": [callback]} ) # Extract the category from the result raw_category = result.strip() logger.info(f"Raw model response: '{raw_category}'") # Check for "None" response first if raw_category.lower() == "none": logger.info("Model determined no category fits") return "No Category" # Validate the category is in our list if raw_category in self.valid_categories: logger.info(f"Successfully categorized text as: {raw_category}") return raw_category else: # Try to match with existing categories for valid_cat in self.valid_categories: if valid_cat.lower() == raw_category.lower() or valid_cat in raw_category: logger.info(f"Matched partial category '{raw_category}' to '{valid_cat}'") return valid_cat # Default to first category if no match (fallback) logger.warning(f"Category '{raw_category}' not in valid categories, using default") return self.valid_categories[0] except Exception as e: logger.error(f"Error during categorization: {str(e)}") # More user-friendly error message based on error type if "timeout" in str(e).lower(): return "Error: The model took too long to respond. Try increasing the timeout in Advanced Settings." elif "token" in str(e).lower(): return "Error: Please check your Hugging Face token is set correctly in the .env file." elif "connection" in str(e).lower(): return "Error: Connection issue with the model API. Please check your internet connection." else: return f"Error: {str(e)}" def categorize_batch(self, texts, batch_size=10): """Categorize a batch of texts to reduce API calls""" if not self.examples: logger.warning("No examples provided for categorization") return ["No examples available. Please add examples first by:\n1. Adding them manually in the 'Add Examples' tab\n2. Importing from a file\n3. Clicking the 'Load Default Examples' button"] * len(texts) # Update valid categories self.valid_categories = sorted(set([ex['category'] for ex in self.examples])) logger.info(f"Batch categorizing with categories: {self.valid_categories}") if not self.valid_categories: logger.warning("No valid categories found in examples") return ["No valid categories available"] * len(texts) # For performance reasons, limit to 8 examples in the actual prompt examples_limit = 8 using_all_examples = len(self.examples) <= examples_limit examples_for_prompt = self.examples if using_all_examples else self.examples[:examples_limit] # Format examples for the prompt formatted_examples = "\n".join([ f"Text: \"{ex['text']}\" → Category: {ex['category']}" for ex in examples_for_prompt ]) # Add note about hidden examples if needed if not using_all_examples: formatted_examples += f"\n\n[Note: Showing {examples_limit} of {len(self.examples)} examples]" # Format categories as a bulleted list formatted_categories = "\n".join([f"- {cat}" for cat in self.valid_categories]) # Create the chain without callbacks initially chain, system_template, human_template = create_batch_categorization_chain(self.valid_categories) # Store sample prompts for display (first batch) first_batch = texts[:min(batch_size, len(texts))] formatted_texts = "\n".join([ f"Text {j+1}: \"{text}\"" for j, text in enumerate(first_batch) ]) self.last_system_prompt = system_template self.last_user_prompt = human_template.format( categories=formatted_categories, examples=formatted_examples, texts=formatted_texts ) # Process texts in batches results = [] total_texts = len(texts) # Use smaller batch size for larger model (max 5) batch_size = min(5, batch_size) logger.info(f"Processing {total_texts} texts in batches of {batch_size}") for i in range(0, total_texts, batch_size): batch = texts[i:i+batch_size] current_batch_size = len(batch) # Format the texts for the prompt formatted_texts = "\n".join([ f"Text {j+1}: \"{text}\"" for j, text in enumerate(batch) ]) # Try up to 3 times with decreasing batch size if errors occur max_retries = 3 success = False for retry in range(max_retries): try: if retry > 0: # Reduce batch size on retry reduced_size = max(1, current_batch_size // (retry + 1)) if reduced_size < current_batch_size: logger.info(f"Retry {retry+1}: Reducing batch size to {reduced_size}") # Handle only part of the batch partial_batch = batch[:reduced_size] formatted_texts = "\n".join([ f"Text {j+1}: \"{text}\"" for j, text in enumerate(partial_batch) ]) else: # If can't reduce further, break break # Create a fresh callback for each batch callback = LoggingCallbackHandler() # Run the chain logger.info(f"Sending batch {i//batch_size + 1} (attempt {retry+1})") raw_result = chain.invoke( { "examples": formatted_examples, "texts": formatted_texts }, config={"callbacks": [callback]} ) # Parse the output using our custom parser parser = CategoryOutputParser(self.valid_categories) categories = parser.parse(raw_result) logger.info(f"Raw batch response: {raw_result}") logger.info(f"Parsed categories: {categories}") # Ensure we have a category for each text in this batch/partial batch current_batch = partial_batch if retry > 0 else batch if len(categories) < len(current_batch): logger.warning(f"Got only {len(categories)} categories for {len(current_batch)} texts") # Fill missing with default category categories.extend([self.valid_categories[0]] * (len(current_batch) - len(categories))) # If we got more categories than texts, trim the excess categories = categories[:len(current_batch)] # Add to results results.extend(categories) success = True # If retry > 0, we processed a partial batch, so update batch if retry > 0: batch = batch[reduced_size:] if batch: # If there are remaining items, continue with them continue # Skip the break # If we successfully processed the full batch, break retry loop break except Exception as e: logger.error(f"Error during batch categorization (attempt {retry+1}): {str(e)}") if retry == max_retries - 1: # Last retry failed # Fill with default category for this batch/partial batch current_batch = partial_batch if retry > 0 else batch results.extend([self.valid_categories[0]] * len(current_batch)) # Log progress logger.info(f"Processed batch {i//batch_size + 1}/{(total_texts + batch_size - 1)//batch_size}") # Final check to ensure we have the right number of results if len(results) < len(texts): logger.warning(f"Result length mismatch. Got {len(results)}, expected {len(texts)}") results.extend([self.valid_categories[0]] * (len(texts) - len(results))) elif len(results) > len(texts): logger.warning(f"Too many results. Got {len(results)}, expected {len(texts)}") results = results[:len(texts)] return results def process_dataset(self): """Process the dataset and categorize all rows using batch processing""" logger.info("Processing dataset requested") if self.dataset is None: logger.warning("Dataset not imported yet") return "Please import a dataset first in Step 1." if self.input_column is None or self.output_column is None: logger.warning("Input or output column not set") return "Please select input and output columns in Step 2." if not self.examples: logger.warning("No examples added") return "No examples available. Please add examples first by:\n1. Adding them manually in the 'Add Examples' tab\n2. Importing from a file\n3. Clicking the 'Load Default Examples' button" try: total_rows = len(self.dataset) logger.info(f"Starting to process {total_rows} rows using input column '{self.input_column}' and output column '{self.output_column}'") result_text = f"Starting to process {total_rows} rows...\n\n" # Show info about the examples being used example_categories = set([ex['category'] for ex in self.examples]) result_text += f"Using {len(self.examples)} examples across {len(example_categories)} categories.\n" result_text += "The model can also return 'No Category' when no category fits.\n\n" # Collect all texts to process texts_to_process = [] row_indices = [] for i, row in self.dataset.iterrows(): text = str(row[self.input_column]) if pd.isna(text) or text.strip() == "": continue texts_to_process.append(text) row_indices.append(i) if not texts_to_process: logger.warning("No valid text data found in the input column") return "No valid text data found in the input column. Please check your data." # Create progress updates for the UI progress_states = [] total_texts = len(texts_to_process) # First try batch processing try: logger.info("Attempting batch processing") result_text += "Attempting batch processing...\n" # Process texts in batches of max 5 for large models batch_size = 5 # Smaller batch size for reliability # Set up progress states progress_updates = ["⏳ Initializing..."] # Categorize in batches with progress updates categories = [] for i in range(0, total_texts, batch_size): batch = texts_to_process[i:i+batch_size] current_batch = i // batch_size + 1 total_batches = (total_texts + batch_size - 1) // batch_size # Update progress progress_percent = min(100, int((i / total_texts) * 100)) progress_updates.append(f"⏳ Processing batch {current_batch}/{total_batches} ({progress_percent}% complete)") # Process the batch batch_categories = self.categorize_batch(batch, batch_size=batch_size) categories.extend(batch_categories) # Final progress update progress_updates.append("✅ Processing complete (100%)") progress_states = "\n".join(progress_updates) result_text += progress_states + "\n\n" except Exception as e: # If batch processing fails, fall back to one-by-one processing logger.warning(f"Batch processing failed: {str(e)}. Falling back to one-by-one processing.") result_text += f"Batch processing failed: {str(e)}.\nFalling back to one-by-one processing...\n\n" # Set up progress states progress_updates = ["⏳ Initializing one-by-one processing..."] categories = [] # Process each item individually for i, text in enumerate(texts_to_process): try: # Update progress every 5 items or at specific milestones if i % 5 == 0 or i == len(texts_to_process) - 1: progress_percent = min(100, int((i / total_texts) * 100)) progress_updates.append(f"⏳ Processing item {i+1}/{total_texts} ({progress_percent}% complete)") progress_states = "\n".join(progress_updates) logger.info(f"Processing item {i+1}/{len(texts_to_process)}") category = self.categorize(text) categories.append(category) except Exception as item_error: logger.error(f"Error categorizing text: {str(item_error)}") # Use default category as fallback categories.append(self.valid_categories[0] if self.valid_categories else "Error") # Final progress update progress_updates.append("✅ Processing complete (100%)") progress_states = "\n".join(progress_updates) result_text += progress_states + "\n\n" # Update the dataset with categories for i, category in zip(row_indices, categories): self.dataset.at[i, self.output_column] = category # Show sample of processed data result_text += "Sample results (first 20 entries):\n" for i in range(min(20, len(texts_to_process))): text = texts_to_process[i] category = categories[i] result_text += f"Input {i+1}: '{text[:50]}{'...' if len(text) > 50 else ''}'\nCategory: '{category}'\n\n" # Summary of categorization category_counts = {} for category in categories: category_counts[category] = category_counts.get(category, 0) + 1 result_text += "Categorization summary:\n" for category, count in sorted(category_counts.items()): percentage = (count / len(categories)) * 100 result_text += f"- {category}: {count} items ({percentage:.1f}%)\n" result_text += "\n" # Show prompt examples result_text += "Prompt used for categorization:\n\n" result_text += "System Prompt:\n" result_text += "```\n" + self.last_system_prompt + "\n```\n\n" result_text += "User Prompt (example):\n" result_text += "```\n" + self.last_user_prompt + "\n```\n\n" # Save the processed dataset if self.dataset_path.lower().endswith('.csv'): self.dataset.to_csv(self.dataset_path, index=False) elif self.dataset_path.lower().endswith(('.xlsx', '.xls')): self.dataset.to_excel(self.dataset_path, index=False) result_text += f"✅ Processed {len(texts_to_process)} rows successfully.\n" result_text += f"✅ Dataset saved with categories in the '{self.output_column}' column.\n" result_text += "👇 Click 'Download Processed Dataset' below to download your results." return result_text except Exception as e: logger.error(f"Error processing dataset: {str(e)}") # More user-friendly error message if "memory" in str(e).lower(): return "Error: The dataset is too large to process at once. Try processing smaller batches." else: return f"Error processing dataset: {str(e)}" def download_dataset(self): """Return the processed dataset for download""" if self.dataset is None or self.dataset_path is None: return None return self.dataset_path def export_examples(self): """Export examples to a JSON file""" if not self.examples: return None try: # Create a temporary file for the examples temp_dir = tempfile.gettempdir() export_path = os.path.join(temp_dir, "categorization_examples.json") with open(export_path, 'w') as f: json.dump(self.examples, f, indent=2) return export_path except Exception as e: print(f"Error exporting examples: {str(e)}") return None # Create the app instance app = CategoryApp() # Create the Gradio interface with gr.Blocks(title="Text Categorization App") as demo: gr.Markdown("# Text Categorization App") gr.Markdown("This app uses the Mistral-7B-Instruct model to categorize text based on examples.") with gr.Accordion("About this App", open=False): gr.Markdown(""" ## How it Works This app categorizes text into predefined categories using AI. It works by: 1. **Adding examples** - Start by adding your own examples or load the default ones with the "Load Default Examples" button 2. **Analyzing data** - Upload your dataset and select columns for processing 3. **Categorizing text** - The AI model categorizes each entry based on your examples ## Tips for Better Results - Add multiple varied examples for each category - Make sure your examples clearly represent each category - For best results, use 5-10 examples per category - Use "Advanced Settings" to adjust model parameters if needed - The model can return "No Category" when text doesn't fit any of your categories ## New Feature: "No Category" Option If text doesn't match any of your defined categories, the model can now classify it as "No Category" instead of forcing it into an ill-fitting category. This improves accuracy by: - Only assigning categories when there's a reasonable fit - Helping you identify texts that may need different categories - Avoiding incorrect categorizations when no good match exists """) # Define a function to log and update dropdowns def update_dropdowns(import_result, input_cols, output_cols): logger.info(f"Updating dropdowns - Input columns: {input_cols}, Output columns: {output_cols}") return import_result, input_cols, output_cols with gr.Tab("1. Add Examples"): gr.Markdown(""" ## Getting Started To categorize text, you need to provide examples first. You can: 1. Add your own examples using the form below 2. Import examples from a file 3. Click "Load Default Examples" to use our pre-defined set of examples """) with gr.Row(): example_text = gr.Textbox(label="Example Text", placeholder="Enter text to use as example...") example_category = gr.Textbox(label="Category", placeholder="Enter the correct category...") add_btn = gr.Button("Add Example") examples_output = gr.Textbox(label="Examples Database", lines=10) clear_output = gr.Textbox(label="", visible=False) with gr.Row(): load_defaults_btn = gr.Button("Load Default Examples") # Add sample examples for users to try gr.Examples( [ ["I absolutely love this product! It's changed my life.", "Positive"], ["This has been a wonderful experience overall.", "Positive"], ["The quality exceeded my expectations in every way.", "Positive"], ["This is awful and doesn't work properly.", "Negative"], ["Disappointed with the performance and reliability.", "Negative"], ["Waste of money, I regret purchasing this item.", "Negative"], ["How do I reset my password?", "Question"], ["Can you tell me what the return policy is?", "Question"], ["When will the next version be released?", "Question"], ["The store is open from 9am to 5pm on weekdays.", "Information"], ["This product contains 3 grams of sugar per serving.", "Information"], ["The meeting will be held in Room 302 at 2pm.", "Information"], ["I need help with setting up my account.", "Support"], ["My order hasn't arrived yet, can you help track it?", "Support"], ["The application keeps crashing when I try to save.", "Support"] ], inputs=[example_text, example_category], label="Sample Examples" ) add_btn.click( app.add_example, inputs=[example_text, example_category], outputs=[examples_output, clear_output] ) load_defaults_btn.click( app.load_default_examples, inputs=[], outputs=[examples_output] ) clear_output.change(lambda _: "", inputs=clear_output, outputs=example_text) gr.Markdown("### Import Examples") with gr.Row(): examples_file = gr.File(label="Upload Examples File (CSV, Excel, or JSON)") import_examples_btn = gr.Button("Import Examples") gr.Markdown(""" ### File Format Information - **CSV/Excel**: First column = text, Second column = category - **JSON**: Exported examples file (can be loaded back) """) import_examples_output = gr.Textbox(label="Import Result", lines=10) import_examples_btn.click( app.import_examples, inputs=[examples_file], outputs=[import_examples_output] ) with gr.Row(): export_examples_btn = gr.Button("Export Examples") export_examples_output = gr.File(label="Download Examples") export_examples_btn.click( app.export_examples, inputs=[], outputs=[export_examples_output] ) with gr.Tab("2. Categorize Single Text"): new_text = gr.Textbox(label="Text to Categorize", placeholder="Enter text to categorize...") categorize_btn = gr.Button("Categorize") result = gr.Textbox(label="Predicted Category") # Add a section to show prompts with gr.Accordion("View Prompts", open=False): system_prompt_display = gr.Textbox(label="System Prompt", lines=10, interactive=False) user_prompt_display = gr.Textbox(label="User Prompt", lines=15, interactive=False) # Add sample texts for categorization gr.Examples( [ "This product exceeded my expectations!", "Could you explain how to use this feature?", "The service was horrible and staff was rude.", "The store is open from 9am to 5pm on weekdays." ], inputs=new_text, label="Sample Texts to Categorize" ) def categorize_and_show_prompts(text): category = app.categorize(text) return category, app.last_system_prompt, app.last_user_prompt categorize_btn.click( categorize_and_show_prompts, inputs=[new_text], outputs=[result, system_prompt_display, user_prompt_display] ) with gr.Tab("3. Process Dataset"): gr.Markdown("### Step 1: Import Dataset") with gr.Row(): dataset_file = gr.File(label="Upload Dataset (CSV or Excel)") import_dataset_btn = gr.Button("Import Dataset") import_dataset_output = gr.Textbox(label="Import Result", lines=10) # Hidden field to store available columns available_columns = gr.Textbox(label="Available Columns", visible=True) gr.Markdown("### Step 2: Configure Columns") gr.Markdown(""" After importing your dataset: 1. Select a column from the list of available columns above 2. Enter that column name in the "Input Column" field below 3. Enter a name for the output column (where categories will be stored) 4. Click "Set Columns" to confirm your selection """) with gr.Row(): # Simple text inputs for column names input_column_text = gr.Textbox( label="Input Column (text to categorize)", placeholder="Enter exactly as shown in Available Columns", interactive=True ) output_column_text = gr.Textbox( label="Output Column Name (for categories)", value="Category", interactive=True ) set_columns_btn = gr.Button("Set Columns") set_columns_output = gr.Textbox(label="Column Selection Result") gr.Markdown("### Step 3: Process Dataset") gr.Markdown(""" After setting columns: 1. Click "Process Dataset" to categorize all entries 2. Review the results 3. Click "Download Processed Dataset" to get the file with categories Note: Make sure to add examples in Tab 1 before processing your dataset. """) process_dataset_btn = gr.Button("Process Dataset") process_dataset_output = gr.Textbox(label="Processing Result", lines=30) with gr.Row(): download_dataset_btn = gr.Button("Download Processed Dataset") download_dataset_output = gr.File(label="Download Dataset") # Function to handle dataset import and show column names def handle_import(file): result, columns, _ = app.import_dataset(file) columns_str = "Available Columns: " + ", ".join(columns) return result, columns_str # Function to set columns def handle_set_columns(input_col, output_col): return app.set_columns(input_col, output_col) # Set up the connections between components import_dataset_btn.click( handle_import, inputs=[dataset_file], outputs=[import_dataset_output, available_columns] ) set_columns_btn.click( handle_set_columns, inputs=[input_column_text, output_column_text], outputs=[set_columns_output] ) process_dataset_btn.click( app.process_dataset, inputs=[], outputs=[process_dataset_output] ) download_dataset_btn.click( app.download_dataset, inputs=[], outputs=[download_dataset_output] ) with gr.Tab("4. Advanced Settings"): gr.Markdown("### Model Parameters") gr.Markdown(""" Adjust these parameters to fine-tune the model's behavior: - **Temperature**: Controls randomness (0.0-1.0) - Lower values (0.0-0.3): More predictable, consistent results - Higher values (0.7-1.0): More creative, varied results - **Max Tokens**: Maximum response length - For categorization, 256 is usually sufficient - **Timeout**: Maximum seconds to wait for model response - Increase if processing long texts or experiencing timeouts """) with gr.Row(): temperature = gr.Slider( minimum=0.0, maximum=1.0, step=0.05, value=app.model_temperature, label="Temperature" ) max_tokens = gr.Slider( minimum=50, maximum=1024, step=50, value=app.model_max_tokens, label="Max Tokens" ) timeout = gr.Slider( minimum=10, maximum=120, step=5, value=app.model_timeout, label="Timeout (seconds)" ) update_params_btn = gr.Button("Update Model Parameters") params_result = gr.Textbox(label="Result") update_params_btn.click( app.update_model_parameters, inputs=[temperature, max_tokens, timeout], outputs=[params_result] ) gr.Markdown("### Troubleshooting") gr.Markdown(""" If you encounter issues: - **Timeouts**: Increase the timeout parameter above - **Inaccurate categorization**: Add more diverse examples - **Slow processing**: Try processing smaller batches of data - **Errors**: Check the error message for specific issues """) # Launch the app demo.launch()