medmac01 commited on
Commit
c893785
1 Parent(s): 8269696

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +216 -0
app.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import streamlit as st
3
+ from streamlit_chat import message
4
+ from streamlit_extras.colored_header import colored_header
5
+ from streamlit_extras.add_vertical_space import add_vertical_space
6
+ import requests
7
+ from gradio_client import Client
8
+ import datetime as dt
9
+ import urllib.parse
10
+
11
+
12
+ st.set_page_config(page_title="HugChat - An LLM-powered Streamlit app")
13
+
14
+ API_TOKEN = st.secrets['HF_TOKEN']
15
+ API_URL = "https://api-inference.huggingface.co/models/mistralai/Mixtral-8x7B-Instruct-v0.1"
16
+ headers = {"Authorization": f"Bearer {str(API_TOKEN)}"}
17
+ def get_text():
18
+ input_text = st.text_input("You: ", "", key="input")
19
+ return input_text
20
+
21
+ soil_types = {
22
+ "Sais plain": "Brown limestone, vertisols, lithosols, and regosols",
23
+ "Chaouïa, Doukkala, and Abda plains": "Rendzines associated with lithosols in the Atlantic coast and isohumic and vertisols inland",
24
+ "Eastern High Plateaux and Moulouya Valley": "Sierozems and fluvisols",
25
+ "Rif": "Brown soils associated with lithosols and regosols or vertisols",
26
+ "Mamora and Zemmour plateau": "Sandy soil",
27
+ "Middle Atlas": "Brown soils and rendzinas",
28
+ "High Atlas": "Lithosols and regosols, in association with brown soils and sierozems",
29
+ "Loukkos": "Mostly gleysols and brunified",
30
+ "Rharb plain": "Gleysols and vertisols",
31
+ "Central plateau": "In forested areas, soils are brown associated with lithosols and regosols. Elsewhere (Zaer), vertisols and gleysols dominate",
32
+ "Plains and plateaux of north of the Atlas": "Lithosols (Rehamnas, Jebilete), sierozems associated with lithosols",
33
+ "Argan zone": "Soils are mostly lithosols and regosols, associated with fluvisols and saline soils on lowlands",
34
+ "Presaharan soils": "Lithosols and regosols in association with sierozems and regs",
35
+ "Saharan zone": "Yermosols, associated with sierozems, lithosols, and saline soils"
36
+ }
37
+
38
+
39
+
40
+ def get_weather_data(city):
41
+ base_url = "http://api.openweathermap.org/data/2.5/weather?"
42
+ api_key = "84f9ed7c3738f567e5f1cbf2068d96a6" # API key
43
+ encoded_api_key = urllib.parse.quote(api_key) # URL encoding the API key
44
+
45
+ url = base_url + "appid=" + encoded_api_key + "&q=" + city
46
+
47
+ try:
48
+ response = requests.get(url)
49
+ response.raise_for_status()
50
+ weather_data = response.json()
51
+
52
+ # Processing the weather data
53
+ temp_kelvin = weather_data['main']['temp']
54
+ humidity = weather_data['main']['humidity']
55
+ weather_condition = weather_data['weather'][0]['description']
56
+
57
+ # Converting temperature to Celsius
58
+ temp_celsius = temp_kelvin - 273.15
59
+
60
+ return {
61
+ "temperature": f"{temp_celsius:.2f}C",
62
+ "humidity": f"{humidity}%",
63
+ "weather_condition": weather_condition
64
+ }
65
+ except requests.exceptions.HTTPError as err:
66
+ print(f"HTTP error: {err}")
67
+ return None
68
+ except requests.exceptions.RequestException as e:
69
+ print(f"Error: {e}")
70
+ return None
71
+
72
+ # Example usage
73
+
74
+
75
+ def query(payload):
76
+ response = requests.post(API_URL, headers=headers, json=payload)
77
+ return response.json()
78
+
79
+ def translate(text,source="English",target="Moroccan Arabic"):
80
+ client = Client("https://facebook-seamless-m4t-v2-large.hf.space/--replicas/2bmbx/")
81
+ result = client.predict(
82
+ text, # str in 'Input text' Textbox component
83
+ source, # Literal[Afrikaans, Amharic, Armenian, Assamese, Basque, Belarusian, Bengali, Bosnian, Bulgarian, Burmese, Cantonese, Catalan, Cebuano, Central Kurdish, Croatian, Czech, Danish, Dutch, Egyptian Arabic, English, Estonian, Finnish, French, Galician, Ganda, Georgian, German, Greek, Gujarati, Halh Mongolian, Hebrew, Hindi, Hungarian, Icelandic, Igbo, Indonesian, Irish, Italian, Japanese, Javanese, Kannada, Kazakh, Khmer, Korean, Kyrgyz, Lao, Lithuanian, Luo, Macedonian, Maithili, Malayalam, Maltese, Mandarin Chinese, Marathi, Meitei, Modern Standard Arabic, Moroccan Arabic, Nepali, North Azerbaijani, Northern Uzbek, Norwegian Bokmål, Norwegian Nynorsk, Nyanja, Odia, Polish, Portuguese, Punjabi, Romanian, Russian, Serbian, Shona, Sindhi, Slovak, Slovenian, Somali, Southern Pashto, Spanish, Standard Latvian, Standard Malay, Swahili, Swedish, Tagalog, Tajik, Tamil, Telugu, Thai, Turkish, Ukrainian, Urdu, Vietnamese, Welsh, West Central Oromo, Western Persian, Yoruba, Zulu] in 'Source language' Dropdown component
84
+ target, # Literal[Afrikaans, Amharic, Armenian, Assamese, Basque, Belarusian, Bengali, Bosnian, Bulgarian, Burmese, Cantonese, Catalan, Cebuano, Central Kurdish, Croatian, Czech, Danish, Dutch, Egyptian Arabic, English, Estonian, Finnish, French, Galician, Ganda, Georgian, German, Greek, Gujarati, Halh Mongolian, Hebrew, Hindi, Hungarian, Icelandic, Igbo, Indonesian, Irish, Italian, Japanese, Javanese, Kannada, Kazakh, Khmer, Korean, Kyrgyz, Lao, Lithuanian, Luo, Macedonian, Maithili, Malayalam, Maltese, Mandarin Chinese, Marathi, Meitei, Modern Standard Arabic, Moroccan Arabic, Nepali, North Azerbaijani, Northern Uzbek, Norwegian Bokmål, Norwegian Nynorsk, Nyanja, Odia, Polish, Portuguese, Punjabi, Romanian, Russian, Serbian, Shona, Sindhi, Slovak, Slovenian, Somali, Southern Pashto, Spanish, Standard Latvian, Standard Malay, Swahili, Swedish, Tagalog, Tajik, Tamil, Telugu, Thai, Turkish, Ukrainian, Urdu, Vietnamese, Welsh, West Central Oromo, Western Persian, Yoruba, Zulu] in 'Target language' Dropdown component
85
+ api_name="/t2tt"
86
+ )
87
+ print(result)
88
+ return result
89
+
90
+
91
+ # Function to generate a response from the chatbot
92
+ def generate_response(user_input,region):
93
+
94
+ city = "Fez"
95
+ weather_info = get_weather_data(city)
96
+ if weather_info:
97
+ print(weather_info)
98
+
99
+ user_input_translated = str(translate(user_input, "Moroccan Arabic", "English"))
100
+ name = 'Fellah(a)'
101
+ date = 'December'
102
+ location = 'Fes, Morocco'
103
+ soil_type = soil_types[region] # Use the selected region's soil type
104
+ humidity = weather_info["humidity"]
105
+ weather = weather_info["weather_condition"]
106
+ temp = weather_info["temperature"]
107
+ # agriculture = 'olives'
108
+
109
+ # Add your chatbot logic here
110
+ # For simplicity, the bot echoes the user's input in this example
111
+
112
+ instruction = f'''
113
+ <s> [INST] You are an agriculture expert, and my name is {name} Given the following informations, prevailing weather conditions, specific land type, chosen type of agriculture, and soil composition of a designated area, answer the question below
114
+ Location: {location},
115
+ Current Month : {date}
116
+ land type: {soil_types[region]}
117
+ humidity: {humidity}
118
+ weather: {weather}
119
+ temperature: {temp}
120
+ Question: {user_input_translated}[/INST]</s>
121
+ '''
122
+ prompt = f'''
123
+ You are an agriculture expert, Given the following informations, geographical coordinates (latitude and longitude), prevailing weather conditions, specific land type, chosen type of agriculture, and soil composition of a designated area, request the LLM to provide detailed insights and predictions on optimal agricultural practices, potential crop yields, and recommended soil management strategies, or answer the question below
124
+ Location: {location},
125
+ land type: {soil_type}
126
+ humidity: {humidity}
127
+ weather: {weather}
128
+ temperature: {temp}
129
+ '''
130
+ # output = query({"inputs": f'''
131
+ # PROMPT: {prompt}
132
+ # QUESTION: {user_input}
133
+ # ANSWER:
134
+ # ''',})
135
+
136
+ output = query({"inputs": instruction, "parameters":{"max_new_tokens":250, "temperature":1, "return_full_text":False}})
137
+ # print(headers)
138
+ print(instruction)
139
+ print(output)
140
+ return f"Bot: {translate(output[0]['generated_text'])}"
141
+
142
+ def sidebar_bg(side_bg):
143
+
144
+ side_bg_ext = 'png'
145
+
146
+ st.markdown(
147
+ f"""
148
+ <style>
149
+ [data-testid="stSidebar"] > div:first-child {{
150
+ background: url(data:image/{side_bg_ext};base64,{base64.b64encode(open(side_bg, "rb").read()).decode()});
151
+ }}
152
+ </style>
153
+ """,
154
+ unsafe_allow_html=True,
155
+ )
156
+
157
+ def main():
158
+ # Sidebar contents
159
+ with st.sidebar:
160
+ st.title('Smart فْلاّح 🌱👩🏻‍🌾')
161
+ st.markdown('''
162
+ ## About
163
+ Smart فلاح , an innovative AI-based platform developed in Morocco, uses machine learning, image processing, and harnesses the power of Large Language Models to offer real-time crop insights to farmers in a customized and friendly way. This solution is tailored to the unique agricultural landscape and challenges of Morocco or Africa.
164
+
165
+ 💡 Note: No API key required!
166
+ ''')
167
+ add_vertical_space(5)
168
+ st.write('Made with ❤️ by [llama-crew](https://huggingface.co/llama-crew)')
169
+ #st.write('Made with ❤️ by [llama-crew](https://hf.co/medmac01)')
170
+
171
+
172
+
173
+ # Generate empty lists for generated and past.
174
+ ## generated stores AI generated responses
175
+ if 'generated' not in st.session_state:
176
+ st.session_state['generated'] = ["واحد السلام عليكم 👋🏻، كيفاش نقدر نعاونك؟"]
177
+ ## past stores User's questions
178
+ if 'past' not in st.session_state:
179
+ st.session_state['past'] = ['سلام!']
180
+
181
+ # sidebar_bg('bg.jpg')
182
+ # Layout of input/response containers
183
+ input_container = st.container()
184
+ selected_region = st.selectbox("Choose a region:", list(soil_types.keys()))
185
+
186
+ if st.button("Clear Chat"):
187
+ st.session_state['past'] = []
188
+ st.session_state['generated'] = []
189
+
190
+ colored_header(label='', description='', color_name='blue-30')
191
+ response_container = st.container()
192
+
193
+ # User input
194
+ ## Function for taking user provided prompt as input
195
+
196
+ ## Applying the user input box
197
+ with input_container:
198
+ user_input = get_text()
199
+
200
+ # Response output
201
+ ## Function for taking user prompt as input followed by producing AI generated responses
202
+
203
+ ## Conditional display of AI generated responses as a function of user provided prompts
204
+ with response_container:
205
+ if user_input:
206
+ response = generate_response(user_input,str(selected_region))
207
+ st.session_state.past.append(user_input)
208
+ st.session_state.generated.append(response)
209
+
210
+ if st.session_state['generated']:
211
+ for i in range(len(st.session_state['generated'])):
212
+ message(st.session_state['past'][i], is_user=True, key=str(i) + '_user', logo="https://i.pinimg.com/originals/d5/b2/13/d5b21384ccaaa6f9ef32986f17c50638.png")
213
+ message(st.session_state["generated"][i], key=str(i), logo= "https://emojiisland.com/cdn/shop/products/Robot_Emoji_Icon_7070a254-26f7-4a54-8131-560e38e34c2e_large.png?v=1571606114")
214
+
215
+ if __name__ == "__main__":
216
+ main()