Spaces:
Paused
Paused
updated app.py
Browse files
app.py
CHANGED
@@ -1,133 +1,71 @@
|
|
1 |
-
import os
|
2 |
import gradio as gr
|
3 |
-
|
4 |
-
|
5 |
-
from
|
6 |
-
|
7 |
-
from transformers import AutoConfig, AutoTokenizer, pipeline, AutoModelForCausalLM
|
8 |
-
from langchain_community.document_loaders import DirectoryLoader
|
9 |
-
import torch
|
10 |
-
import re
|
11 |
-
import transformers
|
12 |
-
from urllib.parse import urlencode
|
13 |
-
import spaces
|
14 |
-
|
15 |
-
# Initialize embeddings and ChromaDB
|
16 |
-
model_name = "sentence-transformers/all-mpnet-base-v2"
|
17 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
18 |
-
model_kwargs = {"device": device}
|
19 |
-
embeddings = HuggingFaceEmbeddings(model_name=model_name, model_kwargs=model_kwargs)
|
20 |
-
|
21 |
-
loader = DirectoryLoader('./example', glob="**/*.pdf", recursive=True, use_multithreading=True)
|
22 |
-
docs = loader.load()
|
23 |
-
vectordb = Chroma.from_documents(documents=docs, embedding=embeddings, persist_directory="companies_db")
|
24 |
-
books_db = Chroma(persist_directory="./companies_db", embedding_function=embeddings)
|
25 |
-
books_db_client = books_db.as_retriever()
|
26 |
-
|
27 |
-
# Initialize the model and tokenizer
|
28 |
-
model_name = "stabilityai/stablelm-zephyr-3b"
|
29 |
-
model_config = transformers.AutoConfig.from_pretrained(model_name, max_new_tokens=1024)
|
30 |
-
model = transformers.AutoModelForCausalLM.from_pretrained(
|
31 |
-
model_name,
|
32 |
-
trust_remote_code=True,
|
33 |
-
config=model_config,
|
34 |
-
device_map=device,
|
35 |
-
)
|
36 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
37 |
-
|
38 |
-
query_pipeline = transformers.pipeline(
|
39 |
-
"text-generation",
|
40 |
-
model=model,
|
41 |
-
tokenizer=tokenizer,
|
42 |
-
return_full_text=True,
|
43 |
-
torch_dtype=torch.float16,
|
44 |
-
device_map=device,
|
45 |
-
do_sample=True,
|
46 |
-
temperature=0.7,
|
47 |
-
top_p=0.9,
|
48 |
-
top_k=50,
|
49 |
-
max_new_tokens=256
|
50 |
-
)
|
51 |
-
|
52 |
-
llm = HuggingFacePipeline(pipeline=query_pipeline)
|
53 |
-
|
54 |
-
books_db_client_retriever = RetrievalQA.from_chain_type(
|
55 |
-
llm=llm,
|
56 |
-
chain_type="stuff",
|
57 |
-
retriever=books_db_client,
|
58 |
-
verbose=True
|
59 |
-
)
|
60 |
-
|
61 |
-
# Function to retrieve answer using the RAG system
|
62 |
-
@spaces.GPU(duration=60)
|
63 |
-
def test_rag(query):
|
64 |
-
books_retriever = books_db_client_retriever.run(query)
|
65 |
-
corrected_text_match = re.search(r"Helpful Answer:(.*)", books_retriever, re.DOTALL)
|
66 |
-
|
67 |
-
if corrected_text_match:
|
68 |
-
corrected_text_books = corrected_text_match.group(1).strip()
|
69 |
-
else:
|
70 |
-
corrected_text_books = "No helpful answer found."
|
71 |
-
|
72 |
-
return corrected_text_books
|
73 |
|
74 |
# OAuth Configuration
|
75 |
-
TENANT_ID =
|
76 |
-
CLIENT_ID =
|
77 |
-
CLIENT_SECRET =
|
78 |
-
REDIRECT_URI =
|
79 |
-
AUTH_URL =
|
80 |
-
TOKEN_URL =
|
81 |
-
SCOPE =
|
82 |
access_token = None
|
83 |
|
84 |
-
|
85 |
-
def
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
|
117 |
-
#
|
118 |
-
|
119 |
-
|
120 |
-
# Hidden components initially
|
121 |
-
input_box = gr.Textbox(label="Enter your question", placeholder="Type your question here...", visible=False)
|
122 |
-
submit_btn = gr.Button("Submit", visible=False)
|
123 |
-
chat_history = gr.Chatbot(label="Chat History", visible=False)
|
124 |
-
|
125 |
-
# Show components after login
|
126 |
-
def show_components():
|
127 |
-
return gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
|
128 |
-
|
129 |
-
# After a successful login, show the input box and buttons
|
130 |
-
submit_btn.click(show_components, outputs=[input_box, submit_btn, chat_history])
|
131 |
-
submit_btn.click(chat, inputs=[input_box, chat_history], outputs=[chat_history, input_box])
|
132 |
-
|
133 |
-
interface.launch()
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import webbrowser
|
4 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
5 |
+
import threading
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
# OAuth Configuration
|
8 |
+
TENANT_ID = '2b093ced-2571-463f-bc3e-b4f8bcb427ee'
|
9 |
+
CLIENT_ID = '2a7c884c-942d-49e2-9e5d-7a29d8a0d3e5'
|
10 |
+
CLIENT_SECRET = 'EOF8Q~kKHCRgx8tnlLM-H8e93ifetxI6x7sU6bGW'
|
11 |
+
REDIRECT_URI = 'https://sanjeevbora-chatbot.hf.space/'
|
12 |
+
AUTH_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/authorize"
|
13 |
+
TOKEN_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"
|
14 |
+
SCOPE = 'User.Read'
|
15 |
access_token = None
|
16 |
|
17 |
+
class RequestHandler(BaseHTTPRequestHandler):
|
18 |
+
def do_GET(self):
|
19 |
+
global access_token
|
20 |
+
if self.path.startswith("/callback"):
|
21 |
+
# Capture the authorization code
|
22 |
+
code = self.path.split("code=")[1]
|
23 |
+
token_url = f"{AUTHORITY_URL}/token"
|
24 |
+
response = requests.post(token_url, data={
|
25 |
+
'client_id': CLIENT_ID,
|
26 |
+
'client_secret': CLIENT_SECRET,
|
27 |
+
'grant_type': 'authorization_code',
|
28 |
+
'code': code,
|
29 |
+
'redirect_uri': REDIRECT_URI
|
30 |
+
})
|
31 |
+
token_data = response.json()
|
32 |
+
access_token = token_data.get('access_token')
|
33 |
+
self.send_response(200)
|
34 |
+
self.end_headers()
|
35 |
+
self.wfile.write(b"Login successful! You can close this window.")
|
36 |
+
return
|
37 |
+
|
38 |
+
self.send_response(404)
|
39 |
+
self.end_headers()
|
40 |
+
|
41 |
+
def start_http_server():
|
42 |
+
server_address = ('', 8080)
|
43 |
+
httpd = HTTPServer(server_address, RequestHandler)
|
44 |
+
httpd.serve_forever()
|
45 |
+
|
46 |
+
def login():
|
47 |
+
auth_url = f"{AUTHORITY_URL}/authorize?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&scope={SCOPE}"
|
48 |
+
webbrowser.open(auth_url)
|
49 |
+
|
50 |
+
def gradio_interface():
|
51 |
+
with gr.Blocks() as demo:
|
52 |
+
gr.Markdown("### Welcome to the App")
|
53 |
+
btn_login = gr.Button("Login with Microsoft")
|
54 |
+
output = gr.Textbox(label="Status")
|
55 |
+
|
56 |
+
def check_login():
|
57 |
+
if access_token:
|
58 |
+
return "You are logged in!"
|
59 |
+
return "You are not logged in."
|
60 |
+
|
61 |
+
btn_login.click(lambda: (login(), check_login()), None, output)
|
62 |
+
|
63 |
+
return demo
|
64 |
+
|
65 |
+
if __name__ == "__main__":
|
66 |
+
# Start the HTTP server in a separate thread
|
67 |
+
threading.Thread(target=start_http_server, daemon=True).start()
|
68 |
|
69 |
+
# Launch Gradio app
|
70 |
+
demo = gradio_interface()
|
71 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|