Muhirwa12a commited on
Commit
8697543
·
verified ·
1 Parent(s): c3b3349

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -48
app.py CHANGED
@@ -1,64 +1,131 @@
 
 
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 pandas as pd
3
  import gradio as gr
 
4
 
5
+ ###################################
6
+ # 1. Load and Chunk CSV Data
7
+ ###################################
8
+ df = pd.read_csv("datasets.csv")
9
 
10
+ # We will chunk the rows in groups of 1,000
11
+ chunk_size = 1000
12
+ context_data = []
13
 
14
+ for start_index in range(0, len(df), chunk_size):
15
+ # Collect rows for one chunk
16
+ chunk_rows = df.iloc[start_index : start_index + chunk_size]
 
 
 
 
 
 
17
 
18
+ # Build a single text block for these rows
19
+ text_block = ""
20
+ for row_idx in range(len(chunk_rows)):
21
+ row_data = chunk_rows.iloc[row_idx]
22
+ for col_name in df.columns:
23
+ text_block += f"{col_name}: {str(row_data[col_name])} "
24
+ text_block += "\n" # separate rows for clarity
25
 
26
+ context_data.append(text_block)
27
 
28
+ ###################################
29
+ # 2. Retrieve API Key
30
+ ###################################
31
+ groq_key = os.environ.get('groq_api_keys')
32
 
33
+ ###################################
34
+ # 3. Language Model & Embeddings
35
+ ###################################
36
+ from langchain_groq import ChatGroq
37
+ llm = ChatGroq(
38
+ model="llama-3.1-70b-versatile",
39
+ api_key=groq_key
40
+ )
41
 
42
+ from langchain_huggingface import HuggingFaceEmbeddings
43
+ embed_model = HuggingFaceEmbeddings(
44
+ model_name="mixedbread-ai/mxbai-embed-large-v1"
45
+ )
46
 
47
+ ###################################
48
+ # 4. Vector Store
49
+ ###################################
50
+ from langchain_chroma import Chroma
51
 
52
+ vectorstore = Chroma(
53
+ collection_name="professional_medical_store",
54
+ embedding_function=embed_model,
55
+ persist_directory="./",
56
+ )
57
+
58
+ # Add chunked data to the vector store
59
+ vectorstore.add_texts(context_data)
60
+ retriever = vectorstore.as_retriever()
61
+
62
+ ###################################
63
+ # 5. Prompt Configuration
64
+ ###################################
65
+ from langchain_core.prompts import PromptTemplate
66
+ from langchain_core.runnables import RunnablePassthrough
67
+ from langchain_core.output_parsers import StrOutputParser
68
+
69
+ prompt_template = """
70
+ You are a supportive and professional mental-health consultant with extensive medical knowledge.
71
+ Speak compassionately while maintaining a calm, informative tone.
72
+ Use the context to answer questions about mental well-being or related medical considerations.
73
+ If you do not know the answer, say so without hesitation.
74
+ Focus on providing actionable insights without explicitly mentioning the context.
75
+ Always encourage users to seek professional or emergency help where appropriate.
76
+
77
+ Context: {context}
78
+ Question: {question}
79
+ Answer:
80
  """
81
+
82
+ rag_prompt = PromptTemplate.from_template(prompt_template)
83
+
84
+ rag_chain = (
85
+ {"context": retriever, "question": RunnablePassthrough()}
86
+ | rag_prompt
87
+ | llm
88
+ | StrOutputParser()
 
 
 
 
 
 
 
 
89
  )
90
 
91
+ ###################################
92
+ # 6. Gradio Interface
93
+ ###################################
94
+ def chain_stream(user_input):
95
+ partial_text = ""
96
+ for new_text in rag_chain.stream(user_input):
97
+ partial_text += new_text
98
+ yield partial_text
99
+
100
+ examples = [
101
+ "I have been feeling anxious and unable to focus. Any recommendations?",
102
+ "I've been feeling extremely tired lately—should I see a professional?"
103
+ ]
104
+
105
+ disclaimer = (
106
+ "**Disclaimer**: I am an AI language model and not a licensed healthcare professional. "
107
+ "For urgent concerns, please seek immediate help from qualified medical professionals."
108
+ )
109
+
110
+ title = "Professional Mental Health & Medical Assistant"
111
+
112
+ demo = gr.Interface(
113
+ fn=chain_stream,
114
+ inputs=gr.Textbox(
115
+ lines=3,
116
+ placeholder="Ask your question or describe your situation here..."
117
+ ),
118
+ outputs="text",
119
+ title=title,
120
+ description=(
121
+ "Welcome to your mental-health and medical information companion. "
122
+ "I provide professional, empathetic, and trustworthy guidance. "
123
+ "Please remember this is not a substitute for direct professional consultation."
124
+ ),
125
+ article=disclaimer,
126
+ examples=examples,
127
+ allow_flagging="never",
128
+ )
129
 
130
  if __name__ == "__main__":
131
+ demo.launch(server_name="0.0.0.0", server_port=7860)