File size: 1,429 Bytes
02cc7f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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)."