lakshmivairamani commited on
Commit
71f20f2
1 Parent(s): a597f2c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -0
app.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from fastapi import FastAPI, File, UploadFile, HTTPException, APIRouter, Form, Request
4
+ from pydantic import BaseModel
5
+ from services.file_upload_service import FileHandler
6
+ from services.chat_service import ChatAgentService
7
+ from fastapi.staticfiles import StaticFiles
8
+ from fastapi.templating import Jinja2Templates
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from dotenv import load_dotenv
11
+
12
+ import mysql.connector
13
+
14
+ # Create the FastAPI app
15
+ app = FastAPI(title="RedmindGen", description="Chat with your Data", version="1.0.0")
16
+
17
+ # Load environment variables from .env file
18
+ load_dotenv()
19
+
20
+ # Get the path to the vector database
21
+ vector_db_path_documents = os.getenv('VECTOR_DB_PATH_DOCUMENTS')
22
+
23
+ # Mount static files
24
+ app.mount("/static", StaticFiles(directory="static"), name="static")
25
+
26
+ # Jinja2 templates
27
+ templates = Jinja2Templates(directory="templates")
28
+
29
+ #log handling
30
+ LOG_PATH = os.getenv('LOG_PATH')
31
+ LOG_FILENAME = "redmindgen.log"
32
+ full_log_path = os.path.join(LOG_PATH, LOG_FILENAME)
33
+ # Configure logging
34
+ logging.basicConfig(filename=full_log_path, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
35
+ logging.info("File upload start")
36
+
37
+ # Configure CORS
38
+ origins = [
39
+ "http://localhost:8000", # Adjust this to the origins you want to allow
40
+ "http://127.0.0.1:8000", # Example: Frontend running on a different port
41
+ "http://167.71.75.10:8003/"
42
+ ]
43
+
44
+ app.add_middleware(
45
+ CORSMiddleware,
46
+ allow_origins=origins, # Allows specified origins (use ["*"] for all origins)
47
+ allow_credentials=True,
48
+ allow_methods=["*"], # Allows all methods
49
+ allow_headers=["*"], # Allows all headers
50
+ )
51
+
52
+ @app.get("/")
53
+ async def read_root(request: Request):
54
+ """
55
+ Root endpoint that returns the index.html template.
56
+ """
57
+ return templates.TemplateResponse("index.html", {"request": request})
58
+
59
+ def verify_user(username: str, password: str):
60
+ """
61
+ Function to verify user credentials by checking the username and password in the database.
62
+ Returns "success" if the user is logged in, otherwise returns "failure".
63
+ """
64
+ # Connect to MySQL database
65
+ cnx = mysql.connector.connect(user='root', password='',
66
+ host='localhost',
67
+ database='redmind_gpt')
68
+
69
+ # Create a cursor object
70
+ cursor = cnx.cursor()
71
+
72
+ # Execute the query
73
+ query = "SELECT * FROM user_detail WHERE username = %s AND password = %s"
74
+ values = (username, password) # Replace with actual values from the front end
75
+ cursor.execute(query, values)
76
+
77
+ # Fetch the result
78
+ result = cursor.fetchone()
79
+
80
+ # Check if the result is not None
81
+ if result is not None:
82
+ # User is logged in
83
+ return "success"
84
+ else:
85
+ # User is not logged in
86
+ return "failure"
87
+
88
+ # Close the cursor and connection
89
+ cursor.close()
90
+ cnx.close()
91
+
92
+ @app.post("/validate-user")
93
+ async def validate_user(request: Request, username: str = Form(...), password: str = Form(...)):
94
+ """
95
+ Endpoint to validate user credentials.
96
+ If the credentials are valid, it returns the dashboard.html template.
97
+ Otherwise, it returns the index.html template.
98
+ """
99
+ status = verify_user(username, password)
100
+ if status == 'success':
101
+ return templates.TemplateResponse("dashboard.html", {"request": request, "username": username})
102
+ else:
103
+ return templates.TemplateResponse("index.html", {"request": request})
104
+
105
+ @app.get("/knowledgebase")
106
+ async def knowledgebase(request: Request):
107
+ """
108
+ Endpoint for the knowledgebase page.
109
+ Returns the knowledgebase.html template.
110
+ """
111
+ return templates.TemplateResponse("knowledgebase.html", {"request": request})
112
+
113
+ @app.get("/chatbot")
114
+ async def chatbot(request: Request):
115
+ """
116
+ Endpoint for the knowledgebase page.
117
+ Returns the knowledgebase.html template.
118
+ """
119
+ return templates.TemplateResponse("chatpage.html", {"request": request})
120
+
121
+ @app.get("/company_profile")
122
+ async def company_profile(request: Request):
123
+ """
124
+ Endpoint for the company profile page.
125
+ Returns the company_profile.html template.
126
+ """
127
+ return templates.TemplateResponse("company_profile.html", {"request": request})
128
+ @app.get("/data_connectors")
129
+ async def data_connectors(request: Request):
130
+ """
131
+ Endpoint for the company profile page.
132
+ Returns the company_profile.html template.
133
+ """
134
+ return templates.TemplateResponse("data_connectors.html", {"request": request})
135
+ @app.get("/API_connectors")
136
+ async def API_connectors(request: Request):
137
+ """
138
+ Endpoint for the company profile page.
139
+ Returns the company_profile.html template.
140
+ """
141
+ return templates.TemplateResponse("API_connectors.html", {"request": request})
142
+
143
+ @app.post("/upload_file/")
144
+ async def upload_file(
145
+ file: UploadFile = File(..., description="Upload a file"),
146
+ document_name: str = Form(..., description="The name of the document."),
147
+ document_description: str = Form(..., description="A brief description of the document."),
148
+ department: str = Form(..., description="The department associated with the document."),
149
+ version: str = Form(..., description="The version of the document."),
150
+ last_updated: str = Form(..., description="The date when the document was last updated.")
151
+ ):
152
+
153
+ """
154
+ Endpoint to handle file uploads.
155
+ It validates the file type and calls the FileHandler to handle the file upload.
156
+ Returns the result of the file upload."""
157
+ print("upload_file called")
158
+ allowed_extensions = {'txt', 'pdf', 'docx', 'csv', 'xlsx'}
159
+ if file.filename.split('.')[-1].lower() not in allowed_extensions:
160
+ raise HTTPException(status_code=400,
161
+ detail="Unsupported file type. Supported types: TXT, PDF, DOCX, CSV, XLSX.")
162
+
163
+ try:
164
+
165
+ file_handler = FileHandler(vector_db_path=vector_db_path_documents)
166
+ print(vector_db_path_documents)
167
+ result = await file_handler.handle_file_upload(file, document_name, document_description, department, version,
168
+ last_updated)
169
+ print("result")
170
+ return result
171
+ except Exception as e:
172
+ logging.error(f"Error handling file uploads: {str(e)}")
173
+ raise HTTPException(status_code=500, detail=str(e))
174
+
175
+ @app.post("/chat_with_agent")
176
+ async def chat_with_agent(request: Request, user_question: str = Form(...)):
177
+ """
178
+ Endpoint to chat with the chat agent.
179
+ It calls the ChatAgentService to get the answer to the user's question.
180
+ Returns the answer.
181
+ """
182
+ print(user_question)
183
+
184
+ chat_service = ChatAgentService()
185
+ try:
186
+ print("chat_with_agent called")
187
+ answer = chat_service.answer_question(user_question)
188
+ print("answer returned")
189
+ return answer
190
+ except Exception as e:
191
+ logging.error(f"Error in chat api: {str(e)}")
192
+ raise HTTPException(status_code=500, detail=str(e))
193
+
194
+
195
+