File size: 1,998 Bytes
c64d0ae
e14e73b
d64331d
8778ef9
e14e73b
c64d0ae
8e4baa6
c64d0ae
 
 
 
8778ef9
e14e73b
c64d0ae
8778ef9
e14e73b
c64d0ae
 
8778ef9
c64d0ae
 
 
 
 
e14e73b
8778ef9
c64d0ae
 
8778ef9
c64d0ae
e14e73b
7aa8793
e14e73b
 
 
c64d0ae
 
e14e73b
d64331d
7aa8793
 
e14e73b
 
c64d0ae
8778ef9
e14e73b
c64d0ae
 
e14e73b
c64d0ae
8778ef9
c64d0ae
7aa8793
e14e73b
c64d0ae
8778ef9
c64d0ae
 
 
 
d64331d
c64d0ae
8778ef9
 
c64d0ae
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
56
57
58
59
60
61
62
63
64
65
import os
import gc
import psutil
import gradio as gr
import keras_nlp
from huggingface_hub import login

# Get the API key from environment variable
api_key = os.getenv("HUGGINGFACE_API_KEY")
if not api_key:
    raise ValueError("Please set the 'HUGGINGFACE_API_KEY' environment variable.")

# Log in with the provided Hugging Face API token
login(api_key)

# Load the Keras NLP model from Hugging Face
model_path = "MNLobago/EcoWise_model"
gemma_lm = keras_nlp.models.GemmaCausalLM.from_preset(f"hf://{model_path}")

class GemmaChat:
    def __init__(self, model, max_length=150, system=""):
        self.model = model
        self.max_length = max_length
        self.system = system
        self.history = []

    def get_full_prompt(self, user_input):
        return f"User: {user_input}\nModel:"

    def query(self, question):
        if not self.history:
            prompt = self.system + "\n" + self.get_full_prompt(question) if self.system else self.get_full_prompt(question)
        else:
            prompt = self.get_full_prompt(question)
        
        response = self.model.generate(prompt, max_length=self.max_length)
        model_response = response.replace(prompt, "").strip()
        
        # Sanitize the response
        if model_response.endswith('?'):
            model_response = model_response.rstrip('?') + '.'

        gc.collect()
        return model_response

# Initialize the chat object
chat = GemmaChat(
    model=gemma_lm,
    system="""You are an intelligent chatbot focused on answering questions related to climate change, sustainability, and carbon footprint."""
)

def chat_with_model(input_text):
    chat.history = []
    answer = chat.query(input_text)
    return [("user", input_text), ("model", answer)]

# Create and launch the Gradio interface
demo = gr.Interface(
    fn=chat_with_model,
    inputs="text",
    outputs="chatbot",
    description="🌍 Welcome to EcoWise, your go-to climate-savvy chatbot! I'm here to help you."
)

demo.launch()