malarsaravanan commited on
Commit
85528c4
·
verified ·
1 Parent(s): b6d55b6

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import requests
4
+
5
+ def generate_answer(question, model_name, temperature):
6
+ prompt = "Answer the following question: " + question
7
+ if model_name == "phi1.5":
8
+ tokenizer = AutoTokenizer.from_pretrained("phi1.5")
9
+ input_ids = tokenizer.encode(prompt, return_tensors="pt")
10
+ output = llm_model.generate(input_ids, max_length=512, do_sample=True, top_k=50, top_p=0.9, temperature=temperature)[0]
11
+ answer = tokenizer.decode(output, skip_special_tokens=True)
12
+ end_of_text_index = answer.find("(end of text)")
13
+ if end_of_text_index > -1:
14
+ answer = answer[:end_of_text_index]
15
+ return answer
16
+ elif model_name == "Google Gemini":
17
+ url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
18
+ headers = {"Content-Type": "application/json", "X-goog-api-key": "AIzaSyCfiLsxlpQcdG6hGwCft6-yO4K2c-kp6-o"}
19
+ data = {
20
+ "contents": [{"parts": [{"text": prompt}]}],
21
+ "generationConfig": {"temperature": temperature}
22
+ }
23
+ response = requests.post(url, headers=headers, json=data)
24
+ if response.status_code == 200:
25
+ try:
26
+ return response.json()["candidates"][0]["content"]["parts"][0]["text"]
27
+ except Exception:
28
+ return "Error: Unexpected Gemini API response format."
29
+ else:
30
+ return f"Error: Gemini API call failed ({response.status_code})"
31
+ else:
32
+ return "Invalid model selection."
33
+
34
+ def chatbot(question, model_name, temperature):
35
+ return generate_answer(question, model_name, temperature)
36
+
37
+ if __name__ == "__main__":
38
+ llm_model = AutoModelForCausalLM.from_pretrained("phi1.5", trust_remote_code=True)
39
+ with gr.Blocks(theme="default") as demo:
40
+ gr.Markdown("# I am your AI Health Assistance 🏥\nAsk general health related questions to the AI Bot.")
41
+ model_name = gr.Dropdown(["phi1.5", "Google Gemini"], value="phi1.5", label="Model Selection")
42
+ temperature = gr.Slider(0.0, 1.0, value=0.7, label="Temperature")
43
+ question = gr.Textbox(lines=2, label="Your Question")
44
+ output = gr.Textbox(lines=10, label="AI Response", interactive=False)
45
+ ## connect to backend
46
+ def run_chatbot(q, m, t):
47
+ return chatbot(q, m, t)
48
+ submit_btn = gr.Button("Submit")
49
+ submit_btn.click(run_chatbot, inputs=[question, model_name, temperature], outputs=output)
50
+ demo.launch()
51
+