elthra commited on
Commit
d26ed7b
·
1 Parent(s): 4bff8cd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gtts import gTTS
2
+ import gradio as gr
3
+ import IPython.display as ipd
4
+ import os
5
+ import numpy as np
6
+
7
+
8
+ conversation_flow = {
9
+ "hello": "Hi there, I can answer questions like disease, treatment, prevention, and medicine! How can I help you ",
10
+
11
+ "about ocular disease": "Ocular cattle disease, also known as infectious bovine keratoconjunctivitis, is a contagious eye infection affecting cattle. It is caused by bacteria like Moraxella bovis and spreads through direct contact or contaminated environments. The disease leads to painful inflammation, discharge, and in severe cases, can cause blindness, impacting the health and productivity of the affected cattle.",
12
+ "ocular disease": "Ocular cattle disease, also known as infectious bovine keratoconjunctivitis, is a contagious eye infection affecting cattle. It is caused by bacteria like Moraxella bovis and spreads through direct contact or contaminated environments. The disease leads to painful inflammation, discharge, and in severe cases, can cause blindness, impacting the health and productivity of the affected cattle.",
13
+ "ocular disease treatment": "Treatment for ocular cattle disease typically involves administering antibiotics such as oxytetracycline or florfenicol to combat the bacterial infection. In addition to antibiotics, supportive care like eye ointments and pain relief medications may be provided to alleviate discomfort and promote healing. Proper hygiene, quarantine measures, and vaccination can also help prevent the spread of the disease within the cattle herd.",
14
+ "ocular disease medicine":"Medicines for ocular diseases vary depending on the specific condition. Common treatments include antibiotic eye drops or ointments to combat infections caused by bacteria, antiviral medications for viral infections like herpes simplex keratitis, and anti-inflammatory drugs to reduce swelling and discomfort. In some cases, lubricating eye drops or artificial tears are used to alleviate dryness and irritation, providing relief for various ocular disorders.",
15
+ "ocular disease prevention":"Preventing ocular diseases in cattle requires implementing proper herd management practices, including maintaining clean and dry living conditions to minimize bacterial contamination. Regular vaccination against common pathogens like Moraxella bovis can significantly reduce the risk of infectious bovine keratoconjunctivitis. Additionally, providing adequate nutrition, minimizing stress, and ensuring proper eye protection in areas prone to dust or irritants are essential measures to safeguard cattle from ocular diseases.",
16
+
17
+ "ringworm disease":"Ringworm in cattle is a highly contagious fungal infection caused by various species of dermatophytes. It manifests as circular, hairless lesions on the skin, leading to itching and discomfort. Proper hygiene, isolation of infected animals, and topical antifungal treatments are crucial for controlling the spread of ringworm in cattle herds.",
18
+ "ringworm disease prevention":"Preventing ringworm in cattle involves maintaining clean and dry living conditions, as the fungus thrives in damp environments. Regular grooming and cleaning of cattle, along with proper disinfection of equipment and facilities, can minimize the risk of infection. Quarantining new animals and promptly isolating and treating infected cattle are essential steps to prevent the spread of ringworm within the herd.",
19
+ "ringworm disease treatment":"Treating ringworm in cattle typically involves topical antifungal medications like iodine-based solutions or creams, which are applied directly to the affected areas. Keeping the infected cattle isolated to prevent further spread is crucial. Additionally, providing a well-balanced diet and ensuring proper hygiene in the environment can aid in the animal's recovery from ringworm.",
20
+ "ringworm disease medicine":"Medicines for ringworm in cattle often include antifungal creams, sprays, or shampoos containing ingredients like miconazole or clotrimazole. These topical treatments are applied directly to the affected areas to eliminate the fungal infection. Additionally, oral antifungal medications might be prescribed in severe cases, aiding in the complete eradication of ringworm in cattle.",
21
+
22
+ "photosensation disease":"Photosensitization in cattle is a condition where their skin becomes overly sensitive to sunlight, leading to severe inflammation and blistering. It can result from ingesting certain plants or substances, causing liver damage and a buildup of photodynamic compounds in the skin. Prevention involves removing harmful plants from pastures, providing shaded areas, and consulting veterinarians for proper diagnosis and management.",
23
+ "photosensation disease prevention":"Preventing photosensitization in cattle involves careful management of their diet to avoid plants like St. John's Wort and buckwheat, known to trigger the condition. Providing adequate nutrition and balanced diets can support liver function, reducing the risk of photosensitization. Additionally, ensuring access to shaded areas during sunny periods and regular veterinary check-ups are vital preventive measures against this disease.",
24
+ "photosensation disease treatment":"Treating photosensitization in cattle involves removing the animals from the source of the photodynamic compounds, such as specific toxic plants. Supportive care, like providing shade and applying soothing topical treatments to affected skin, helps alleviate discomfort. Veterinarians might administer medications to address underlying liver issues, aiding in the overall recovery of cattle affected by photosensitization.",
25
+ "photosensation disease medicine":"There is no specific medicine to treat photosensitization in cattle; however, supportive care and symptomatic treatment are provided. Veterinarians may prescribe anti-inflammatory medications and pain relief drugs to alleviate discomfort. Focus is primarily on removing the source of photodynamic compounds, managing skin lesions, and ensuring the affected cattle receive proper nutrition and hydration during the recovery process.",
26
+
27
+ "blue tongue disease":"Blue tongue disease in cattle is a viral illness transmitted by certain species of biting insects, primarily midges. It causes fever, swollen tongue, and oral lesions, leading to difficulty in eating and drooling. Prevention involves vaccination, controlling insect vectors, and quarantine measures to restrict the movement of infected animals, mitigating the spread of this disease within cattle populations.",
28
+ "blue tongue disease prevention":"Preventing blue tongue disease in cattle involves implementing rigorous insect control measures to reduce exposure to biting midges, the primary vectors of the virus. Regular vaccination of cattle against blue tongue virus serotypes prevalent in the region is essential. Quarantine protocols for introducing new animals and maintaining a vector-free environment are crucial steps to prevent the spread of this disease within cattle herds.",
29
+ "blue tongue disease treatment":"There is no specific cure for blue tongue disease in cattle. Supportive care, such as providing fluids, nutritional support, and anti-inflammatory medications, can help manage symptoms and improve the animal's comfort. Quarantine and insect control measures are crucial to prevent the disease from spreading, as there is no direct treatment to eliminate the virus in affected cattle.",
30
+ "blue tongue disease medicine":"There is no specific medicine to treat blue tongue disease in cattle; however, supportive care is provided to manage symptoms. Anti-inflammatory drugs and pain relief medications can help alleviate discomfort. Prevention through vaccination and insect control remains the primary focus in managing this viral disease in cattle herds.",
31
+
32
+ "papillomatosis disease":"Papillomatosis in cattle is a viral skin disease caused by papillomaviruses, leading to the formation of wart-like growths on the skin and mucous membranes. While the condition is usually benign, it can cause discomfort and affect cattle aesthetics. Treatment options include surgical removal, cryotherapy, or topical applications to minimize the growths and prevent their spread within the herd.",
33
+ "papillomatosis disease prevention":"Preventing papillomatosis in cattle involves maintaining good hygiene practices within the herd and avoiding direct contact with infected animals or their contaminated equipment. Regular monitoring and prompt removal of any developing warts can prevent further transmission. Implementing quarantine measures for introducing new cattle and proper sanitation in the environment can significantly reduce the risk of papillomatosis within cattle populations.",
34
+ "papillomatosis disease treatment":"Treatment for papillomatosis in cattle typically involves physical removal of warts through methods like surgical excision or cryotherapy. Topical applications of antiviral agents or caustic chemicals can also be used to shrink the growths. Proper isolation of affected animals and maintaining a clean environment are essential during the healing process to prevent reinfection and transmission to other cattle.",
35
+ "papillomatosis disease medicine":"There is no specific medicine to directly treat papillomatosis in cattle. However, topical applications of chemicals like salicylic acid or formalin solutions are commonly used to shrink the warts. Additionally, immunomodulatory medications might be prescribed to boost the animal's immune response, aiding in the natural regression of papillomatosis growths over time.",
36
+
37
+ "default": "I'm not sure how to respond to that. Can you ask me something else?"
38
+ }
39
+
40
+
41
+
42
+ class Chatbot:
43
+ def __init__(self):
44
+ self.chat_history = []
45
+
46
+ def respond(self, user_input, session_id):
47
+ # Check if the session_id is different from the current session
48
+ if len(self.chat_history) > 0 and self.chat_history[0]["session_id"] != session_id:
49
+ # If it's a new session, clear the chat history
50
+ self.chat_history.clear()
51
+
52
+ # Check if the input text matches predefined questions
53
+ if user_input.lower() in conversation_flow:
54
+ response = conversation_flow[user_input.lower()]
55
+ else:
56
+ # If the input doesn't match, use the default response
57
+ response = conversation_flow["default"]
58
+
59
+ # Add the user input, response, and session_id to the chat history
60
+ self.chat_history.append({"user": user_input, "bot": response, "session_id": session_id})
61
+
62
+ # Format the chat history as a conversation
63
+ chat_history_formatted = ""
64
+ for chat in self.chat_history:
65
+ chat_history_formatted += f'User: {chat["user"]}<br>Bot: {chat["bot"]}<br><br>'
66
+
67
+ # Convert the response to speech
68
+ translated_speech_path = self.text_to_speech(response, session_id)
69
+
70
+ return response, chat_history_formatted, translated_speech_path
71
+
72
+ def text_to_speech(self, text, session_id):
73
+ # Generate speech from text using gTTS and save it to a temporary file
74
+ temp_file = f"{session_id}.mp3"
75
+ tts = gTTS(text=text, lang='en') # Use English for speech synthesis
76
+ tts.save(temp_file)
77
+ return temp_file
78
+
79
+ # Create a Gradio interface for the chatbot with custom HTML layout
80
+ chatbot = Chatbot()
81
+ def custom_layout(current_output, chat_history, translated_speech_path):
82
+ # Load the audio file as a numpy array
83
+ audio_data = np.array(gTTS(translated_speech_path).get_array_of_samples())
84
+
85
+ # Delete the temporary audio file if it exists
86
+ if os.path.exists(translated_speech_path):
87
+ os.remove(translated_speech_path)
88
+
89
+ return f"""
90
+ <div style="margin-bottom: 10px;">
91
+ <strong>Bot:</strong> {current_output}
92
+ </div>
93
+ <div>
94
+ <strong>Chat History:</strong><br>
95
+ {chat_history}
96
+ </div>
97
+ {gr.outputs.Audio(audio_data, type='numpy', embed=True)}
98
+ """
99
+
100
+ # ... (code to create Gradio interface remains unchanged)
101
+
102
+ chatbot_interface = gr.Interface(
103
+ fn=chatbot.respond,
104
+ inputs="text",
105
+ outputs=["text", "html", gr.outputs.Audio(type='numpy')],
106
+ layout=custom_layout,
107
+ title="Chatbot Assistant"
108
+ )
109
+ chatbot_interface.launch()