Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252698 unmodified lines125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178import randomimport requestsimport twitchiofrom twitchio.ext import commandsfrom huggingface_hub import InferenceClientimport json# Load your config for Twitch credentials and Hugging Face APIdef load_config():"""Load configuration from config.json."""with open('config.json', 'r') as config_file:return json.load(config_file)config = load_config()# Use the Hugging Face API token from the environment variable (set as a secret)api_token = os.getenv('HUGGINGFACE_API_TOKEN')if api_token is None:print("Environment variable 'HUGGINGFACE_API_TOKEN' is missing.")raise ValueError("Hugging Face API token not found in environment variables.")# Initialize the Inference Client for GPT-Neoclient = InferenceClient("EleutherAI/gpt-neo-1.3B")# List of house music hooks to drop randomlyhouse_music_hooks = [98 unmodified lines"The music's got us moving, can't stop dancing!",]# Define the response function to generate a reply with a random house music hookdef generate_response(prompt):"""Generates a response using GPT-Neo model."""guided_prompt = f"Yo, what’s up? You’re talking to an old-school raver who’s all about house music, good vibes, and funky beats. Let’s keep it groovy, laid-back, and full of love!\n{prompt}"payload = {'model': 'EleutherAI/gpt-neo-1.3B','prompt': guided_prompt,'max_tokens': 150,'temperature': 0.7,'stream': False,}# Send the request to Hugging Face APItry:response = client.chat_completion([{"role": "user", "content": guided_prompt}], stream=False)result = response['choices'][0]['message']['content']return random.choice(house_music_hooks) + " " + resultexcept Exception as e:print(f"Error generating response: {e}")return "Sorry, I'm too hyped to respond right now!"# Create a Twitch chatbot using TwitchIOclass LlamaChatBot(commands.Bot):def __init__(self):# Initialize the bot with your Twitch OAuth token and the channel namesuper().__init__(token=config['oauth_token'], prefix='!', initial_channels=[config['channel_name']])async def event_ready(self):"""Event handler when the bot is connected and ready."""print(f"Logged in as {self.nick}")print(f"Connected to channel: {config['channel_name']}")async def event_message(self, message):"""Event handler when a message is received in chat."""if message.author.name.lower() == self.nick.lower():return # Ignore the bot's own messagesprint(f"Message received: {message.content} from {message.author.name}")# Generate a response using the GPT-Neo modelresponse = generate_response(message.content)# Send the response back to the Twitch chatawait message.channel.send(f"@{message.author.name} {response}")# Initialize and run the botif __name__ == "__main__":bot = LlamaChatBot()bot.run()12345678910111213141516171819202122232425262728293031323334353637383940414298 unmodified lines141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205import osimport randomimport loggingimport asynciofrom twitchio.ext import commandsfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM# Set up logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Get Twitch credentials and Hugging Face API token from environment variablesTWITCH_OAUTH_TOKEN = os.getenv('TWITCH_OAUTH_TOKEN')TWITCH_CHANNEL_NAME = os.getenv('TWITCH_CHANNEL_NAME')TWITCH_BOT_USERNAME = os.getenv('TWITCH_BOT_USERNAME')HUGGINGFACE_API_TOKEN = os.getenv('HUGGINGFACE_API_TOKEN')MAX_TOKENS = int(os.getenv('MAX_TOKENS', 50))TEMPERATURE = float(os.getenv('TEMPERATURE', 0.7))# Validate environment variablesrequired_vars = ['TWITCH_OAUTH_TOKEN','TWITCH_CHANNEL_NAME','TWITCH_BOT_USERNAME','HUGGINGFACE_API_TOKEN']missing_vars = [var for var in required_vars if not globals().get(var)]if missing_vars:raise ValueError(f"Missing environment variables: {', '.join(missing_vars)}")# Initialize the Hugging Face tokenizer and modelmodel_name = "google/flan-t5-small" # or "t5-small" for an even lighter modeltokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=HUGGINGFACE_API_TOKEN)model = AutoModelForSeq2SeqLM.from_pretrained(model_name, use_auth_token=HUGGINGFACE_API_TOKEN)# Ensure the model runs on CPUdevice = 'cpu'model.to(device)# List of house music hooks to drop randomlyhouse_music_hooks = [98 unmodified lines"The music's got us moving, can't stop dancing!",]# Define the response function to generate a replyasync def generate_response(prompt):"""Generates a response using the FLAN-T5 model."""guided_prompt = ("You are an old-school raver who’s all about house music, good vibes, ""and funky beats. Keep the conversation groovy, laid-back, and full of love.\n"f"User: {prompt}\nBot:")try:inputs = tokenizer.encode(guided_prompt, return_tensors="pt", max_length=512, truncation=True)inputs = inputs.to(device)outputs = model.generate(inputs,max_length=MAX_TOKENS + inputs.shape[1],temperature=TEMPERATURE,num_return_sequences=1,no_repeat_ngram_size=2,early_stopping=True,)response_text = tokenizer.decode(outputs[0], skip_special_tokens=True)# Extract the bot's responseresponse = response_text.replace(guided_prompt, "").strip()return f"{random.choice(HOUSE_MUSIC_HOOKS)} {response}"except Exception as e:logger.error(f"Error generating response: {e}")return "Sorry, I'm too hyped to respond right now!"# Create a Twitch chatbot using TwitchIOclass TwitchChatBot(commands.Bot):def __init__(self):super().__init__(token=TWITCH_OAUTH_TOKEN,nick=TWITCH_BOT_USERNAME,prefix='!',initial_channels=[TWITCH_CHANNEL_NAME])async def event_ready(self):"""Event handler when the bot is connected and ready."""logger.info(f"Logged in as | {self.nick}")logger.info(f"Connected to channel | {TWITCH_CHANNEL_NAME}")async def event_message(self, message):"""Event handler when a message is received in chat."""if message.author.name.lower() == self.nick.lower():return # Ignore the bot's own messageslogger.info(f"Message received from {message.author.name}: {message.content}")# Generate a responseresponse = await generate_response(message.content)# Send the response back to the Twitch chatawait message.channel.send(f"@{message.author.name} {response}")# Initialize and run the botif __name__ == "__main__":bot = TwitchChatBot()bot.run()
app.py+71-44