Balaprime commited on
Commit
584cd3e
·
verified ·
1 Parent(s): f0aa357

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -59
app.py CHANGED
@@ -1,64 +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
- """
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 gradio as gr
2
+ from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
3
+ from llama_index.llms.huggingface import HuggingFaceInferenceAPI
4
+ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
5
+ import os
6
+ from pathlib import Path
7
+ import shutil
8
+
9
+ # Set up Hugging Face API token (replace with your token or set in HF Spaces secrets)
10
+ os.environ["HF_TOKEN"] = os.getenv("HF_TOKEN", "your-huggingface-api-token")
11
+
12
+ # Initialize Mistral model for text generation
13
+ llm = HuggingFaceInferenceAPI(
14
+ model_name="mistralai/Mistral-7B-Instruct-v0.3",
15
+ api_key=os.environ["HF_TOKEN"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  )
17
 
18
+ # Initialize embedding model for document indexing
19
+ embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
20
+
21
+ # Directory to store uploaded documents
22
+ DOCS_DIR = "policy_docs"
23
+ if not os.path.exists(DOCS_DIR):
24
+ os.makedirs(DOCS_DIR)
25
+
26
+ # Global variable to store the index
27
+ index = None
28
+
29
+ def process_document(file):
30
+ """Process uploaded policy document and create an index."""
31
+ global index
32
+ try:
33
+ # Clear previous documents
34
+ if os.path.exists(DOCS_DIR):
35
+ shutil.rmtree(DOCS_DIR)
36
+ os.makedirs(DOCS_DIR)
37
+
38
+ # Save uploaded file
39
+ file_path = os.path.join(DOCS_DIR, file.name)
40
+ shutil.copy(file.name, file_path)
41
+
42
+ # Load documents
43
+ documents = SimpleDirectoryReader(DOCS_DIR).load_data()
44
+
45
+ # Create index
46
+ index = VectorStoreIndex.from_documents(documents, embed_model=embed_model)
47
+
48
+ return "Document processed successfully! You can now ask questions about the policy."
49
+ except Exception as e:
50
+ return f"Error processing document: {str(e)}"
51
+
52
+ def policy_chat(message, history):
53
+ """Handle user queries about the policy with context-aware responses."""
54
+ global index
55
+ if index is None:
56
+ return "Please upload a policy document first."
57
+
58
+ try:
59
+ # Create query engine
60
+ query_engine = index.as_query_engine(llm=llm, similarity_top_k=3)
61
+
62
+ # Craft a prompt that considers financial and other perspectives
63
+ prompt = (
64
+ f"You are a policy expert. A user has asked: '{message}'. "
65
+ "Based on the uploaded policy document, provide a concise response addressing the user's query. "
66
+ "Consider financial, practical, and other relevant perspectives. "
67
+ "If the query is about whether the policy works for the user, evaluate eligibility and benefits clearly. "
68
+ "Keep the response brief and clear."
69
+ )
70
+
71
+ # Query the index
72
+ response = query_engine.query(prompt)
73
+
74
+ # Append to history
75
+ history.append({"role": "user", "content": message})
76
+ history.append({"role": "assistant", "content": str(response)})
77
+ return history
78
+ except Exception as e:
79
+ return f"Error processing query: {str(e)}"
80
+
81
+ # Gradio interface
82
+ with gr.Blocks() as demo:
83
+ gr.Markdown("# Policy Bot")
84
+ gr.Markdown("Upload a policy document (PDF, text, etc.) and ask questions about it. The bot will analyze the policy and respond from financial, practical, and other perspectives.")
85
+
86
+ # File upload for policy documents
87
+ file_input = gr.File(label="Upload Policy Document")
88
+ upload_button = gr.Button("Process Document")
89
+ upload_output = gr.Textbox(label="Upload Status")
90
+
91
+ # Chat interface
92
+ chatbot = gr.Chatbot(type="messages")
93
+ msg = gr.Textbox(placeholder="Ask about the policy (e.g., 'Will this policy cover my medical expenses?')")
94
+ clear = gr.ClearButton([msg, chatbot])
95
+
96
+ # Event handlers
97
+ upload_button.click(process_document, inputs=file_input, outputs=upload_output)
98
+ msg.submit(policy_chat, inputs=[msg, chatbot], outputs=chatbot)
99
 
100
  if __name__ == "__main__":
101
+ demo.launch()