Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,20 +1,69 @@
|
|
| 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:
|
| 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:
|
|
@@ -25,8 +74,12 @@ def respond(
|
|
| 25 |
|
| 26 |
messages.append({"role": "user", "content": message})
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
| 29 |
|
|
|
|
| 30 |
for message in client.chat_completion(
|
| 31 |
messages,
|
| 32 |
max_tokens=max_tokens,
|
|
@@ -35,29 +88,35 @@ def respond(
|
|
| 35 |
top_p=top_p,
|
| 36 |
):
|
| 37 |
token = message.choices[0].delta.content
|
| 38 |
-
|
| 39 |
response += token
|
| 40 |
yield response
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
"""
|
| 45 |
-
demo = gr.ChatInterface(
|
| 46 |
-
respond,
|
| 47 |
-
additional_inputs=[
|
| 48 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 49 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 50 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 51 |
-
gr.Slider(
|
| 52 |
-
minimum=0.1,
|
| 53 |
-
maximum=1.0,
|
| 54 |
-
value=0.95,
|
| 55 |
-
step=0.05,
|
| 56 |
-
label="Top-p (nucleus sampling)",
|
| 57 |
-
),
|
| 58 |
-
],
|
| 59 |
-
)
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
if __name__ == "__main__":
|
| 63 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
+
from typing import List, Tuple
|
| 4 |
+
import fitz # PyMuPDF
|
| 5 |
+
from sentence_transformers import SentenceTransformer, util
|
| 6 |
+
import numpy as np
|
| 7 |
+
import faiss
|
| 8 |
|
| 9 |
+
# Initialize the Inference Client
|
|
|
|
|
|
|
| 10 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 11 |
|
| 12 |
+
# Define the MyApp class to manage text file processing and vector database
|
| 13 |
+
class MyApp:
|
| 14 |
+
def __init__(self) -> None:
|
| 15 |
+
self.documents = []
|
| 16 |
+
self.embeddings = None
|
| 17 |
+
self.index = None
|
| 18 |
+
self.load_text_file("requirements.txt") # Replace with your actual text file path
|
| 19 |
+
self.build_vector_db()
|
| 20 |
|
| 21 |
+
def load_text_file(self, file_path: str) -> None:
|
| 22 |
+
"""Extracts text from a text file and stores it in the app's documents."""
|
| 23 |
+
with open(file_path, 'r') as file:
|
| 24 |
+
text = file.read()
|
| 25 |
+
self.documents.append({"content": text})
|
| 26 |
+
print("Text file processed successfully!")
|
| 27 |
+
|
| 28 |
+
def build_vector_db(self) -> None:
|
| 29 |
+
"""Builds a vector database using the content of the text file."""
|
| 30 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 31 |
+
# Generate embeddings for the document content
|
| 32 |
+
self.embeddings = model.encode([doc["content"] for doc in self.documents])
|
| 33 |
+
# Create a FAISS index
|
| 34 |
+
self.index = faiss.IndexFlatL2(self.embeddings.shape[1])
|
| 35 |
+
# Add the embeddings to the index
|
| 36 |
+
self.index.add(np.array(self.embeddings))
|
| 37 |
+
print("Vector database built successfully!")
|
| 38 |
+
|
| 39 |
+
def search_documents(self, query: str, k: int = 3) -> List[str]:
|
| 40 |
+
"""Searches for relevant documents using vector similarity."""
|
| 41 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 42 |
+
# Generate an embedding for the query
|
| 43 |
+
query_embedding = model.encode([query])
|
| 44 |
+
# Perform a search in the FAISS index
|
| 45 |
+
D, I = self.index.search(np.array(query_embedding), k)
|
| 46 |
+
# Retrieve the top-k documents
|
| 47 |
+
results = [self.documents[i]["content"] for i in I[0]]
|
| 48 |
+
return results if results else ["No relevant documents found."]
|
| 49 |
+
|
| 50 |
+
# Instantiate the app
|
| 51 |
+
app = MyApp()
|
| 52 |
+
|
| 53 |
+
# Define the respond function for the chatbot
|
| 54 |
def respond(
|
| 55 |
+
message: str,
|
| 56 |
+
history: List[Tuple[str, str]],
|
| 57 |
+
system_message: str,
|
| 58 |
+
max_tokens: int,
|
| 59 |
+
temperature: float,
|
| 60 |
+
top_p: float,
|
| 61 |
):
|
| 62 |
+
system_message = ("You are a knowledgeable sustainability consultant for the Environmental Issues. "
|
| 63 |
+
"You provide concise and accurate advice on sustainability practices, "
|
| 64 |
+
"and you encourage environmentally friendly habits. Remember to greet the user warmly, "
|
| 65 |
+
"ask relevant questions, and offer supportive and insightful responses.")
|
| 66 |
+
|
| 67 |
messages = [{"role": "system", "content": system_message}]
|
| 68 |
|
| 69 |
for val in history:
|
|
|
|
| 74 |
|
| 75 |
messages.append({"role": "user", "content": message})
|
| 76 |
|
| 77 |
+
# RAG - Retrieve relevant documents
|
| 78 |
+
retrieved_docs = app.search_documents(message)
|
| 79 |
+
context = "\n".join(retrieved_docs)
|
| 80 |
+
messages.append({"role": "system", "content": "Relevant documents: " + context})
|
| 81 |
|
| 82 |
+
response = ""
|
| 83 |
for message in client.chat_completion(
|
| 84 |
messages,
|
| 85 |
max_tokens=max_tokens,
|
|
|
|
| 88 |
top_p=top_p,
|
| 89 |
):
|
| 90 |
token = message.choices[0].delta.content
|
|
|
|
| 91 |
response += token
|
| 92 |
yield response
|
| 93 |
|
| 94 |
+
# Create the Gradio interface
|
| 95 |
+
demo = gr.Blocks()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
with demo:
|
| 98 |
+
gr.Markdown("🌍 **Environmnetal Issues**")
|
| 99 |
+
gr.Markdown(
|
| 100 |
+
"‼️Disclaimer: This chatbot is based on publicly available sustainability guidelines and practices. "
|
| 101 |
+
"We are not certified sustainability experts, and the use of this chatbot is at your own responsibility.‼️"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
chatbot = gr.ChatInterface(
|
| 105 |
+
respond,
|
| 106 |
+
examples=[
|
| 107 |
+
["What are the main causes of air pollution in urban areas?"],
|
| 108 |
+
["How does deforestation contribute to global warming?"],
|
| 109 |
+
["What are some of the adverse effects of plastic waste on marine life?"],
|
| 110 |
+
["Can you explain the concept of carbon footprint and why it’s important?"],
|
| 111 |
+
["What are some effective ways to reduce water pollution?"],
|
| 112 |
+
["How does climate change impact biodiversity?"],
|
| 113 |
+
["What is the role of renewable energy in reducing environmental degradation?"],
|
| 114 |
+
["What are the health impacts of living in areas with high levels of pollution?"],
|
| 115 |
+
["How can individuals contribute to environmental conservation?"],
|
| 116 |
+
["What is the impact of industrialization on natural resources?"],
|
| 117 |
+
],
|
| 118 |
+
title='Environmental Issues🌞'
|
| 119 |
+
)
|
| 120 |
|
| 121 |
if __name__ == "__main__":
|
| 122 |
demo.launch()
|