punitub01 commited on
Commit
3e0863f
verified
1 Parent(s): de938c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -62
app.py CHANGED
@@ -1,64 +1,63 @@
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
+ import torch
3
+ import pandas as pd
4
+ import faiss
5
+ from sentence_transformers import SentenceTransformer
6
+ from transformers import AutoTokenizer, AutoModelForCausalLM
7
+
8
+ # Initialize components (automatically cached)
9
+ def load_components():
10
+ tokenizer = AutoTokenizer.from_pretrained("punitub01/llama2-7b-qlora-finetuned")
11
+ model = AutoModelForCausalLM.from_pretrained(
12
+ "punitub01/llama2-7b-qlora-finetuned",
13
+ device_map="cpu",
14
+ torch_dtype= torch.float32
15
+ )
16
+ encoder = SentenceTransformer('all-MiniLM-L6-v2')
17
+ index = faiss.read_index("diabetes_abstracts.index")
18
+ metadata = pd.read_csv("diabetes_metadata.csv")
19
+ return tokenizer, model, encoder, index, metadata
20
+
21
+ tokenizer, model, encoder, index, metadata = load_components()
22
+ chat_history = []
23
+
24
+ def summarize_with_llama(text):
25
+ prompt = f"""Summarize this medical information in 1-2 lines:
26
+ {text}
27
+ Concise summary:"""
28
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
29
+ with torch.no_grad():
30
+ outputs = model.generate(**inputs, max_new_tokens=100, temperature=0.1)
31
+ return tokenizer.decode(outputs[0], skip_special_tokens=True).split("Concise summary:")[-1].strip()
32
+
33
+ def respond(message, history):
34
+ # Semantic search
35
+ query_embed = encoder.encode([message])
36
+ distances, indices = index.search(query_embed, k=3)
37
+
38
+ # Build context
39
+ references = [
40
+ f"{metadata.iloc[idx]['title']} (Score: {dist:.2f})"
41
+ for idx, dist in zip(indices[0], distances[0]) if dist >= 0.3
42
+ ]
43
+ context_summary = summarize_with_llama("\n".join(references)) if references else "No clinical references"
44
+
45
+ # Generate response
46
+ prompt = f"""Clinical Context: {context_summary}
47
+ Chat History: {history[-2:] if history else 'None'}
48
+ Question: {message}
49
+ Answer:"""
50
+
51
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
52
+ with torch.no_grad():
53
+ outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.7)
54
+
55
+ return tokenizer.decode(outputs[0], skip_special_tokens=True).split("Answer:")[-1].strip()
56
+
57
+ # Gradio interface
58
+ gr.ChatInterface(
59
  respond,
60
+ title="Diabetes Assistant",
61
+ description="Ask questions about diabetes management",
62
+ examples=["What are hypoglycemia symptoms?", "驴C贸mo manejar la diabetes tipo 2?"]
63
+ ).launch()