tahiryaqoob commited on
Commit
82b49ce
·
verified ·
1 Parent(s): 3db4acf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -51
app.py CHANGED
@@ -1,64 +1,108 @@
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
27
 
28
- response = ""
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ import os
2
+ import requests
3
+ from io import BytesIO
4
+ from PyPDF2 import PdfReader
5
+ from tempfile import NamedTemporaryFile
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ from langchain_community.embeddings import HuggingFaceEmbeddings
8
+ from langchain_community.vectorstores import FAISS
9
+ from groq import Groq
10
  import gradio as gr
 
11
 
12
+ # Initialize Groq client
13
+ client = Groq(api_key="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")
 
 
14
 
15
+ # Predefined list of Google Drive links
16
+ drive_links = [
17
+ "https://drive.google.com/file/d/1vku86qnrvJtCtHTxKXvSOJwtCYC6u3sp/view",
18
+ # Add more links here as needed
19
+ ]
20
 
21
+ # Function to download PDF from Google Drive
22
+ def download_pdf_from_drive(drive_link):
23
+ file_id = drive_link.split('/d/')[1].split('/')[0]
24
+ download_url = f"https://drive.google.com/uc?id={file_id}&export=download"
25
+ response = requests.get(download_url)
26
+ if response.status_code == 200:
27
+ return BytesIO(response.content)
28
+ else:
29
+ raise Exception("Failed to download the PDF file from Google Drive.")
30
 
31
+ # Function to extract text from a PDF
32
+ def extract_text_from_pdf(pdf_stream):
33
+ pdf_reader = PdfReader(pdf_stream)
34
+ text = ""
35
+ for page in pdf_reader.pages:
36
+ text += page.extract_text()
37
+ return text
38
 
39
+ # Function to split text into chunks
40
+ def chunk_text(text, chunk_size=500, chunk_overlap=50):
41
+ text_splitter = RecursiveCharacterTextSplitter(
42
+ chunk_size=chunk_size, chunk_overlap=chunk_overlap
43
+ )
44
+ return text_splitter.split_text(text)
45
 
46
+ # Function to create embeddings and store them in FAISS
47
+ def create_embeddings_and_store(chunks):
48
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
49
+ vector_db = FAISS.from_texts(chunks, embedding=embeddings)
50
+ return vector_db
51
 
52
+ # Function to query the vector database and interact with Groq
53
+ def query_vector_db(query, vector_db):
54
+ # Retrieve relevant documents
55
+ docs = vector_db.similarity_search(query, k=3)
56
+ context = "\n".join([doc.page_content for doc in docs])
 
 
 
57
 
58
+ # Interact with Groq API
59
+ chat_completion = client.chat.completions.create(
60
+ messages=[
61
+ {"role": "system", "content": f"Use the following context:\n{context}"},
62
+ {"role": "user", "content": query},
63
+ ],
64
+ model="llama3-8b-8192",
65
+ )
66
+ return chat_completion.choices[0].message.content
67
 
68
+ # Process the predefined Google Drive links
69
+ def process_drive_links():
70
+ all_chunks = []
71
+ for link in drive_links:
72
+ try:
73
+ # Download PDF
74
+ pdf_stream = download_pdf_from_drive(link)
75
+ # Extract text
76
+ text = extract_text_from_pdf(pdf_stream)
77
+ # Chunk text
78
+ chunks = chunk_text(text)
79
+ all_chunks.extend(chunks)
80
+ except Exception as e:
81
+ return f"Error processing link {link}: {e}"
82
+
83
+ if all_chunks:
84
+ # Generate embeddings and store in FAISS
85
+ vector_db = create_embeddings_and_store(all_chunks)
86
+ return vector_db
87
+ return None
88
 
89
+ # Gradio interface
90
+ vector_db = process_drive_links()
91
+
92
+ def gradio_query_interface(user_query):
93
+ if vector_db is None:
94
+ return "Error: Could not process Google Drive links."
95
+ if not user_query:
96
+ return "Please enter a query."
97
+ response = query_vector_db(user_query, vector_db)
98
+ return response
 
 
 
 
 
 
 
 
99
 
100
+ iface = gr.Interface(
101
+ fn=gradio_query_interface,
102
+ inputs=gr.Textbox(label="Enter your query:"),
103
+ outputs=gr.Textbox(label="Response from LLM:"),
104
+ title="RAG-Based Application with Google Drive Support",
105
+ description="This application processes predefined Google Drive links, extracts text, and uses embeddings for querying."
106
+ )
107
 
108
+ iface.launch()