mohamedalcafory commited on
Commit
121c906
1 Parent(s): ad4f152

update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -57
app.py CHANGED
@@ -1,63 +1,101 @@
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
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
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 langchain.prompts import PromptTemplate
3
+ from langchain.embeddings import SentenceTransformerEmbeddings
4
+
5
+ # Set model_kwargs with trust_remote_code=True
6
+ embeddings = SentenceTransformerEmbeddings(
7
+ model_name="nomic-ai/nomic-embed-text-v1.5",
8
+ model_kwargs={"trust_remote_code": True}
9
+ )
10
+
11
+ from langchain_community.vectorstores import FAISS
12
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
13
+ from langchain.document_loaders import TextLoader, PyPDFLoader
14
+
15
+ loader = PyPDFLoader("https://www.versusarthritis.org/media/24901/fibromyalgia-information-booklet-july2021.pdf")
16
+ documents = loader.load()
17
+
18
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
19
+ docs = text_splitter.split_documents(documents)
20
+ vector_store = FAISS.from_documents(docs, embeddings)
21
+ retriever = vector_store.as_retriever()
22
+
23
+ from langchain import hub
24
+ from langchain_core.output_parsers import StrOutputParser
25
+ from langchain_core.runnables import RunnablePassthrough
26
+
27
+ prompt = hub.pull("rlm/rag-prompt")
28
+
29
+ from transformers import AutoTokenizer, AutoModelForCausalLM
30
+ tokenizer = AutoTokenizer.from_pretrained("mohamedalcafory/PubMed_Llama3.1_Based_model")
31
+ model = AutoModelForCausalLM.from_pretrained("mohamedalcafory/PubMed_Llama3.1_Based_model")
32
+
33
+ from transformers import pipeline
34
+ from langchain_huggingface import HuggingFacePipeline
35
+ pipe = pipeline(
36
+ "text-generation",
37
+ model=model,
38
+ tokenizer=tokenizer,
39
+ max_new_tokens=512,
40
+ temperature=0.7,
41
+ top_p=0.95,
42
+ repetition_penalty=1.15
43
+ )
44
+
45
+ llm = HuggingFacePipeline(pipeline=pipe)
46
+
47
+ prompt = PromptTemplate(
48
+ input_variables=["query"],
49
+ template="{query}"
50
+ )
51
+
52
+ # Define the retrieval chain
53
+ retrieve_docs = (lambda x: retriever.get_relevant_documents(x["query"]))
54
+
55
+ # Define the generator chain
56
+ generator_chain = (
57
+ prompt
58
+ | llm
59
+ | StrOutputParser()
60
  )
61
 
62
+ def format_docs(docs):
63
+ # Check if docs is a list of Document objects or just strings
64
+ if docs and hasattr(docs[0], 'page_content'):
65
+ return "\n\n".join(doc.page_content for doc in docs)
66
+ else:
67
+ return "\n\n".join(str(doc) for doc in docs)
68
+
69
+ # Create the full RAG chain
70
+ rag_chain = (
71
+ RunnablePassthrough.assign(context=retrieve_docs)
72
+ | RunnablePassthrough.assign(
73
+ formatted_context=lambda x: format_docs(x["context"])
74
+ )
75
+ | prompt
76
+ | llm
77
+ | StrOutputParser()
78
+ )
79
+
80
+ def process_query(query):
81
+ try:
82
+ response = rag_chain.invoke({"query": query})
83
+ return response
84
+ except Exception as e:
85
+ return f"An error occurred: {str(e)}"
86
+
87
+ # Create Gradio interface
88
+ demo = gr.Interface(
89
+ fn=process_query,
90
+ inputs=gr.Textbox(label= "Your question", lines=2, placeholder="Enter your question here..."),
91
+ outputs=gr.Textbox(label="Response"),
92
+ title="Fibromyalgia Q&A Assistant",
93
+ description="Ask questions and get answers based on the retrieved context.",
94
+ examples=[
95
+ ["How does Physiotherapy work with Fibromyalgia?"],
96
+ ["What are the common treatments for chronic pain?"],
97
+ ]
98
+ )
99
 
100
  if __name__ == "__main__":
101
  demo.launch()