ADKU commited on
Commit
313b367
Β·
verified Β·
1 Parent(s): 6fdc95d

for integration with react

Browse files
Files changed (1) hide show
  1. app.py +41 -26
app.py CHANGED
@@ -1,23 +1,39 @@
 
 
1
  import os
2
- import gradio as gr
3
  import google.generativeai as genai
4
  import faiss
5
  import numpy as np
6
  from sentence_transformers import SentenceTransformer
7
  from pymongo import MongoClient
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  # βœ… Configure Gemini API
10
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
11
 
12
- # βœ… Load Sentence Transformer Model
13
- model = SentenceTransformer('all-MiniLM-L6-v2')
14
 
15
- # βœ… Connect to MongoDB
16
  MONGO_URI = os.getenv("MONGO_URI")
17
  client = MongoClient(MONGO_URI)
18
  db = client["AiWork"]
19
 
20
- # βœ… Fetch latest data dynamically
 
 
 
21
  def fetch_latest_data():
22
  return {
23
  "users": list(db.users.find()),
@@ -29,6 +45,8 @@ def fetch_latest_data():
29
  }
30
 
31
  def generate_sentences(db):
 
 
32
  users, teams, projects, modules, documents, schedules = (
33
  db["users"], db["teams"], db["projects"], db["modules"], db["documents"], db["schedules"]
34
  )
@@ -99,8 +117,8 @@ def generate_sentences(db):
99
 
100
  return user_sentences
101
 
102
- # βœ… Update FAISS Index dynamically
103
  def update_faiss_index(user_sentences):
 
104
  faiss_indices = {}
105
  for email, categories in user_sentences.items():
106
  sentences = sum(categories.values(), [])
@@ -118,8 +136,8 @@ def update_faiss_index(user_sentences):
118
 
119
  return faiss_indices
120
 
121
- # βœ… Query FAISS Index
122
  def get_relevant_sentences(email, query, faiss_indices):
 
123
  if email not in faiss_indices:
124
  return ["User not found or no data available."]
125
 
@@ -138,31 +156,28 @@ def get_relevant_sentences(email, query, faiss_indices):
138
 
139
  return filtered_sentences if filtered_sentences else ["No relevant information found."]
140
 
141
- # βœ… Generate response using Gemini API
142
  def generate_response(email, query):
143
  filtered_sentences = get_relevant_sentences(email, query, faiss_indices)
144
-
145
- if filtered_sentences == ["No relevant information found."]:
146
- return "No relevant information found."
147
-
148
- prompt = f"Based on query '{query}', generate a short answer using:\n\n" + "\n".join(filtered_sentences)
149
  model = genai.GenerativeModel("gemini-1.5-flash")
150
  response = model.generate_content(prompt)
151
-
152
  return response.text
153
 
154
- # βœ… Real-time data update function
155
- def real_time_update():
156
- latest_data = fetch_latest_data()
157
- user_sentences = generate_sentences(latest_data)
158
- return update_faiss_index(user_sentences)
 
 
159
 
160
- # βœ… Run initial update
161
- faiss_indices = real_time_update()
 
162
 
163
- # βœ… Gradio Web UI
164
- def chat(email, query):
165
- return generate_response(email, query)
166
 
167
- iface = gr.Interface(fn=chat, inputs=["text", "text"], outputs="text", title="AI Workspace Assistant")
168
- iface.launch()
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
  import os
 
4
  import google.generativeai as genai
5
  import faiss
6
  import numpy as np
7
  from sentence_transformers import SentenceTransformer
8
  from pymongo import MongoClient
9
+ import uvicorn
10
+ from fastapi.middleware.cors import CORSMiddleware
11
+
12
+ app = FastAPI()
13
+
14
+ # CORS Middleware to allow frontend to access API
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"], # Allow all origins (React App)
18
+ allow_methods=["*"],
19
+ allow_headers=["*"],
20
+ )
21
 
22
  # βœ… Configure Gemini API
23
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
24
 
25
+ # βœ… Sentence Transformer
26
+ model = SentenceTransformer("all-MiniLM-L6-v2")
27
 
28
+ # βœ… MongoDB
29
  MONGO_URI = os.getenv("MONGO_URI")
30
  client = MongoClient(MONGO_URI)
31
  db = client["AiWork"]
32
 
33
+ class QueryRequest(BaseModel):
34
+ email: str
35
+ query: str
36
+
37
  def fetch_latest_data():
38
  return {
39
  "users": list(db.users.find()),
 
45
  }
46
 
47
  def generate_sentences(db):
48
+ # Your existing logic here...
49
+
50
  users, teams, projects, modules, documents, schedules = (
51
  db["users"], db["teams"], db["projects"], db["modules"], db["documents"], db["schedules"]
52
  )
 
117
 
118
  return user_sentences
119
 
 
120
  def update_faiss_index(user_sentences):
121
+ # Your existing FAISS logic here...
122
  faiss_indices = {}
123
  for email, categories in user_sentences.items():
124
  sentences = sum(categories.values(), [])
 
136
 
137
  return faiss_indices
138
 
 
139
  def get_relevant_sentences(email, query, faiss_indices):
140
+ # Your FAISS query logic here...
141
  if email not in faiss_indices:
142
  return ["User not found or no data available."]
143
 
 
156
 
157
  return filtered_sentences if filtered_sentences else ["No relevant information found."]
158
 
159
+
160
  def generate_response(email, query):
161
  filtered_sentences = get_relevant_sentences(email, query, faiss_indices)
162
+ prompt = f"Query: {query}\n\n" + "\n".join(filtered_sentences)
 
 
 
 
163
  model = genai.GenerativeModel("gemini-1.5-flash")
164
  response = model.generate_content(prompt)
 
165
  return response.text
166
 
167
+ @app.post("/chat")
168
+ async def chat(request: QueryRequest):
169
+ try:
170
+ response = generate_response(request.email, request.query)
171
+ return {"response": response}
172
+ except Exception as e:
173
+ raise HTTPException(status_code=500, detail=str(e))
174
 
175
+ @app.get("/")
176
+ def home():
177
+ return {"message": "AI Workspace Backend Running"}
178
 
179
+ # Initial Update
180
+ faiss_indices = update_faiss_index(generate_sentences(fetch_latest_data()))
 
181
 
182
+ if __name__ == "__main__":
183
+ uvicorn.run(app, host="0.0.0.0", port=7860)