import os from hugchat import hugchat from hugchat.login import Login from dotenv import load_dotenv load_dotenv() HF_EMAIL = os.getenv("HUGGINGFACE_EMAIL") HF_PASS = os.getenv("HUGGINGFACE_PASS") # Global variables to reuse login session _chatbot = None def get_chatbot(): global _chatbot if _chatbot: return _chatbot if not HF_EMAIL or not HF_PASS: print("Warning: HUGGINGFACE_EMAIL or HUGGINGFACE_PASS not found.") return None try: sign = Login(HF_EMAIL, HF_PASS) cookies = sign.login() _chatbot = hugchat.ChatBot(cookies=cookies.get_dict()) return _chatbot except Exception as e: print(f"HuggingChat Login Error: {e}") return None def generate_hugchat_response(prompt: str) -> str: """ Generates text using HuggingChat. """ chatbot = get_chatbot() if not chatbot: return "AI unavailable (Auth missing)." try: # Create a new conversation for isolation or reuse default id = chatbot.new_conversation() chatbot.change_conversation(id) response = chatbot.chat(prompt) text = response.wait_until_done() # Cleanup? (Optional, but good for privacy) # chatbot.delete_conversation(id) return text except Exception as e: print(f"HuggingChat Error: {e}") return "AI unavailable (Error)."