File size: 6,082 Bytes
03bf0d5
 
 
 
37eb186
925795a
03bf0d5
 
0be7c95
03bf0d5
 
 
 
 
 
 
0be7c95
03bf0d5
 
 
37eb186
03bf0d5
 
 
 
0be7c95
911a038
925795a
0be7c95
925795a
 
 
 
 
 
03bf0d5
 
0be7c95
 
 
03bf0d5
0be7c95
 
 
 
911a038
ddc98da
 
 
911a038
ddc98da
03bf0d5
0be7c95
925795a
 
 
 
03bf0d5
925795a
03bf0d5
0be7c95
ddc98da
 
 
 
 
03bf0d5
 
 
 
0be7c95
 
 
 
 
 
03bf0d5
 
0be7c95
925795a
37eb186
 
ddc98da
 
 
 
 
 
 
 
 
 
 
 
03bf0d5
ddc98da
03bf0d5
0be7c95
911a038
 
03bf0d5
911a038
03bf0d5
 
37eb186
925795a
03bf0d5
925795a
03bf0d5
925795a
03bf0d5
925795a
03bf0d5
 
 
 
 
 
911a038
03bf0d5
0be7c95
ddc98da
 
 
 
03bf0d5
925795a
ddc98da
911a038
03bf0d5
 
911a038
 
 
03bf0d5
0be7c95
911a038
 
 
0be7c95
 
 
 
 
 
911a038
 
 
 
 
 
 
 
 
03bf0d5
911a038
 
0be7c95
925795a
ddc98da
 
 
 
 
 
 
 
 
 
03bf0d5
925795a
 
ddc98da
03bf0d5
 
925795a
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import os
import gradio as gr
import numpy as np
import google.generativeai as genai
import faiss
from sentence_transformers import SentenceTransformer
from datasets import load_dataset
from dotenv import load_dotenv
import threading

# Load environment variables
load_dotenv()

# Configuration
MODEL_NAME = "all-MiniLM-L6-v2"
GENAI_MODEL = "gemini-pro"
DATASET_NAME = "midrees2806/7K_Dataset"
CHUNK_SIZE = 500
TOP_K = 3

class GeminiRAGSystem:
    def __init__(self):
        self.index = None
        self.chunks = []
        self.dataset_loaded = False
        self.loading_error = None
        self.gemini_api_key = os.getenv("GEMINI_API_KEY")
        
        # Initialize embedding model
        try:
            self.embedding_model = SentenceTransformer(MODEL_NAME)
        except Exception as e:
            raise RuntimeError(f"Failed to initialize embedding model: {str(e)}")
        
        # Configure Gemini
        if self.gemini_api_key:
            genai.configure(api_key=self.gemini_api_key)
        
        # Start dataset loading in background
        self.load_dataset_in_background()
    
    def load_dataset_in_background(self):
        """Load dataset in a background thread"""
        def load_task():
            try:
                # Load dataset directly
                dataset = load_dataset(
                    DATASET_NAME,
                    split='train',
                    download_mode="force_redownload"  # Fixes extraction error
                )
                
                # Process dataset
                if 'text' in dataset.features:
                    self.chunks = dataset['text'][:1000]  # Limit to first 1000 entries
                elif 'context' in dataset.features:
                    self.chunks = dataset['context'][:1000]
                else:
                    raise ValueError("Dataset must have 'text' or 'context' field")
                
                # Create embeddings
                embeddings = self.embedding_model.encode(
                    self.chunks,
                    show_progress_bar=False,
                    convert_to_numpy=True
                )
                self.index = faiss.IndexFlatL2(embeddings.shape[1])
                self.index.add(embeddings.astype('float32'))
                
                self.dataset_loaded = True
            except Exception as e:
                self.loading_error = str(e)
                print(f"Dataset loading failed: {str(e)}")
        
        # Start the loading thread
        threading.Thread(target=load_task, daemon=True).start()
    
    def get_relevant_context(self, query: str) -> str:
        """Retrieve most relevant chunks"""
        if not self.index:
            return ""
            
        try:
            query_embed = self.embedding_model.encode(
                [query],
                convert_to_numpy=True
            ).astype('float32')
            
            _, indices = self.index.search(query_embed, k=TOP_K)
            return "\n\n".join([self.chunks[i] for i in indices[0] if i < len(self.chunks)])
        except Exception as e:
            print(f"Search error: {str(e)}")
            return ""

    def generate_response(self, query: str) -> str:
        """Generate response with robust error handling"""
        if not self.dataset_loaded:
            if self.loading_error:
                return f"⚠️ Dataset loading failed: {self.loading_error}"
            return "⚠️ Dataset is still loading, please wait..."
        if not self.gemini_api_key:
            return "🔑 Please set your Gemini API key in environment variables"
        
        context = self.get_relevant_context(query)
        if not context:
            return "No relevant context found"
        
        prompt = f"""Answer based on this context:
        {context}
        
        Question: {query}
        Answer concisely:"""
        
        try:
            model = genai.GenerativeModel(GENAI_MODEL)
            response = model.generate_content(prompt)
            return response.text
        except Exception as e:
            return f"⚠️ API Error: {str(e)}"

# Initialize system
try:
    rag_system = GeminiRAGSystem()
except Exception as e:
    raise RuntimeError(f"System initialization failed: {str(e)}")

# Create interface
with gr.Blocks(title="UE Chatbot") as app:
    gr.Markdown("# UE 24 Hour Service")
    
    with gr.Row():
        chatbot = gr.Chatbot(height=500, label="Chat History", 
                           avatar_images=(None, (None, "https://huggingface.co/spaces/groq/Groq-LLM/resolve/main/groq_logo.png")),
                           bubble_full_width=False)
    
    with gr.Row():
        query = gr.Textbox(label="Your question", 
                         placeholder="Ask your question...", 
                         scale=4)
        submit_btn = gr.Button("Submit", variant="primary", scale=1)
    
    with gr.Row():
        clear_btn = gr.Button("Clear Chat", variant="secondary")

    # Status indicator
    status = gr.Textbox(label="System Status", 
                       value="Initializing...",
                       interactive=False)

    # Update status periodically
    def update_status():
        if rag_system.loading_error:
            return f"Error: {rag_system.loading_error}"
        return "Ready" if rag_system.dataset_loaded else "Loading dataset..."
    
    app.load(update_status, None, status, every=1)

    # Event handlers
    def respond(message, chat_history):
        try:
            response = rag_system.generate_response(message)
            chat_history.append((message, response))
            return "", chat_history
        except Exception as e:
            chat_history.append((message, f"Error: {str(e)}"))
            return "", chat_history
    
    def clear_chat():
        return []
    
    submit_btn.click(respond, [query, chatbot], [query, chatbot])
    query.submit(respond, [query, chatbot], [query, chatbot])
    clear_btn.click(clear_chat, outputs=chatbot)

if __name__ == "__main__":
    app.launch(share=True)