import gradio as gr from transformers import AutoModelForCausalLM, LlamaTokenizer from transformers import LlamaTokenizerFast import torch import json import os # Retrieve the Hugging Face token from environment variables hf_token = os.getenv('read_hf_token') # Verify that the token is available if not hf_token: raise ValueError("HUGGINGFACE_TOKEN environment variable not set.") tokenizer = LlamaTokenizerFast.from_pretrained( "meta-llama/Llama-3.2-3B", use_fast=False, token=hf_token # Updated parameter ) model = AutoModelForCausalLM.from_pretrained( "laohan/mini_liao", token=hf_token # Updated parameter ) # Move the model to GPU if available device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) # Set pad_token_id to eos_token_id to handle padding tokenizer.pad_token_id = tokenizer.eos_token_id model.config.pad_token_id = tokenizer.eos_token_id def generate_category(description): instruction = "Categorize the following project, based on the following info:" prompt = f"Instruction: {instruction}\n\nInput: {description}\n\nOutput:" # Tokenize the prompt with attention mask inputs = tokenizer( prompt, return_tensors='pt', padding=True, truncation=True, max_length=1024 # Adjust as needed ).to(device) # Generate output with attention_mask output_ids = model.generate( inputs['input_ids'], attention_mask=inputs['attention_mask'], max_length=512, # Adjust as needed num_beams=5, early_stopping=True, no_repeat_ngram_size=2, ) # Decode the generated tokens output_text = tokenizer.decode(output_ids[0], skip_special_tokens=True) print(output_text) # Find the first JSON string in the output json_start = output_text.find('{') json_end = output_text.find('}') + 1 if json_start != -1 and json_end != -1: json_string = output_text[json_start:json_end] else: json_string = "No JSON output found." print(json_string) return json_string # Extract the output after 'Output:' output_parts = output_text.split('Output:') if len(output_parts) > 1: category_output = output_parts[1].strip() else: category_output = "No output generated." # Parse JSON if possible try: category_dict = json.loads(category_output) return json.dumps(category_dict, indent=2) except json.JSONDecodeError: return category_output # Create Gradio interface iface = gr.Interface( fn=generate_category, inputs=gr.Textbox(lines=10, placeholder="Enter project description here..."), outputs="text", title="Project Categorization", description="Enter a project description, and the model will generate its category.", ) # Launch the interface iface.launch()