willco-afk commited on
Commit
19da2df
·
verified ·
1 Parent(s): 47cbaaf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -55
app.py CHANGED
@@ -1,64 +1,85 @@
1
- import gradio as gr
2
- from sentence_transformers import SentenceTransformer, util
3
- import torch
4
- import faiss
5
- import chromadb
6
 
7
- # Load the SentenceTransformer model for vector embeddings
8
- model = SentenceTransformer('all-MiniLM-L6-v2')
9
 
10
- # FAQ dataset (this can be expanded)
11
- faq_data = [
12
- ("What is Hugging Face?", "Hugging Face is a company specializing in AI and machine learning, known for their open-source models and datasets."),
13
- ("What is AI?", "Artificial Intelligence (AI) is the simulation of human intelligence in machines.")
14
- # Add more FAQ pairs...
15
- ]
16
 
17
- corpus = [item[0] for item in faq_data] # Questions only
18
- answers = {item[0]: item[1] for item in faq_data} # Map questions to answers
19
- corpus_embeddings = model.encode(corpus, convert_to_tensor=True)
20
 
21
- # Initialize FAISS Index
22
- index = faiss.IndexFlatL2(corpus_embeddings.shape[1])
23
- index.add(corpus_embeddings.cpu().numpy())
 
 
24
 
25
- # Initialize Chroma vector store
26
- client = chromadb.Client()
27
- collection = client.create_collection(name="faq_data")
28
- for i, text in enumerate(corpus):
29
- collection.add(
30
- ids=[f"faq_{i}"], # Unique ID for each document (using the index i)
31
- documents=[text],
32
- metadatas=[{"source": f"faq_{i}"}],
33
- embeddings=[corpus_embeddings[i].cpu().numpy()],
 
 
 
 
 
 
 
 
 
34
  )
35
-
36
- # Retrieval function using FAISS and Chroma
37
- def retrieve(query):
38
- query_embedding = model.encode(query, convert_to_tensor=True).cpu().numpy()
39
-
40
- # Use FAISS for nearest neighbor search
41
- faiss_results = index.search(query_embedding, k=1)
42
- faiss_top_result_idx = faiss_results[1][0][0]
43
- faiss_top_score = faiss_results[0][0][0]
44
-
45
- # Use Chroma for semantic search
46
- chroma_results = collection.query(query_embeddings=[query_embedding], n_results=1)
47
- chroma_top_result = chroma_results['documents'][0]
48
-
49
- # Combining results from FAISS and Chroma
50
- if faiss_top_score > 0.5:
51
- return answers[corpus[faiss_top_result_idx]]
52
  else:
53
- return chroma_top_result or "Sorry, I didn’t understand that. Could you try asking something else?"
54
 
55
- # Gradio interface to interact with the bot
56
- iface = gr.Interface(fn=retrieve,
57
- inputs="text",
58
- outputs="text",
59
- live=True,
60
- title="RAG AI Bot with OCI AI Skills",
61
- description="Ask me anything related to Hugging Face, Oracle OCI AI, or general knowledge!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- # Launch the Gradio interface
64
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ import requests
3
+ import oci
4
+ import json
5
+ from datetime import datetime
6
 
7
+ app = FastAPI()
 
8
 
9
+ # Oracle Cloud Configurations (Ensure your OCI config file is set up correctly)
10
+ config = oci.config.from_file("~/.oci/config", "DEFAULT")
11
+ signer = oci.auth.signers.get_resource_principals_signer()
 
 
 
12
 
13
+ # Endpoint URL for Oracle AI Service (Replace region appropriately)
14
+ oci_endpoint = "https://anomalydetection.aiservice.{{region}}.oci.oraclecloud.com/20210101/aiPrivateEndpoints"
 
15
 
16
+ # Request headers including authentication (ensure the correct signing/authentication process)
17
+ headers = {
18
+ "Content-Type": "application/json",
19
+ "Authorization": "Bearer {access_token}" # Use the appropriate method to authenticate
20
+ }
21
 
22
+ @app.post("/create-private-endpoint")
23
+ async def create_private_endpoint(compartment_id: str, subnet_id: str, display_name: str, dns_zones: list):
24
+ """Creates a private reverse connection endpoint in Oracle Cloud"""
25
+
26
+ # Prepare the request body
27
+ request_body = {
28
+ "compartmentId": compartment_id,
29
+ "subnetId": subnet_id,
30
+ "displayName": display_name,
31
+ "dnsZones": dns_zones,
32
+ "definedTags": {},
33
+ "freeformTags": {}
34
+ }
35
+
36
+ response = requests.post(
37
+ oci_endpoint,
38
+ headers=headers,
39
+ data=json.dumps(request_body)
40
  )
41
+
42
+ if response.status_code == 202:
43
+ return {"message": "Private endpoint created successfully", "status": response.status_code}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  else:
45
+ raise HTTPException(status_code=response.status_code, detail=response.json())
46
 
47
+ @app.put("/update-private-endpoint/{endpoint_id}")
48
+ async def update_private_endpoint(endpoint_id: str, display_name: str, dns_zones: list):
49
+ """Updates a private reverse connection endpoint"""
50
+
51
+ update_url = f"{oci_endpoint}/{endpoint_id}"
52
+
53
+ request_body = {
54
+ "displayName": display_name,
55
+ "dnsZones": dns_zones,
56
+ "definedTags": {},
57
+ "freeformTags": {}
58
+ }
59
+
60
+ response = requests.put(
61
+ update_url,
62
+ headers=headers,
63
+ data=json.dumps(request_body)
64
+ )
65
+
66
+ if response.status_code == 202:
67
+ return {"message": "Private endpoint updated successfully", "status": response.status_code}
68
+ else:
69
+ raise HTTPException(status_code=response.status_code, detail=response.json())
70
 
71
+ @app.get("/get-private-endpoint/{endpoint_id}")
72
+ async def get_private_endpoint(endpoint_id: str):
73
+ """Retrieves a private reverse connection endpoint by its ID"""
74
+
75
+ get_url = f"{oci_endpoint}/{endpoint_id}"
76
+
77
+ response = requests.get(
78
+ get_url,
79
+ headers=headers
80
+ )
81
+
82
+ if response.status_code == 200:
83
+ return response.json()
84
+ else:
85
+ raise HTTPException(status_code=response.status_code, detail=response.json())