SAVAI123 commited on
Commit
8f8a72d
·
verified ·
1 Parent(s): 3f701a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +300 -180
app.py CHANGED
@@ -1,215 +1,335 @@
1
- #!/usr/bin/env python
2
- # coding: utf-8
3
-
4
- # In[144]:
5
-
6
-
7
- from langchain_google_genai import ChatGoogleGenerativeAI
8
- from langchain.prompts import PromptTemplate
9
- from langchain.chains import LLMChain
10
-
11
  import os
12
-
13
  import google.generativeai as genai
14
- from langchain.document_loaders import PyPDFLoader
15
- from langchain.text_splitter import RecursiveCharacterTextSplitter
16
  from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
17
- from langchain.vectorstores import FAISS
18
- import gradio as gr
19
-
20
-
21
- os.environ["MY_SECRET_KEY"] = "AIzaSyDRj3wAgqOCjc_D45W_u-G3y9dk5YDgxEo"
22
-
23
-
24
- # In[145]:
25
-
26
-
27
- #pip install pypdf
28
- #!pip install faiss-cpu
29
-
30
-
31
- # In[146]:
32
-
33
-
34
- google_api_key = os.environ["MY_SECRET_KEY"]
35
-
36
- # Check if the API key was found
37
- if google_api_key:
38
- # Set the environment variable if the API key was found
39
- os.environ["GOOGLE_API_KEY"] = google_api_key
40
-
41
- llm = ChatGoogleGenerativeAI(
42
- model="gemini-pro", # Specify the model name
43
- google_api_key=os.environ["GOOGLE_API_KEY"]
44
- )
45
- else:
46
- print("Error: GOOGLE_API_KEY not found in Colab secrets. Please store your API key.")
47
 
 
 
48
 
 
 
49
 
 
50
  genai.configure(api_key=google_api_key)
51
- model = genai.GenerativeModel("gemini-pro")
52
-
53
-
54
- # In[147]:
55
-
56
 
57
- work_dir=os.getcwd()
58
-
59
-
60
- # In[148]:
61
-
62
-
63
- # Verify file existence
64
- assert "RAG.pdf" in os.listdir(work_dir), "RAG.pdf not found in the specified directory!"
65
- print(f"Current Working Directory: {os.getcwd()}")
66
-
67
-
68
- # In[149]:
69
-
70
-
71
- # Load PDF and split text
72
- pdf_path = "RAG.pdf" # Ensure this file is uploaded to Colab
73
- loader = PyPDFLoader(pdf_path)
74
- documents = loader.load()
75
-
76
- # Split text into chunks
77
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=10)
78
- text_chunks = text_splitter.split_documents(documents)
79
-
80
-
81
- # In[150]:
82
-
83
-
84
- # Generate embeddings
85
- embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
86
-
87
- # Store embeddings in FAISS index
88
- vectorstore = FAISS.from_documents(text_chunks, embeddings)
89
- retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
90
-
91
-
92
- # In[151]:
93
-
94
-
95
- # Set up Gemini model
96
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-001", temperature=0)
97
- #llm = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0)
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
- # In[152]:
 
 
 
101
 
 
 
102
 
103
- import gradio as gr
104
- from langchain.prompts import PromptTemplate
105
- from langchain.chains import LLMChain
106
-
107
- def rag_query(query):
108
- # Retrieve relevant documents
109
- docs = retriever.get_relevant_documents(query)
110
 
111
- # Otherwise, use RAG
112
- context = "\n".join([doc.page_content for doc in docs])
113
- prompt = f"Context:\n{context}\n\nQuestion: {query}\nAnswer directly and concisely:"
 
 
 
 
 
 
114
 
 
 
115
  try:
116
- response = llm.invoke(prompt)
117
  except Exception as e:
118
- response = f"Error in RAG processing: {str(e)}"
119
-
120
- return response.content
121
-
122
 
 
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
- # In[153]:
126
-
127
-
128
- import gradio as gr
129
- from langchain.prompts import PromptTemplate
130
- from langchain.chains import LLMChain
131
- from langchain_google_genai import ChatGoogleGenerativeAI
132
-
133
- # Initialize LLM once (avoid repeated initialization)
134
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
135
 
136
- # Define the general query function
137
  def general_query(query):
 
 
 
 
 
 
138
  try:
139
- # Define the prompt correctly
140
- prompt = PromptTemplate.from_template("Answer the following query: {query}")
 
 
 
 
141
 
142
  # Create an LLM Chain
143
  chain = LLMChain(llm=llm, prompt=prompt)
144
 
145
- # Run chatbot and return response
146
- response = chain.run(query=query)
147
-
148
- return response # Return response directly (not response.content)
149
 
150
  except Exception as e:
151
- return f"Error: {str(e)}"
152
-
153
-
154
 
155
- # In[154]:
156
-
157
-
158
- import gradio as gr
159
-
160
-
161
- # Function to call the selected query method
162
- def query_router(query, method):
163
- if method == "Team Query": # Ensure exact match with dropdown options
164
- return rag_query(query)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  elif method == "General Query":
166
  return general_query(query)
167
  return "Invalid selection!"
168
 
169
- # Define local image paths
170
- logo_path = "Equinix-LOGO.jpeg" # Ensure this file exists
171
-
172
- # Custom CSS for background styling
173
- custom_css = """
174
- .gradio-container {
175
- background-color: #f0f0f0;
176
- text-align: center;
177
- }
178
- #logo img {
179
- display: block;
180
- margin: 0 auto;
181
- max-width: 200px; /* Adjust size */
182
- }
183
- """
184
-
185
- # Create Gradio UI
186
- with gr.Blocks(css=custom_css) as ui:
187
- gr.Image(logo_path, elem_id="logo", show_label=False, height=100, width=200) # Display Logo
188
-
189
- # Title & Description
190
- gr.Markdown("<h1 style='text-align: center; color: black;'>Equinix Chatbot for Automation Team</h1>")
191
- gr.Markdown("<p style='text-align: center; color: black;'>Ask me anything!</p>")
192
-
193
- # Input & Dropdown Section
194
- with gr.Row():
195
- query_input = gr.Textbox(label="Enter your query")
196
- query_method = gr.Dropdown(["Team Query", "General Query"], label="Select Query Type")
197
-
198
- # Button for submitting query
199
- submit_button = gr.Button("Submit")
200
-
201
- # Output Textbox
202
- output_box = gr.Textbox(label="Response", interactive=False)
203
-
204
- # Button Click Event
205
- submit_button.click(query_router, inputs=[query_input, query_method], outputs=output_box)
206
-
207
- # Launch UI
208
- ui.launch(share=True)
209
-
210
-
211
- # In[168]:
212
 
 
 
 
 
213
 
214
- get_ipython().system('jupyter nbconvert --to script GenAI_1.ipynb')
215
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import gradio as gr
3
  import google.generativeai as genai
 
 
4
  from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
5
+ from langchain_community.document_loaders import PyPDFLoader
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ from langchain_community.vectorstores import FAISS
8
+ from langchain.prompts import PromptTemplate
9
+ from langchain.chains import LLMChain
10
+ from datetime import datetime
11
+ import pytz
12
+ import time
13
+ import shutil
14
+ import numpy as np
15
+ import cv2
16
+ from PIL import Image, ImageEnhance, ImageFilter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ # Get API key from Hugging Face Spaces secrets
19
+ google_api_key = os.environ.get("GOOGLE_API_KEY")
20
 
21
+ if not google_api_key:
22
+ raise ValueError("GOOGLE_API_KEY not found in environment variables. Please add it to Hugging Face Space secrets.")
23
 
24
+ # Configure Google Generative AI
25
  genai.configure(api_key=google_api_key)
 
 
 
 
 
26
 
27
+ # Function to get current date and time
28
+ def get_current_datetime():
29
+ # Using UTC as default, but you can change to any timezone
30
+ utc_now = datetime.now(pytz.UTC)
31
+
32
+ # Convert to IST (Indian Standard Time) - modify as needed
33
+ ist_timezone = pytz.timezone('Asia/Kolkata')
34
+ ist_now = utc_now.astimezone(ist_timezone)
35
+
36
+ # Format the datetime
37
+ formatted_date = ist_now.strftime("%B %d, %Y")
38
+ formatted_time = ist_now.strftime("%I:%M:%S %p")
39
+
40
+ return formatted_date, formatted_time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ # Load PDF and create vector store
43
+ def initialize_retriever():
44
+ try:
45
+ # Get current directory
46
+ current_dir = os.getcwd()
47
+ print(f"Current working directory: {current_dir}")
48
+
49
+ # List files in current directory for debugging
50
+ print(f"Files in directory: {os.listdir(current_dir)}")
51
+
52
+ # Use absolute path for the PDF
53
+ pdf_path = os.path.join(current_dir, "Team1.pdf")
54
+ print(f"Attempting to load PDF from: {pdf_path}")
55
+
56
+ # Check if file exists
57
+ if not os.path.exists(pdf_path):
58
+ raise FileNotFoundError(f"The file {pdf_path} does not exist")
59
+
60
+ # Load PDF
61
+ loader = PyPDFLoader(pdf_path)
62
+ documents = loader.load()
63
+
64
+ print(f"Successfully loaded {len(documents)} pages from the PDF")
65
 
66
+ # Split text into chunks
67
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
68
+ text_chunks = text_splitter.split_documents(documents)
69
+ print(f"Split into {len(text_chunks)} text chunks")
70
 
71
+ # Generate embeddings
72
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
73
 
74
+ # Store embeddings in FAISS index
75
+ vectorstore = FAISS.from_documents(text_chunks, embeddings)
76
+ print("Successfully created vector store")
77
+ return vectorstore.as_retriever(search_kwargs={"k": 10})
 
 
 
78
 
79
+ except Exception as e:
80
+ print(f"Error in initialize_retriever: {str(e)}")
81
+ # Return a dummy retriever for graceful failure
82
+ class DummyRetriever:
83
+ def get_relevant_documents(self, query):
84
+ return []
85
+
86
+ print("Returning dummy retriever due to error")
87
+ return DummyRetriever()
88
 
89
+ # Initialize LLM
90
+ def get_llm():
91
  try:
92
+ return ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
93
  except Exception as e:
94
+ print(f"Error initializing LLM: {str(e)}")
95
+ return None
 
 
96
 
97
+ llm = get_llm()
98
 
99
+ # RAG query function
100
+ def rag_query(query, retriever):
101
+ if retriever is None:
102
+ return "Error: Could not initialize document retriever. Please check if Team1.pdf exists."
103
+
104
+ # Get current date and time for context
105
+ current_date, current_time = get_current_datetime()
106
+
107
+ try:
108
+ # Retrieve relevant documents
109
+ docs = retriever.get_relevant_documents(query)
110
+
111
+ if not docs:
112
+ return "No relevant information found in the document. Try a general query instead."
113
+
114
+ # Create context from retrieved documents
115
+ context = "\n".join([doc.page_content for doc in docs])
116
+ prompt = f"""Context:\n{context}
117
+ Current Date: {current_date}
118
+ Current Time: {current_time}
119
+ Question: {query}
120
+ Answer directly and concisely, using the current date and time information if relevant:"""
121
 
122
+ response = llm.invoke(prompt)
123
+ return response.content
124
+ except Exception as e:
125
+ return f"Error in RAG processing: {str(e)}"
 
 
 
 
 
 
126
 
127
+ # General query function
128
  def general_query(query):
129
+ if llm is None:
130
+ return "Error: Could not initialize language model. Please check your API key."
131
+
132
+ # Get current date and time for context
133
+ current_date, current_time = get_current_datetime()
134
+
135
  try:
136
+ # Define the prompt with date and time context
137
+ prompt_template = """Current Date: {date}
138
+ Current Time: {time}
139
+ Answer the following query, using the current date and time information if relevant: {query}"""
140
+
141
+ prompt = PromptTemplate.from_template(prompt_template)
142
 
143
  # Create an LLM Chain
144
  chain = LLMChain(llm=llm, prompt=prompt)
145
 
146
+ # Run chatbot and get response
147
+ response = chain.run(date=current_date, time=current_time, query=query)
148
+ return response
 
149
 
150
  except Exception as e:
151
+ return f"Error in general query: {str(e)}"
 
 
152
 
153
+ # Function to make a person look younger in an image
154
+ def make_younger(input_image, youth_level=50):
155
+ try:
156
+ if input_image is None:
157
+ return None, "No image uploaded. Please upload an image first."
158
+
159
+ # Convert to PIL Image if necessary
160
+ if isinstance(input_image, np.ndarray):
161
+ input_image = Image.fromarray(input_image.astype('uint8'))
162
+
163
+ # Youth level should be between 0 and 100
164
+ youth_level = max(0, min(100, youth_level))
165
+
166
+ # Apply a series of transformations to make the person look younger
167
+
168
+ # 1. Smooth skin (reduce wrinkles)
169
+ smoothing_factor = youth_level / 100
170
+ smoothed = input_image.filter(ImageFilter.GaussianBlur(radius=smoothing_factor * 1.5))
171
+
172
+ # 2. Enhance brightness slightly (younger skin tends to be brighter)
173
+ brightness_enhancer = ImageEnhance.Brightness(smoothed)
174
+ brightened = brightness_enhancer.enhance(1 + (smoothing_factor * 0.2))
175
+
176
+ # 3. Enhance color (more vibrant)
177
+ color_enhancer = ImageEnhance.Color(brightened)
178
+ colored = color_enhancer.enhance(1 + (smoothing_factor * 0.3))
179
+
180
+ # 4. Adjust contrast (younger skin has better contrast)
181
+ contrast_enhancer = ImageEnhance.Contrast(colored)
182
+ contrasted = contrast_enhancer.enhance(1 + (smoothing_factor * 0.1))
183
+
184
+ # 5. Sharpen to maintain some details
185
+ sharpened = contrasted.filter(ImageFilter.SHARPEN)
186
+
187
+ return sharpened, f"Image processed successfully! Youth level applied: {youth_level}%"
188
+
189
+ except Exception as e:
190
+ return None, f"Error processing image: {str(e)}"
191
+
192
+ # Function to handle the case when no PDF is found
193
+ def file_not_found_message():
194
+ return ("The Team1.pdf file could not be found. Team Query mode will not work properly. "
195
+ "Please ensure the PDF is correctly uploaded to the Hugging Face Space.")
196
+
197
+ # Query router function
198
+ def query_router(query, method, retriever):
199
+ if method == "Team Query":
200
+ if isinstance(retriever, type) or retriever is None:
201
+ return file_not_found_message()
202
+ return rag_query(query, retriever)
203
  elif method == "General Query":
204
  return general_query(query)
205
  return "Invalid selection!"
206
 
207
+ # Function to reset input and output
208
+ def reset_query_field():
209
+ return "", "" # Reset only the query input
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
 
211
+ # Function to update the clock
212
+ def update_datetime():
213
+ date, time = get_current_datetime()
214
+ return date, time
215
 
216
+ # Main function to create and launch the Gradio interface
217
+ def main():
218
+ # Initialize retriever
219
+ print("Initializing retriever...")
220
+ retriever = initialize_retriever()
221
+
222
+ # Define local image paths
223
+ logo_path = "Equinix-LOGO.jpeg" # Ensure this file exists
224
+
225
+ # Custom CSS for background styling
226
+ custom_css = """
227
+ .gradio-container {
228
+ background-color: #f0f0f0;
229
+ text-align: center;
230
+ }
231
+ #logo img {
232
+ display: block;
233
+ margin: 0 auto;
234
+ max-width: 200px; /* Adjust size */
235
+ }
236
+ /* Hide download buttons and controls */
237
+ .download-button {
238
+ display: none !important;
239
+ }
240
+ /* Hide other download options */
241
+ .file-preview .download {
242
+ display: none !important;
243
+ }
244
+ /* Hide the three dots menu that might contain download options */
245
+ .icon-button.secondary {
246
+ display: none !important;
247
+ }
248
+ .tab-selected {
249
+ background-color: #e6f7ff;
250
+ border-bottom: 2px solid #1890ff;
251
+ }
252
+ """
253
+
254
+ # Create the Gradio interface using Blocks
255
+ with gr.Blocks(css=custom_css) as demo:
256
+ gr.Image(logo_path, elem_id="logo", show_label=False, height=100, width=400, show_download_button=False)
257
+
258
+ # Title & Description
259
+ gr.Markdown("<h1 style='text-align: center; color: black;'>Equinix Chatbot for Automation Team</h1>")
260
+
261
+ # Create tabs for different functionalities
262
+ with gr.Tabs() as tabs:
263
+ with gr.TabItem("Chat Assistant", id="chat_tab"):
264
+ # Date and Time Display
265
+ with gr.Row(elem_classes="datetime-display"):
266
+ date_display = gr.Textbox(label="Date", interactive=False)
267
+ time_display = gr.Textbox(label="Time", interactive=False)
268
+
269
+ # Add refresh button for time
270
+ refresh_btn = gr.Button("Update Date & Time")
271
+ refresh_btn.click(fn=update_datetime, inputs=[], outputs=[date_display, time_display])
272
+
273
+ gr.Markdown("<p style='text-align: center; color: black;'>Ask me anything!</p>")
274
+
275
+ # Input & Dropdown Section
276
+ with gr.Row():
277
+ query_input = gr.Textbox(label="Enter your query")
278
+ query_method = gr.Dropdown(["Team Query", "General Query"], label="Select Query Type", value="Team Query")
279
+
280
+ # Output Textbox
281
+ output_box = gr.Textbox(label="Response", interactive=False)
282
+
283
+ # Buttons Section
284
+ with gr.Row():
285
+ submit_button = gr.Button("Submit")
286
+ reset_button = gr.Button("Reset Query")
287
+
288
+ # Button Click Events
289
+ submit_button.click(
290
+ lambda query, method: query_router(query, method, retriever),
291
+ inputs=[query_input, query_method],
292
+ outputs=output_box
293
+ )
294
+
295
+ # Reset only the query input
296
+ reset_button.click(reset_query_field, inputs=[], outputs=[query_input, output_box])
297
+
298
+ # Update date and time on submission
299
+ submit_button.click(
300
+ fn=update_datetime,
301
+ inputs=[],
302
+ outputs=[date_display, time_display]
303
+ )
304
+
305
+ # Initialize date and time values
306
+ date_val, time_val = get_current_datetime()
307
+ date_display.value = date_val
308
+ time_display.value = time_val
309
+
310
+ # Add a new tab for the image age modification feature
311
+ with gr.TabItem("Age Modification", id="age_mod_tab"):
312
+ gr.Markdown("<h2 style='text-align: center; color: black;'>Make Person Look Younger</h2>")
313
+ gr.Markdown("<p style='text-align: center; color: black;'>Upload an image to make the person look younger.</p>")
314
+
315
+ with gr.Row():
316
+ input_image = gr.Image(label="Upload Image", type="pil")
317
+ output_image = gr.Image(label="Younger Version", show_download_button=False)
318
+
319
+ with gr.Row():
320
+ youth_slider = gr.Slider(minimum=0, maximum=100, value=50, step=5, label="Youth Level (%)")
321
+ process_button = gr.Button("Make Younger")
322
+
323
+ result_text = gr.Textbox(label="Processing Result", interactive=False)
324
+
325
+ process_button.click(
326
+ fn=make_younger,
327
+ inputs=[input_image, youth_slider],
328
+ outputs=[output_image, result_text]
329
+ )
330
+
331
+ # Launch the interface
332
+ demo.launch(share=True)
333
+
334
+ if __name__ == "__main__":
335
+ main()