Redmind commited on
Commit
253c66c
·
verified ·
1 Parent(s): f2d12d5

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1511
app.py DELETED
@@ -1,1511 +0,0 @@
1
- import json
2
- import os
3
- import logging
4
- import shutil
5
- import asyncpg
6
- from fastapi import FastAPI, File, Query,Form, Request, HTTPException, UploadFile
7
- from fastapi.responses import JSONResponse, RedirectResponse
8
- from fastapi.staticfiles import StaticFiles
9
- from fastapi.templating import Jinja2Templates
10
- from fastapi.middleware.cors import CORSMiddleware
11
- from dotenv import load_dotenv
12
- import mysql.connector
13
- from typing import List
14
- from pydantic import BaseModel
15
- import psycopg2
16
-
17
-
18
-
19
- # Load environment variables
20
- load_dotenv()
21
-
22
- # Configure logging
23
- logging.basicConfig(
24
- level=logging.INFO,
25
- format='%(asctime)s - %(levelname)s - %(message)s',
26
- handlers=[
27
- logging.FileHandler("redmindgen.log"),
28
- logging.StreamHandler() # This ensures logging to console
29
- ]
30
- )
31
- logging.info("Application startup")
32
-
33
- # Create the FastAPI app
34
- app = FastAPI(title="RedmindGen", description="Chat with your Data", version="1.0.0")
35
-
36
- # Mount static files
37
- app.mount("/static", StaticFiles(directory="static"), name="static")
38
-
39
- # Jinja2 templates
40
- templates = Jinja2Templates(directory="templates")
41
-
42
- # Configure CORS
43
- origins = [
44
- "http://localhost:8000",
45
- "http://127.0.0.1:8000",
46
- "http://167.71.75.10:8003/"
47
- ]
48
-
49
- app.add_middleware(
50
- CORSMiddleware,
51
- allow_origins=origins,
52
- allow_credentials=True,
53
- allow_methods=["*"],
54
- allow_headers=["*"],
55
- )
56
- DB_USER = 'u852023448_redmindgpt'
57
- DB_PASSWORD = 'redmindGpt@123'
58
- DB_HOST = '217.21.88.10'
59
- DB_NAME = 'u852023448_redmindgpt'
60
- from pydantic import BaseModel
61
- class DatabaseConnection(BaseModel):
62
- database_type: str
63
- server: str
64
- port: str
65
- databaseName: str
66
- username: str
67
- password: str
68
- @app.post("/api/connect")
69
- async def connect_to_database(connection: DatabaseConnection):
70
- try:
71
- print(f"Attempting to connect to database: {connection.database_type}")
72
- if connection.database_type == "Postgres":
73
- print(f"PostgreSQL connection details - Host: {connection.server}, Port: {connection.port}, Database: {connection.databaseName}, User: {connection.username}")
74
- conn = psycopg2.connect(
75
- host=connection.server,
76
- port=connection.port,
77
- database=connection.databaseName,
78
- user=connection.username,
79
- password=connection.password
80
- )
81
- query_schemas = "SELECT schema_name FROM information_schema.schemata"
82
- query_tables = "SELECT table_name FROM information_schema.tables WHERE table_schema = %s"
83
- elif connection.database_type == "mysql":
84
- print(f"inside mysql",connection.server,connection.port,connection.databaseName,connection.username,connection.password)
85
- conn = mysql.connector.connect(
86
- host=connection.server,
87
- port=connection.port,
88
- database=connection.databaseName,
89
- user=connection.username,
90
- password=connection.password
91
- )
92
- query_schemas = "SELECT schema_name FROM information_schema.schemata"
93
- query_tables = "SELECT table_name FROM information_schema.tables WHERE table_schema = %s"
94
- else:
95
- raise HTTPException(status_code=400, detail="Unsupported database type")
96
-
97
- cursor = conn.cursor()
98
-
99
- # Fetch all schemas
100
- cursor.execute(query_schemas)
101
- schemas = cursor.fetchall()
102
-
103
- # Fetch all tables within each schema
104
- schema_tables = {}
105
- for schema in schemas:
106
- cursor.execute(query_tables, (schema[0],))
107
- tables = cursor.fetchall()
108
- schema_tables[schema[0]] = [table[0] for table in tables]
109
-
110
- cursor.close()
111
- conn.close()
112
-
113
- return {"schemas": [schema[0] for schema in schemas], "schema_tables": schema_tables, "success": True}
114
-
115
- except Exception as e:
116
- raise HTTPException(status_code=500, detail=str(e))
117
-
118
- # Function to create a new database connection for MySQL (Example)
119
- def get_db_connection():
120
- try:
121
- cnx = mysql.connector.connect(user=DB_USER, password=DB_PASSWORD, host=DB_HOST, database=DB_NAME)
122
- return cnx
123
- except mysql.connector.Error as err:
124
- logging.error(f"Database connection error: {err}")
125
- return None
126
- # Function to create a new database connection for MySQL (Example)
127
- def get_db_connection():
128
- try:
129
- cnx = mysql.connector.connect(user=DB_USER, password=DB_PASSWORD, host=DB_HOST, database=DB_NAME)
130
- return cnx
131
- except mysql.connector.Error as err:
132
- logging.error(f"Database connection error: {err}")
133
- return None
134
-
135
- @app.get("/")
136
- async def read_root(request: Request):
137
- return templates.TemplateResponse("index.html", {"request": request})
138
-
139
- def verify_user(username: str, password: str):
140
- try:
141
- cnx = get_db_connection()
142
- cursor = cnx.cursor()
143
- query = "SELECT role,company_id FROM user_detail WHERE username = %s AND password = %s"
144
- values = (username, password)
145
- cursor.execute(query, values)
146
- result = cursor.fetchone()
147
- cursor.close()
148
- cnx.close()
149
- if result is not None:
150
- logging.info(f"User {username}{result[1]} logged in successfully")
151
- return "success",result[0],result[1]
152
- else:
153
- logging.info(f"User {username} login failed")
154
- return "failure"
155
- except mysql.connector.Error as err:
156
- logging.error(f"Database error: {err}")
157
- return "failure"
158
-
159
- @app.post("/validate-user")
160
- async def validate_user(request: Request, username: str = Form(...), password: str = Form(...)):
161
- status, role ,company_id= verify_user(username, password)
162
- if status == 'success' and role and company_id:
163
- logging.info(f"user role {role} is returned")
164
-
165
- # Set cookies and redirect to the dashboard
166
- response = RedirectResponse(url="/dashboard", status_code=302)
167
- response.set_cookie(key="role", value=role)
168
- response.set_cookie(key="username", value=username)
169
- response.set_cookie(key="company_id",value=company_id)
170
- return response
171
- else:
172
- # If login fails, redirect back to the index page with an error message
173
- return templates.TemplateResponse("index.html", {
174
- "request": request,
175
- "error": "Invalid username or password"
176
- })
177
-
178
- @app.post("/submit_company_profile")
179
- async def submit_company_profile(request: Request,
180
- company_name: str = Form(...),
181
- company_code: str = Form(...),
182
- domain: str = Form(...),
183
- llm_tools: List[str] = Form(...),
184
- username:str=Form(...),
185
- password:str=Form(...),
186
- role:str=Form(...)):
187
- logging.info("Received form submission for company profile")
188
- logging.info(f"Form data - company_name: {company_name}, company_code: {company_code}, domain: {domain}, llm_tools: {llm_tools}")
189
-
190
- try:
191
- cnx = get_db_connection()
192
- cursor = cnx.cursor()
193
- query = "INSERT INTO company_detail (company_name, company_code, domain, llm_tools) VALUES (%s, %s, %s, %s)"
194
- values = (company_name, company_code, domain, ",".join(llm_tools))
195
- logging.info(f"Executing query: {query} with values: {values}")
196
- cursor.execute(query, values)
197
- # Retrieve the inserted company_id
198
- company_id = cursor.lastrowid
199
- logging.info(f"Company profile for {company_name} inserted successfully with company_id: {company_id}")
200
-
201
- # Insert user details with the retrieved company_id
202
- user_query = "INSERT INTO user_detail (company_id, username, password,role) VALUES (%s, %s, %s, %s)"
203
- user_values = (company_id, username, password, role)
204
- logging.info(f"Executing user detail query: {user_query} with values: {user_values}")
205
- cursor.execute(user_query, user_values)
206
- cnx.commit()
207
- logging.info(f"Query executed successfully, {cursor.rowcount} row(s) affected")
208
- cursor.close()
209
- cnx.close()
210
- logging.info(f"Company profile for {company_name} inserted successfully")
211
- RedirectResponse(url="/company_profile?message=Data saved successfully", status_code=302)
212
- except mysql.connector.Error as err:
213
- logging.error(f"Database error: {err}")
214
- raise HTTPException(status_code=500, detail="Internal Server Error")
215
-
216
-
217
- @app.get("/api/companies")
218
- async def get_companies():
219
- try:
220
- cnx = get_db_connection()
221
- cursor = cnx.cursor()
222
- query = "SELECT company_name FROM company_detail "
223
- cursor.execute(query)
224
- companies = cursor.fetchall()
225
- cursor.close()
226
- cnx.close()
227
- return {"companies": [{"name": company[0]} for company in companies]}
228
- except mysql.connector.Error as err:
229
- logging.error(f"Database error: {err}")
230
- raise HTTPException(status_code=500, detail="Internal Server Error")
231
-
232
- @app.get("/dashboard")
233
- async def dashboard(request: Request):
234
- try:
235
- # Retrieve cookies
236
- role = request.cookies.get("role")
237
- username = request.cookies.get("username")
238
- company_id=request._cookies.get("company_id")
239
-
240
- # Establish database connection
241
- cnx = get_db_connection()
242
- cursor = cnx.cursor()
243
-
244
- # Fetch all table names
245
- cursor.execute("SHOW TABLES")
246
- all_tables = cursor.fetchall()
247
-
248
- # Dictionary to hold the count of records for each table
249
- table_count_of_each_table = {}
250
-
251
- # Fetch count of records for each table
252
- for table in all_tables:
253
- table_name = table[0]
254
- print(table_name)
255
- if table_name != "user_feedback":
256
- query = f"SELECT COUNT(*) FROM {table_name} WHERE company_id = %s"
257
- cursor.execute(query, (company_id,))
258
-
259
- count = cursor.fetchone()[0]
260
- table_count_of_each_table[table_name] = count
261
- query1=f"select company_name from company_detail where company_id = %s"
262
- cursor.execute(query1,(company_id,))
263
- company_name_result = cursor.fetchone()
264
-
265
- # Check if company_name_result is not None
266
- if company_name_result:
267
- company_name = company_name_result[0]
268
- else:
269
- company_name = "Unknown" # Default
270
- # Close cursor and connection
271
- cursor.close()
272
- cnx.close()
273
-
274
- # Log the counts for debugging purposes
275
- logging.info(table_count_of_each_table)
276
-
277
- # Render the template with the data, role, and username
278
- return templates.TemplateResponse("dashboard.html", {
279
- "request": request,
280
- "title": "Dashboard",
281
- "table_count_of_each_table": table_count_of_each_table,
282
- "role": role,
283
- "username": username,
284
- "company_id":company_id,
285
- "company_name":company_name
286
- })
287
- except mysql.connector.Error as err:
288
- # Log the error and raise an HTTPException
289
- logging.error(f"Database error: {err}")
290
- raise HTTPException(status_code=500, detail="Internal Server Error")
291
-
292
- @app.get("/api/company_record_count/{company_id}")
293
- async def get_company_record_count(company_id: int):
294
- try:
295
- # Establish database connection
296
- cnx = get_db_connection()
297
- cursor = cnx.cursor()
298
-
299
- # List of tables to count records in
300
- tables = ["knowledge_base", "data_connectors", "api_connectors", "prompt_templates"]
301
-
302
- # Dictionary to hold the count of records for each table
303
- table_counts = {}
304
-
305
- # Fetch count of records for the selected company in each table
306
- for table in tables:
307
- query = f"SELECT COUNT(*) FROM {table} WHERE company_id = %s"
308
- cursor.execute(query, (company_id,))
309
- count = cursor.fetchone()[0]
310
- table_counts[table] = count
311
-
312
- # Close cursor and connection
313
- cursor.close()
314
- cnx.close()
315
-
316
- return {"table_counts": table_counts}
317
-
318
- except mysql.connector.Error as err:
319
- logging.error(f"Database error: {err}")
320
- raise HTTPException(status_code=500, detail="Internal Server Error")
321
-
322
-
323
- @app.get("/company_profile")
324
- async def company_profile(request: Request):
325
- try:
326
- # Retrieve cookies
327
- role = request.cookies.get("role")
328
- company_id = request.cookies.get("company_id")
329
-
330
- # Render the template with the role and company_id
331
- return templates.TemplateResponse("company_profile.html", {
332
- "request": request,
333
- "role": role,
334
- "company_id": company_id,
335
- "title":"Company Profile"
336
- })
337
- except Exception as e:
338
- # Handle exceptions
339
- logging.error(f"Error: {e}")
340
- raise HTTPException(status_code=500, detail="Internal Server Error")
341
- #return templates.TemplateResponse("company_profile.html", {"request": request,"title":"Company Profile"})
342
- @app.get("/api/company_id")
343
- async def get_company_id(company_name: str):
344
- print(f"Received company_name: {company_name}") # Debug statement
345
- logging.info(f"Received request for company name: {company_name}")
346
- try:
347
- cnx = get_db_connection()
348
- cursor = cnx.cursor()
349
- query = "SELECT * FROM company_detail WHERE company_name = %s"
350
- cursor.execute(query, (company_name,))
351
- result = cursor.fetchone()
352
- cursor.close()
353
- cnx.close()
354
-
355
- if result:
356
- llm_tools = result[4].split(',') if result[4] else []
357
- return {"company_id": result[0],
358
- "company_name":result[1],
359
- "company_code":result[2],
360
- "domain":result[3],
361
- "llm_tools":llm_tools
362
- }
363
- else:
364
- logging.error(f"Company not found for name: {company_name}")
365
- raise HTTPException(status_code=404, detail="Company not found")
366
- except mysql.connector.Error as err:
367
- logging.error(f"Database error: {err}")
368
- raise HTTPException(status_code=500, detail="Internal Server Error")
369
-
370
- @app.get("/api/companydetails")
371
- async def get_companies():
372
- print(f"Received company_name") # Debug statement
373
- logging.info(f"Received request for company name")
374
-
375
- try:
376
- cnx = get_db_connection()
377
- cursor = cnx.cursor()
378
- query = "SELECT * FROM company_detail"
379
- cursor.execute(query)
380
- result = cursor.fetchall()
381
- logging.info(f"Query result: {result}")
382
- cursor.close()
383
- cnx.close()
384
-
385
- companies = []
386
- for row in result:
387
- llm_tools = row[4].split(',') if row[4] else []
388
- logging.info(row[4])
389
- companies.append({
390
- "company_id": row[0],
391
- "company_name": row[1],
392
- "company_code": row[2],
393
- "domain": row[3],
394
- "llm_tools": row[4]
395
- })
396
-
397
- if companies:
398
- return companies
399
- else:
400
- logging.error(f"Company not found for name: {result[1]}")
401
- raise HTTPException(status_code=404, detail="Company not found")
402
- except mysql.connector.Error as err:
403
- logging.error(f"Database error: {err}")
404
- raise HTTPException(status_code=500, detail="Internal Server Error")
405
-
406
- #to view the details
407
- @app.get("/api/getcompanydetails/{company_id}")
408
- async def get_company_details(company_id: int):
409
- company = await get_company_from_db(company_id)
410
- if not company:
411
- raise HTTPException(status_code=404, detail="Company not found")
412
- return company
413
-
414
- async def get_company_from_db(company_id: int):
415
- try:
416
- # Establish a connection to the database
417
- cnx = get_db_connection()
418
- if cnx is None:
419
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
420
- cursor = cnx.cursor(dictionary=True)
421
- query = "SELECT * FROM company_detail WHERE company_id = %s"
422
- cursor.execute(query, (company_id,))
423
- company = cursor.fetchone()
424
- cursor.close()
425
- cnx.close()
426
- return company
427
- except mysql.connector.Error as err:
428
- logging.error(f"Error fetching company: {err}")
429
- raise HTTPException(status_code=500, detail="Failed to fetch company")
430
- # to edit the details
431
- @app.put("/api/putcompanydetails/{company_id}")
432
- async def update_company_details(company_id: int,
433
- company_name: str = Form(...),
434
- company_code: str = Form(...),
435
- domain: str = Form(...),
436
- llm_tools: List[str] = Form(...)):
437
- print(f"Received company_id",company_id) # Debug statement
438
- logging.info(f"Received request for company data")
439
- company_data = {
440
- 'company_name': company_name,
441
- 'company_code': company_code,
442
- 'domain': domain,
443
- 'llm_tools': ','.join(llm_tools)
444
- }
445
- updated_company = await update_company_in_db(company_id, company_data)
446
- if not updated_company:
447
- raise HTTPException(status_code=500, detail="Failed to update company")
448
- return updated_company
449
-
450
- async def update_company_in_db(company_id: int, company_data: dict):
451
- try:
452
- print(f"Received company_nid inside function",company_id) # Debug statement
453
- logging.info(f"Received request for company name")
454
- cnx = get_db_connection()
455
- if cnx is None:
456
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
457
- cursor = cnx.cursor()
458
- update_query = """
459
- UPDATE u852023448_redmind.gptcompany_detail cd
460
- SET cd.company_name = %s, cd.company_code = %s, cd.domain = %s, cd.llm_tools = %s
461
- WHERE cd.company_id = %s;
462
- """
463
- logging.info(f"Executing query: {update_query} with company_id: {company_id}")
464
- params = (company_id,company_data)
465
- logging.info(f"Query parameters: {params}")
466
- print(f"Query parameters: {params}")
467
-
468
-
469
- cursor.execute(update_query, (
470
- company_data['company_name'],
471
- company_data['company_code'],
472
- company_data['domain'],
473
- company_data['llm_tools'],
474
- company_id
475
- ))
476
-
477
- cnx.commit()
478
- success = cursor.rowcount > 0
479
- cursor.close()
480
- cnx.close()
481
- if not success:
482
- return None
483
- return company_data
484
- except mysql.connector.Error as err:
485
- logging.error(f"Error updating company: {err}")
486
- raise HTTPException(status_code=500, detail="Failed to update company")
487
-
488
-
489
- def delete_company_from_db(company_id: int) -> bool:
490
- print(f"Received company_name: {company_id}") # Debug statement
491
- logging.info(f"Received request for company name: {company_id}")
492
- try:
493
- # Establish a connection to the database
494
- cnx = get_db_connection()
495
- if cnx is None:
496
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
497
- cursor = cnx.cursor()
498
- delete_query = "DELETE FROM company_detail WHERE company_id = %s"
499
- cursor.execute(delete_query, (company_id,))
500
- cnx.commit()
501
- success = cursor.rowcount > 0
502
- cursor.close()
503
- cnx.close()
504
- return success
505
- except mysql.connector.Error as err:
506
- logging.error(f"Error deleting company: {err}")
507
- raise HTTPException(status_code=500, detail="Failed to delete company")
508
- @app.delete("/api/delcompanydetails/{company_id}")
509
- async def delete_company(company_id: int):
510
- deletion_success = delete_company_from_db(company_id)
511
- if not deletion_success:
512
- raise HTTPException(status_code=404, detail="Company not found or failed to delete")
513
- return {"message": "Company deleted successfully"}
514
-
515
- @app.get("/knowledgebase")
516
- async def knowledgebase(request: Request):
517
- try:
518
- # Retrieve cookies
519
- role = request.cookies.get("role")
520
- company_id = request.cookies.get("company_id")
521
-
522
- # Render the template with the role and company_id
523
- return templates.TemplateResponse("knowledgebase.html", {
524
- "request": request,
525
- "role": role,
526
- "company_id": company_id,
527
- "title":"KnowledgeBase"
528
- })
529
- except Exception as e:
530
- # Handle exceptions
531
- logging.error(f"Error: {e}")
532
- raise HTTPException(status_code=500, detail="Internal Server Error")
533
-
534
-
535
- #to insert into knowledgebase
536
- @app.post("/upload_document")
537
- async def upload_document(
538
- request: Request,
539
- company_id:str=Form(...),
540
- uploadFile: UploadFile = File(...),
541
- documentName: str = Form(...),
542
- documentDescription: str = Form(...),
543
- department: str = Form(...),
544
- vectorDBflag:str=Form(...),
545
- version: str = Form(...),
546
- lastUpdated: str = Form(...)
547
- ):
548
- try:
549
- # Save the uploaded file
550
- upload_folder = "uploads/"
551
- os.makedirs(upload_folder, exist_ok=True)
552
- file_path = os.path.join(upload_folder, uploadFile.filename)
553
-
554
- with open(file_path, "wb") as buffer:
555
- shutil.copyfileobj(uploadFile.file, buffer)
556
-
557
- # Save the details to the database
558
- cnx = get_db_connection()
559
- cursor = cnx.cursor()
560
- query = """
561
- INSERT INTO knowledge_base (company_id,file_path, document_name, document_desc, department, version,vectorDBflag, last_updated)
562
- VALUES (%s,%s, %s, %s, %s, %s,%s, %s)
563
- """
564
- values = (company_id,file_path, documentName, documentDescription, department, version,vectorDBflag, lastUpdated)
565
- cursor.execute(query, values)
566
- cnx.commit()
567
- row_id=cursor.lastrowid
568
- cursor.close()
569
- cnx.close()
570
-
571
- logging.info(f"Document {documentName} uploaded successfully")
572
- return JSONResponse(status_code=200, content={"message": "Data saved successfully", "row_id": row_id})
573
- #return RedirectResponse(url="/knowledgebase", status_code=302)
574
- except mysql.connector.Error as err:
575
- logging.error(f"Database error: {err}")
576
- raise HTTPException(status_code=500, detail="Internal Server Error")
577
-
578
- #to retrieve from knowledgebase
579
- @app.get("/api/document_upload")
580
- async def get_document(company_id: str = Query(...)):
581
- print(f"Received companyId and name: {company_id}") # Log rec
582
- #async def get_data_connectors(company_id: str, company_name: str):
583
- logging.info(f"Received request for company_id and company_id: {company_id}")
584
- try:
585
- cnx = get_db_connection()
586
- cursor = cnx.cursor()
587
- query = """
588
- SELECT kb.kid,kb.company_id, kb.file_path, kb.document_name, kb.document_desc,kb.department,kb.version,kb.vectorDBflag,kb.last_updated
589
- FROM u852023448_redmindgpt.knowledge_base kb
590
- JOIN u852023448_redmindgpt.company_detail cd ON kb.company_id = cd.company_id
591
- WHERE kb.company_id = %s
592
- """
593
- logging.info(f"Executing query: {query} with company_id: {company_id}")
594
- params = (company_id,)
595
- logging.info(f"Query parameters: {params}")
596
- print(f"Query parameters: {params}")
597
-
598
- cursor.execute(query, params) # Pa
599
- result = cursor.fetchall()
600
- logging.info(f"Query result: {result}")
601
- cursor.close
602
- cnx.close()
603
- companies=[]
604
- for row in result:
605
-
606
- companies.append({
607
- "row_id":row[0],
608
- "company_id": row[1],
609
- "file_path":row[2],
610
- "document_name": row[3],
611
- "document_desc": row[4],
612
- "department": row[5],
613
- "version": row[6],
614
- "vectorDBflag":row[7],
615
- "last_updated": row[8]
616
- })
617
- if companies:
618
- return companies
619
- else:
620
- logging.warning(f"No document found for company_id: {company_id}")
621
- raise HTTPException(status_code=404, detail="Data document not found")
622
- except mysql.connector.Error as err:
623
- logging.error(f"Database error: {err}")
624
- raise HTTPException(status_code=500, detail="Internal Server Error")
625
-
626
- #on update of modal form the data table is refresh the value in datatable
627
- @app.get("/api/document_update")
628
- async def get_document(company_id: str = Query(...)):
629
- print(f"Received companyId and name: {company_id},{company_id}") # Log rec
630
- #async def get_data_connectors(company_id: str, company_name: str):
631
- logging.info(f"Received request for company_id and company_id: {company_id},{company_id}")
632
- try:
633
- cnx = get_db_connection()
634
- cursor = cnx.cursor()
635
- query = """
636
- SELECT kb.kid,kb.company_id, kb.file_path, kb.document_name, kb.document_desc,kb.department,kb.version,kb.vectorDBflag,kb.last_updated
637
- FROM u852023448_redmindgpt.knowledge_base kb
638
- JOIN u852023448_redmindgpt.company_detail cd ON kb.company_id = cd.company_id
639
- WHERE kb.company_id = %s
640
- """
641
- logging.info(f"Executing query: {query} with company_id: {company_id}")
642
- values= (company_id,)
643
- # logging.info(f"Query parameters: {params}")
644
- print(f"Query parameters: {values}")
645
-
646
- cursor.execute(query, values) # Pa
647
- result = cursor.fetchall()
648
- logging.info(f"Query result: {r.esult}")
649
- cursor.close
650
- cnx.close()
651
- companies=[]
652
- for row in result:
653
-
654
- companies.append({
655
- "kid":row[0],
656
- "company_id": row[1],
657
- "file_path":row[2],
658
- "document_name": row[3],
659
- "document_desc": row[4],
660
- "department": row[5],
661
- "version": row[6],
662
- "vectorDBflag":row[7],
663
- "last_updated": row[8]
664
- })
665
- if companies:
666
- return companies
667
- else:
668
- logging.warning(f"No document found for company_id: {company_id}")
669
- raise HTTPException(status_code=404, detail="Data document not found")
670
- except mysql.connector.Error as err:
671
- logging.error(f"Database error: {err}")
672
- raise HTTPException(status_code=500, detail="Internal Server Error")
673
-
674
- #to get data for view in knowledgebase
675
- @app.get("/api/getknowledgebase/{company_id}")
676
- async def get_company_details(company_id: int):
677
- company = await get_knowledge_from_db(company_id)
678
- if not company:
679
- raise HTTPException(status_code=404, detail="Company not found")
680
- return company
681
-
682
- async def get_knowledge_from_db(company_id: int):
683
- try:
684
- # Establish a connection to the database
685
- cnx = get_db_connection()
686
- if cnx is None:
687
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
688
- cursor = cnx.cursor(dictionary=True)
689
- query = "SELECT * FROM knowledge_base WHERE kid = %s"
690
- cursor.execute(query, (company_id,))
691
- company = cursor.fetchone()
692
- cursor.close()
693
- cnx.close()
694
- if company:
695
- logging.debug(f"Extracted filename")
696
- if company.get('file_path'):
697
- company['file_path'] = os.path.basename(company['file_path'])
698
- logging.debug(f"Extracted filename: {company['file_path']}")
699
- return company
700
- else:
701
- raise HTTPException(status_code=404, detail="Company not found or file not found for the company")
702
- except mysql.connector.Error as err:
703
- logging.error(f"Error fetching company: {err}")
704
- raise HTTPException(status_code=500, detail="Failed to fetch company")
705
-
706
- # to edit the knowledgebase details
707
- @app.put("/api/putknowledgebase/{companyId}")
708
- async def update_company_details(
709
- request: Request,
710
- companyId: int,
711
- company_id: str = Form(...),
712
- file_path: UploadFile = File(...),
713
- documentName: str = Form(...),
714
- documentDescription: str = Form(...),
715
- department: str = Form(...),
716
- version: str = Form(...),
717
- vectorDBFlag: str = Form(...),
718
- lastUpdated: str = Form(...)
719
- ):
720
- logging.info(f"Received request for company data with ID inside edit/update knowledgebase: {companyId}")
721
- print(f"Received request for company data with ID inside edit/update knowledgebase file name: {file_path.filename}")
722
-
723
- # Create the upload folder if it doesn't exist
724
- upload_folder = "uploads/"
725
- os.makedirs(upload_folder, exist_ok=True)
726
-
727
- # Construct the file path for saving
728
- saved_file_path = os.path.join(upload_folder, file_path.filename)
729
-
730
- try:
731
- # Save the uploaded file to the server
732
- with open(saved_file_path, "wb") as buffer:
733
- shutil.copyfileobj(file_path.file, buffer)
734
- except Exception as e:
735
- logging.error(f"Error saving file: {e}")
736
- raise HTTPException(status_code=500, detail="Failed to save file")
737
-
738
- # Prepare the company data dictionary
739
- company_data = {
740
- 'kid': companyId,
741
- 'company_id': company_id,
742
- 'file_path': saved_file_path, # Use the path where the file was saved
743
- 'document_name': documentName,
744
- 'document_desc': documentDescription,
745
- 'department': department,
746
- 'version': version,
747
- 'vectorDBflag': vectorDBFlag,
748
- 'last_updated': lastUpdated
749
- }
750
-
751
- # Update the knowledge base in the database
752
- updated_company = await update_knowledge_in_db(companyId, company_data)
753
- if not updated_company:
754
- raise HTTPException(status_code=500, detail="Failed to update company")
755
- return updated_company
756
-
757
- async def update_knowledge_in_db(kid: int, company_data: dict):
758
- try:
759
- logging.info(f"Updating knowledge base for ID: {kid}")
760
- cnx = get_db_connection()
761
- if cnx is None:
762
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
763
-
764
- cursor = cnx.cursor()
765
- update_query = """
766
- UPDATE u852023448_redmindgpt.knowledge_base kb
767
- SET kb.company_id = %s, kb.document_name = %s, kb.document_desc = %s,
768
- kb.department = %s, kb.version = %s, kb.vectorDBflag = %s, kb.last_updated = %s
769
- WHERE kb.kid = %s;
770
- """
771
- logging.info(f"Executing update query: {update_query}")
772
-
773
- cursor.execute(update_query, (
774
- company_data['company_id'],
775
- company_data['document_name'],
776
- company_data['document_desc'],
777
- company_data['department'],
778
- company_data['version'],
779
- company_data['vectorDBflag'],
780
- company_data['last_updated'],
781
- kid
782
- ))
783
-
784
- cnx.commit()
785
- success = cursor.rowcount > 0
786
- cursor.close()
787
- cnx.close()
788
-
789
- if not success:
790
- logging.info("No rows updated")
791
- return None
792
- logging.info("Update successful")
793
- return company_data
794
- except mysql.connector.Error as err:
795
- logging.error(f"Database error: {err}")
796
- raise HTTPException(status_code=500, detail="Failed to update company")
797
- except Exception as e:
798
- logging.error(f"Unexpected error: {e}")
799
- raise HTTPException(status_code=500, detail="Unexpected error occurred")
800
-
801
-
802
- def delete_knowledge_from_db(company_id: int) -> bool:
803
- print(f"Received knowledge base company_id: {company_id}") # Debug statement
804
- logging.info(f"Received request for knowledgebase company id: {company_id}")
805
- try:
806
- # Establish a connection to the database
807
- cnx = get_db_connection()
808
- if cnx is None:
809
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
810
- cursor = cnx.cursor()
811
- delete_query = "DELETE FROM knowledge_base WHERE kid = %s"
812
- cursor.execute(delete_query, (company_id,))
813
- cnx.commit()
814
- success = cursor.rowcount > 0
815
- cursor.close()
816
- cnx.close()
817
- return success
818
- except mysql.connector.Error as err:
819
- logging.error(f"Error deleting company: {err}")
820
- raise HTTPException(status_code=500, detail="Failed to delete company")
821
-
822
- #to perform delete operation in knowlegebase
823
- @app.delete("/api/delknowledgebase/{company_id}")
824
- async def delete_company(company_id: int):
825
- deletion_success = delete_knowledge_from_db(company_id)
826
- if not deletion_success:
827
- raise HTTPException(status_code=404, detail="Company not found or failed to delete")
828
- return {"message": "Company deleted successfully"}
829
-
830
-
831
- @app.get("/data_connectors")
832
- async def data_connectors(request: Request):
833
- try:
834
- # Retrieve cookies
835
- role = request.cookies.get("role")
836
- company_id = request.cookies.get("company_id")
837
-
838
- # Render the template with the role and company_id
839
- return templates.TemplateResponse("data_connectors.html", {
840
- "request": request,
841
- "role": role,
842
- "company_id": company_id,
843
- "title": "Data Connectors"
844
- })
845
- except Exception as e:
846
- # Handle exceptions
847
- logging.error(f"Error: {e}")
848
- raise HTTPException(status_code=500, detail="Internal Server Error")
849
-
850
- #to insert into data_connectors
851
- @app.post("/save_data_connectors")
852
- async def save_data_connectors( request: Request,
853
- company_id: int = Form(...),
854
- database: List[str] = Form(...),
855
- server: str = Form(...),
856
- port: str = Form(...),
857
- databaseName:List[str]= Form(...),
858
- username: str=Form(...),
859
- password: str=Form(...),
860
- selectedTables: List[str] = Form(...)):
861
- logging.info(f"Received form submission for database_connectors")
862
- print(f"Received form submission for database_connectors")
863
- try:
864
- cnx = get_db_connection()
865
- cursor = cnx.cursor()
866
- # Check if the company_id already exists in the data_connectors table
867
- check_query = "SELECT COUNT(*) FROM data_connectors WHERE company_id = %s"
868
- cursor.execute(check_query, (company_id,))
869
- exists = cursor.fetchone()[0] > 0
870
-
871
- if exists:
872
- # Update the existing record
873
- query = """
874
- UPDATE data_connectors
875
- SET databasetype = %s, serverip = %s, port = %s, database_name = %s, username = %s, password = %s, dbtablename = %s
876
- WHERE company_id = %s
877
- """
878
- values = (",".join(database), server, port, ",".join(databaseName), username, password or '', ",".join(selectedTables), company_id)
879
- logging.info(f"Executing update query: {query} with values: {values}")
880
- cursor.execute(query, values)
881
- cnx.commit()
882
- logging.info(f"Query executed successfully, {cursor.rowcount} row(s) updated")
883
- else:
884
- # Insert a new record
885
- query = """
886
- INSERT INTO data_connectors(company_id, databasetype, serverip, port, database_name, username, password, dbtablename)
887
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
888
- """
889
- values = (company_id, ",".join(database), server, port, ",".join(databaseName), username, password or '', ",".join(selectedTables))
890
- logging.info(f"Executing insert query: {query} with values: {values}")
891
- cursor.execute(query, values)
892
- cnx.commit()
893
- logging.info(f"Query executed successfully, {cursor.rowcount} row(s) inserted")
894
-
895
- cursor.close()
896
- cnx.close()
897
-
898
- # logging.info(f"Data_connectors for {database} processed successfully")
899
- # return JSONResponse(content={"status": "success", "message": "Data saved successfully"}, status_code=200)
900
- response = {
901
- "msg": "Data saved successfully",
902
- "url": "/save_data_connectors", # The URL you want to redirect to
903
- "created": True
904
- }
905
- return JSONResponse(content=response)
906
-
907
-
908
- except mysql.connector.Error as err:
909
- logging.error(f"Database error: {err}")
910
- return JSONResponse(content={"status": "error", "message": "Internal Server Error"}, status_code=500)
911
- except Exception as e:
912
- logging.error(f"Unexpected error: {e}")
913
- return JSONResponse(content={"status": "error", "message": "Unexpected Server Error"}, status_code=500)
914
-
915
- @app.get("/api/check_data_connectors")
916
- async def get_data_connectors(company_id: str = Query(...), company_name: str = Query(...)):
917
- print(f"Received companyId and name: {company_id},{company_name}") # Log rec
918
- #async def get_data_connectors(company_id: str, company_name: str):
919
- logging.info(f"Received request for company_id and company_id: {company_id},{company_name}")
920
- try:
921
- cnx = get_db_connection()
922
- cursor = cnx.cursor()
923
- query = """
924
- SELECT dc.company_id, dc.databasetype, dc.serverip, dc.port,dc.database_name, dc.username, dc.password ,dc.dbtablename
925
- FROM u852023448_redmindgpt.data_connectors dc
926
- JOIN u852023448_redmindgpt.company_detail cd ON dc.company_id = cd.company_id
927
- WHERE dc.company_id = %s and cd.company_name=%s
928
- """
929
- logging.info(f"Executing query: {query} with company_id: {company_id}")
930
- params = (company_id,company_name)
931
- logging.info(f"Query parameters: {params}")
932
- print(f"Query parameters: {params}")
933
-
934
- cursor.execute(query, params) # Pa
935
- result = cursor.fetchone()
936
- logging.info(f"Query result: {result}")
937
- cursor.close()
938
- cnx.close()
939
-
940
- if result:
941
- databasetype = result[1]
942
- dbtablename = result[7].split(',') if result[7] else []
943
- logging.info(f"Data found for company_id: {company_id}")
944
- return {
945
- "company_id": result[0],
946
- "databasetype":databasetype,
947
- "serverip": result[2],
948
- "port": result[3],
949
- "database_name": result[4],
950
- "username": result[5],
951
- "password": result[6],
952
- "dbtablename": dbtablename
953
- }
954
- else:
955
- logging.warning(f"No data found for company_id: {company_id}")
956
- raise HTTPException(status_code=404, detail="Data connector not found")
957
- except mysql.connector.Error as err:
958
- logging.error(f"Database error: {err}")
959
- raise HTTPException(status_code=500, detail="Internal Server Error")
960
-
961
- @app.get("/API_connectors")
962
- async def API_connectors(request: Request):
963
- try:
964
- # Retrieve cookies
965
- role = request.cookies.get("role")
966
- company_id = request.cookies.get("company_id")
967
-
968
- # Render the template with the role and company_id
969
- return templates.TemplateResponse("API_connectors.html", {
970
- "request": request,
971
- "role": role,
972
- "company_id": company_id,
973
- "title":"API Connectors"
974
- })
975
- except Exception as e:
976
- # Handle exceptions
977
- logging.error(f"Error: {e}")
978
- raise HTTPException(status_code=500, detail="Internal Server Error")
979
-
980
- #save api connectors
981
- @app.post("/api/save_api_details")
982
- async def API_saveconnectors(request: Request,
983
- company_id:int=Form(...),
984
- APIName:str=Form(...),
985
- APIEndpoint:str=Form(...),
986
- Auth_Bearer:str=Form(...),
987
- Inputjson:str=Form(...),
988
- OutputJson:str=Form(...),
989
- Description:str=Form(...)):
990
- logging.info(f"Received form submission for database_connectors")
991
- try:
992
- cnx =get_db_connection()
993
- cursor = cnx.cursor()
994
- #databasetype_json=json.dumps(database)
995
- query = "INSERT INTO api_connectors(company_id,api_name, api_endpoint, auth_token, input_param,output_json,description) VALUES (%s,%s, %s, %s, %s,%s,%s)"
996
- values = (company_id, APIName, APIEndpoint, Auth_Bearer, Inputjson,OutputJson,Description)
997
- logging.info(f"Executing query: {query} with values: {values}")
998
- cursor.execute(query, values)
999
- cnx.commit()
1000
- logging.info(f"Query executed successfully, {cursor.rowcount} row(s) affected")
1001
- row_id = cursor.lastrowid
1002
- cursor.close()
1003
- cnx.close()
1004
- logging.info(f"Data_connectors for {APIName} inserted successfully")
1005
- return JSONResponse(status_code=200, content={"message": "Data saved successfully", "row_id": row_id})
1006
- #return RedirectResponse(url="/data_connectors", status_code=302)
1007
- except mysql.connector.Error as err:
1008
- logging.error(f"Database error: {err}")
1009
- raise HTTPException(status_code=500, detail="Internal Server Error")
1010
- # retrieve api connectors
1011
- @app.get("/api/get_api_connectors")
1012
- async def get_api_connectors(company_id: str = Query(...)):
1013
- print(f"Received companyId and name: {company_id}") # Log rec
1014
- #async def get_data_connectors(company_id: str, company_name: str):
1015
- logging.info(f"Received request for company_id and company_id: {company_id}")
1016
- try:
1017
- cnx =get_db_connection()
1018
- cursor = cnx.cursor()
1019
- query = """
1020
- SELECT ac.id, ac.company_id, ac.api_name, ac.api_endpoint,ac.auth_token,ac.input_param, ac.output_json, ac.description
1021
- FROM u852023448_redmindgpt.api_connectors ac
1022
- JOIN u852023448_redmindgpt.company_detail cd ON ac.company_id = cd.company_id
1023
- WHERE ac.company_id = %s
1024
- """
1025
- logging.info(f"Executing query: {query} with company_id: {company_id}")
1026
- params = (company_id,)
1027
- logging.info(f"Query parameters: {params}")
1028
- print(f"Query parameters: {params}")
1029
-
1030
- cursor.execute(query, params) # Pa
1031
- result = cursor.fetchall()
1032
- logging.info(f"Query result: {result}")
1033
- cursor.close()
1034
- cnx.close()
1035
- companies=[]
1036
- for row in result:
1037
- companies.append({
1038
- "row_id":row[0],
1039
- "company_id": row[1],
1040
- "APIName":row[2],
1041
- "APIEndpoint": row[3]
1042
- # "Auth_Bearer": result[3],
1043
- # "Inputjson": result[4],
1044
- #"OutputJson": result[5],
1045
- #"description": result[6]
1046
-
1047
- })
1048
- if companies:
1049
- return companies
1050
- else:
1051
- logging.warning(f"No data found for company_id: {company_id}")
1052
- raise HTTPException(status_code=404, detail="Data connector not found")
1053
- except mysql.connector.Error as err:
1054
- logging.error(f"Database error: {err}")
1055
- raise HTTPException(status_code=500, detail="Internal Server Error")
1056
- #to view the table details in modal
1057
- @app.get("/api/viewapiconnectors/{company_id}")
1058
- async def get_company_details(company_id: int):
1059
-
1060
- company = await get_api_from_db(company_id)
1061
- if not company:
1062
- raise HTTPException(status_code=404, detail="Company not found")
1063
- return company
1064
-
1065
- async def get_api_from_db(company_id: int):
1066
- try:
1067
- # Establish a connection to the database
1068
- cnx = get_db_connection()
1069
- if cnx is None:
1070
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
1071
- cursor = cnx.cursor(dictionary=True)
1072
- query = "SELECT * FROM api_connectors WHERE id = %s"
1073
- cursor.execute(query, (company_id,))
1074
- company = cursor.fetchone()
1075
- cursor.close()
1076
- cnx.close()
1077
- if company:
1078
- logging.info(f"api details:{company}")
1079
- return company
1080
- else:
1081
- raise HTTPException(status_code=404, detail="Company not found or file not found for the company")
1082
- except mysql.connector.Error as err:
1083
- logging.error(f"Error fetching company: {err}")
1084
- raise HTTPException(status_code=500, detail="Failed to fetch company")
1085
- #to edit the api details in modal form
1086
- @app.put("/api/editapiconnectors/{companyId}")
1087
- async def update_company_details(
1088
- request: Request,
1089
- companyId: int,
1090
- company_id:str=Form(...),
1091
- APIName:str=Form(...),
1092
- APIEndpoint:str=Form(...),
1093
- Auth_Bearer:str=Form(...),
1094
- Inputjson:str=Form(...),
1095
- OutputJson:str=Form(...),
1096
- Description:str=Form(...)):
1097
- logging.info(f"Received form submission for database_connectors")
1098
- logging.info(f"Received request for company data with ID inside edit/update knowledgebase: {companyId}")
1099
-
1100
- # Prepare the company data dictionary
1101
- company_data = {
1102
- 'kid': companyId,
1103
- 'company_id': company_id,
1104
- 'api_name': APIName,
1105
- 'api_endpoint': APIEndpoint,
1106
- 'auth_token': Auth_Bearer,
1107
- 'input_param': Inputjson,
1108
- 'output_json': OutputJson,
1109
- 'description': Description
1110
- }
1111
-
1112
- # Update the knowledge base in the database
1113
- updated_company = await update_api_in_db(companyId, company_data)
1114
- if not updated_company:
1115
- raise HTTPException(status_code=500, detail="Failed to update company")
1116
- return updated_company
1117
-
1118
- async def update_api_in_db(id: int, company_data: dict):
1119
- try:
1120
- logging.info(f"Updating api for ID: {id}")
1121
- cnx = get_db_connection()
1122
- if cnx is None:
1123
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
1124
-
1125
- cursor = cnx.cursor()
1126
- update_query = """
1127
- UPDATE u852023448_redmindgpt.api_connectors ac
1128
- SET ac.company_id = %s, ac.api_name = %s, ac.api_endpoint= %s,
1129
- ac.auth_token= %s, ac.input_param= %s,ac.output_json = %s, ac.description= %s
1130
- WHERE ac.id = %s;
1131
- """
1132
- logging.info(f"Executing update query: {update_query}")
1133
-
1134
- cursor.execute(update_query, (
1135
- company_data['company_id'],
1136
- company_data['api_name'],
1137
- company_data['api_endpoint'],
1138
- company_data['auth_token'],
1139
- company_data['input_param'],
1140
- company_data['output_json'],
1141
- company_data['description'],
1142
- id
1143
- ))
1144
-
1145
- cnx.commit()
1146
- success = cursor.rowcount > 0
1147
- cursor.close()
1148
- cnx.close()
1149
-
1150
- if not success:
1151
- logging.info("No rows updated")
1152
- return None
1153
- logging.info("Update successful")
1154
- return company_data
1155
- except mysql.connector.Error as err:
1156
- logging.error(f"Database error: {err}")
1157
- raise HTTPException(status_code=500, detail="Failed to update company")
1158
- except Exception as e:
1159
- logging.error(f"Unexpected error: {e}")
1160
- raise HTTPException(status_code=500, detail="Unexpected error occurred")
1161
-
1162
- #on update of modal form the data table is refreshed to dispalyupdated value in datatable
1163
- @app.get("/api/api_updatetable")
1164
- async def get_document(company_id: str = Query(...)):
1165
- print(f"Received companyId and name for api datatable update: {company_id},{company_id}") # Log rec
1166
- #async def get_data_connectors(company_id: str, company_name: str):
1167
- logging.info(f"Received request for company_id and company_id: {company_id},{company_id}")
1168
- try:
1169
- cnx = get_db_connection()
1170
- cursor = cnx.cursor()
1171
- query=""" SELECT ac.id,ac.company_id, ac.api_name, ac.api_endpoint,ac.auth_token,ac.input_param, ac.output_json, ac.description
1172
- FROM u852023448_redmindgpt.api_connectors ac
1173
- JOIN u852023448_redmindgpt.company_detail cd ON ac.company_id = cd.company_id
1174
- WHERE ac.company_id = %s
1175
- """
1176
- logging.info(f"Executing query: {query} with company_id: {company_id}")
1177
- values= (company_id,)
1178
- # logging.info(f"Query parameters: {params}")
1179
- print(f"Query parameters: {values}")
1180
-
1181
- cursor.execute(query, values) # Pa
1182
- result = cursor.fetchall()
1183
- logging.info(f"Query result for update table: {result}")
1184
- cursor.close
1185
- cnx.close()
1186
- companies=[]
1187
- for row in result:
1188
-
1189
- companies.append({
1190
- "row_id":row[0],
1191
- "company_id": row[1],
1192
- "api_name":row[2],
1193
- "api_endpoint": row[3],
1194
- # "Auth_Bearer": row[4],
1195
- # "Inputjson": row[5],
1196
- # "OutputJson": row[6],
1197
- # "description": row[7]
1198
-
1199
- })
1200
- if companies:
1201
- return companies
1202
- else:
1203
- logging.warning(f"No document found for company_id: {company_id}")
1204
- raise HTTPException(status_code=404, detail="Data document not found")
1205
- except mysql.connector.Error as err:
1206
- logging.error(f"Database error: {err}")
1207
- raise HTTPException(status_code=500, detail="Internal Server Error")
1208
-
1209
- #to delete api details from db
1210
- @app.delete("/api/deleteapi/{company_id}")
1211
- async def delete_company(company_id: int):
1212
- deletion_success = delete_api_from_db(company_id)
1213
- if not deletion_success:
1214
- raise HTTPException(status_code=404, detail="Company not found or failed to delete")
1215
- return {"message": "Company deleted successfully"}
1216
-
1217
- def delete_api_from_db(company_id: int) -> bool:
1218
- print(f"Received api for company_id: {company_id}") # Debug statement
1219
- logging.info(f"Received request for api for company id: {company_id}")
1220
- try:
1221
- # Establish a connection to the database
1222
- cnx = get_db_connection()
1223
- if cnx is None:
1224
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
1225
- cursor = cnx.cursor()
1226
- delete_query = "DELETE FROM api_connectors WHERE id = %s"
1227
- cursor.execute(delete_query, (company_id,))
1228
- cnx.commit()
1229
- success = cursor.rowcount > 0
1230
- cursor.close()
1231
- cnx.close()
1232
- return success
1233
- except mysql.connector.Error as err:
1234
- logging.error(f"Error deleting company: {err}")
1235
- raise HTTPException(status_code=500, detail="Failed to delete company")
1236
-
1237
-
1238
- @app.get("/prompt_template")
1239
- async def prompt_template(request: Request):
1240
- try:
1241
- # Retrieve cookies
1242
- role = request.cookies.get("role")
1243
- company_id = request.cookies.get("company_id")
1244
-
1245
- # Render the template with the role and company_id
1246
- return templates.TemplateResponse("prompt_template.html", {
1247
- "request": request,
1248
- "role": role,
1249
- "company_id": company_id,
1250
- "title":"Prompt Templates"
1251
- })
1252
- except Exception as e:
1253
- # Handle exceptions
1254
- logging.error(f"Error: {e}")
1255
- raise HTTPException(status_code=500, detail="Internal Server Error")
1256
- # to insert into prompt templates
1257
- @app.post("/api/save_prompt_details")
1258
- async def prompt_saveconnectors(request: Request,
1259
- company_id:int=Form(...),
1260
- scenario:str=Form(...),
1261
- sampleprompt:str=Form(...),
1262
- comments:str=Form(...),
1263
- ):
1264
- logging.info(f"Received form submission for database_connectors")
1265
- try:
1266
- cnx =get_db_connection()
1267
- cursor = cnx.cursor()
1268
- #databasetype_json=json.dumps(database)
1269
- query = "INSERT INTO prompt_templates(company_id,scenario, prompts, comments) VALUES (%s,%s, %s, %s)"
1270
- values = (company_id, scenario, sampleprompt, comments)
1271
- logging.info(f"Executing query: {query} with values: {values}")
1272
- cursor.execute(query, values)
1273
- cnx.commit()
1274
- logging.info(f"Query executed successfully, {cursor.rowcount} row(s) affected")
1275
- row_id = cursor.lastrowid # Get the last inserted row_id
1276
- cursor.close()
1277
- cnx.close()
1278
- logging.info(f"Data_connectors for {scenario} inserted successfully")
1279
- return JSONResponse(status_code=200, content={"message": "Data saved successfully", "row_id": row_id})
1280
- #return RedirectResponse(url="/prompt_template", status_code=302)
1281
- except mysql.connector.Error as err:
1282
- logging.error(f"Database error: {err}")
1283
- raise HTTPException(status_code=500, detail="Internal Server Error")
1284
- # retrieve api connectors
1285
- @app.get("/api/get_prompt_templates")
1286
- async def get_prompt_connectors(company_id: str = Query(...)):
1287
- print(f"Received companyId and name: {company_id}") # Log rec
1288
- #async def get_data_connectors(company_id: str, company_name: str):
1289
- logging.info(f"Received request for company_id and company_id: {company_id}")
1290
- try:
1291
- cnx =get_db_connection()
1292
- cursor = cnx.cursor()
1293
- query = """
1294
- SELECT pt.id,pt.company_id,pt.scenario,pt.prompts,pt.comments
1295
- FROM u852023448_redmindgpt.prompt_templates pt
1296
- JOIN u852023448_redmindgpt.company_detail cd ON pt.company_id = cd.company_id
1297
- WHERE pt.company_id = %s
1298
- """
1299
- logging.info(f"Executing query: {query} with company_id: {company_id}")
1300
- params = (company_id,)
1301
- logging.info(f"Query parameters: {params}")
1302
- print(f"Query parameters: {params}")
1303
-
1304
- cursor.execute(query, params) # Pa
1305
- result = cursor.fetchall()
1306
- logging.info(f"Query result: {result}")
1307
- cursor.close()
1308
- cnx.close()
1309
- companies=[]
1310
- for row in result:
1311
- companies.append({
1312
- "row_id":row[0],
1313
- "company_id": row[1],
1314
- "scenario":row[2],
1315
- "prompt": row[3]
1316
- # "Auth_Bearer": result[3],
1317
- # "Inputjson": result[4],
1318
- #"OutputJson": result[5],
1319
- #"description": result[6]
1320
-
1321
- })
1322
- if companies:
1323
- return companies
1324
- else:
1325
- logging.warning(f"No data found for company_id: {company_id}")
1326
- raise HTTPException(status_code=404, detail="Data connector not found")
1327
- except mysql.connector.Error as err:
1328
- logging.error(f"Database error: {err}")
1329
- raise HTTPException(status_code=500, detail="Internal Server Error")
1330
-
1331
- def delete_prompt_template_from_db(row_id: int) -> bool:
1332
- logging.info(f"Received request for prompt_template company id: {row_id}")
1333
- logging.info(f"Received request for prompt_template row id: {row_id}")
1334
-
1335
- try:
1336
- # Establish a connection to the database
1337
- cnx = get_db_connection()
1338
- if cnx is None:
1339
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
1340
- cursor = cnx.cursor()
1341
- delete_query = "DELETE FROM prompt_templates WHERE id = %s"
1342
-
1343
- logging.info(f"sql delete query for prompt template ===> {delete_query}")
1344
-
1345
- cursor.execute(delete_query, (row_id,))
1346
- cnx.commit()
1347
- success = cursor.rowcount > 0
1348
- logging.info (f"deleted succesfully ! ===> {success}")
1349
-
1350
- cursor.close()
1351
- cnx.close()
1352
- return success
1353
- except mysql.connector.Error as err:
1354
- print('python')
1355
- logging.error(f"Error deleting company: {err}")
1356
- raise HTTPException(status_code=500, detail="Failed to delete company")
1357
-
1358
- @app.delete("/api/prompt_template_for_del/{row_id}")
1359
- async def delete_company(row_id: int):
1360
- deletion_success = delete_prompt_template_from_db(row_id)
1361
- logging.info(f"company row_id +++> {row_id}")
1362
-
1363
- if not deletion_success:
1364
- raise HTTPException(status_code=404, detail="Company not found or failed to delete")
1365
- return {"message": "Company deleted successfully"}
1366
-
1367
- # promt_template view function ! ............
1368
-
1369
- #to get data for view in promt_templae by id
1370
- @app.get("/api/getpromttemplate/{company_id}")
1371
- async def get_promt_company_details(company_id: int):
1372
- company = await get_promt_from_db(company_id)
1373
- if not company:
1374
- raise HTTPException(status_code=404, detail="Company not found")
1375
- return company
1376
-
1377
- async def get_promt_from_db(company_id: int):
1378
- try:
1379
- # Establish a connection to the database
1380
- cnx = get_db_connection()
1381
- if cnx is None:
1382
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
1383
- cursor = cnx.cursor(dictionary=True)
1384
- query = "SELECT * FROM prompt_templates WHERE id = %s"
1385
- logging.info(f"row_id in db addresss ========> {company_id}")
1386
-
1387
- cursor.execute(query, (company_id,))
1388
- company = cursor.fetchone()
1389
- cursor.close()
1390
- cnx.close()
1391
- if company:
1392
- logging.info(f"row_id in db addresss ========> {company}")
1393
- return company
1394
-
1395
- else:
1396
- raise HTTPException(status_code=404, detail="Company not found or file not found for the company")
1397
- except mysql.connector.Error as err:
1398
- logging.error(f"Error fetching company: {err}")
1399
- raise HTTPException(status_code=500, detail="Failed to fetch company")
1400
-
1401
- # Function to update company details
1402
- @app.put("/api/putprompttemplates/{kid}")
1403
- async def update_company_details(
1404
- kid: int,
1405
- scenario: str = Form(...),
1406
- prompt: str = Form(...),
1407
- comments: str = Form(...)
1408
- ):
1409
- logging.info(f"Received request for company data with ID: {kid}")
1410
- company_data = {
1411
- 'scenario': scenario,
1412
- 'prompts': prompt,
1413
- 'comments': comments,
1414
- }
1415
- updated_company = await update_prompt_in_db(kid, company_data)
1416
- if not updated_company:
1417
- raise HTTPException(status_code=500, detail="Failed to update company")
1418
- return updated_company
1419
-
1420
- # Database query function to update company data
1421
- async def update_prompt_in_db(kid: int, company_data: dict):
1422
- try:
1423
- logging.info(f"Updating prompt for ID: {kid}")
1424
- cnx = get_db_connection()
1425
- if cnx is None:
1426
- raise HTTPException(status_code=500, detail="Failed to connect to the database")
1427
-
1428
- cursor = cnx.cursor()
1429
- update_query = """
1430
- UPDATE u852023448_redmindgpt.prompt_templates pt
1431
- SET pt.scenario=%s, pt.prompts=%s, pt.comments=%s
1432
- WHERE pt.id = %s;
1433
- """
1434
- logging.info(f"row_id in prompt db address ========> {kid}")
1435
- logging.info(f"SQL update query for company ===> {update_query}")
1436
-
1437
- cursor.execute(update_query, (
1438
- company_data['scenario'],
1439
- company_data['prompts'],
1440
- company_data['comments'],
1441
- kid
1442
- ))
1443
-
1444
- cnx.commit()
1445
- success = cursor.rowcount > 0
1446
- cursor.close()
1447
- cnx.close()
1448
-
1449
- if not success:
1450
- return None
1451
- return company_data
1452
-
1453
- except mysql.connector.Error as err:
1454
- logging.error(f"Error updating company: {err}")
1455
- raise HTTPException(status_code=500, detail="Failed to update company")
1456
-
1457
- # to refresh prompt data table
1458
- @app.get("/api/prompt_update")
1459
- async def get_document(company_id: str = Query(...)):
1460
- print(f"Received companyId and name: {company_id},{company_id}") # Log rec
1461
- #async def get_data_connectors(company_id: str, company_name: str):
1462
- logging.info(f"Received request for company_id and company_id: {company_id},{company_id}")
1463
- try:
1464
- cnx = get_db_connection()
1465
- cursor = cnx.cursor()
1466
- query = """
1467
- SELECT pt.id,pt.company_id,pt.scenario,pt.prompts,pt.comments
1468
- FROM u852023448_redmindgpt.prompt_templates pt
1469
- JOIN u852023448_redmindgpt.company_detail cd ON pt.company_id = cd.company_id
1470
- WHERE pt.company_id = %s
1471
- """
1472
- logging.info(f"Executing query: {query} with company_id: {company_id}")
1473
- values= (company_id,)
1474
- # logging.info(f"Query parameters: {params}")
1475
- print(f"Query parameters: {values}")
1476
-
1477
- cursor.execute(query, values) # Pa
1478
- result = cursor.fetchall()
1479
- logging.info(f"Query result: {result}")
1480
- cursor.close
1481
- cnx.close()
1482
- companies=[]
1483
- for row in result:
1484
- companies.append({
1485
- 'id':row[0],
1486
- "company_id": row[1],
1487
- "scenario":row[2],
1488
- "prompts": row[3]
1489
- # "Auth_Bearer": result[3],
1490
- # "Inputjson": result[4],
1491
- #"OutputJson": result[5],
1492
- #"description": result[6]
1493
-
1494
- })
1495
- if companies:
1496
- logging.info(f"the primary key id is {companies}")
1497
- return companies
1498
- else:
1499
- logging.warning(f"No document found for company_id: {company_id}")
1500
- raise HTTPException(status_code=404, detail="Data document not found")
1501
- except mysql.connector.Error as err:
1502
- logging.error(f"Database error: {err}")
1503
- raise HTTPException(status_code=500, detail="Internal Server Error")
1504
-
1505
- @app.get("/chatbot")
1506
- async def chatbot(request: Request):
1507
- return templates.TemplateResponse("chatbot.html", {"request": request,"title":"Chatbot"})
1508
-
1509
- if __name__ == "__main__":
1510
- import uvicorn
1511
- uvicorn.run(app, host="127.0.0.1", port=8000)