File size: 12,070 Bytes
c893785
 
 
 
 
fd6c26a
c893785
 
 
 
 
 
 
 
 
 
 
fd6c26a
 
c893785
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd6c26a
c893785
fd6c26a
 
 
c893785
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd6c26a
 
c893785
 
 
 
 
 
 
 
 
 
 
 
 
fd6c26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c893785
 
fd6c26a
c893785
 
 
 
 
 
 
fd6c26a
 
c893785
 
 
 
 
 
 
 
 
 
 
 
fd6c26a
 
 
 
 
 
 
c893785
 
fd6c26a
c893785
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd6c26a
c893785
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd6c26a
 
c893785
 
 
 
 
 
 
 
 
 
 
 
 
 
fd6c26a
c893785
 
 
 
 
 
 
 
fd6c26a
 
 
 
 
 
 
 
 
 
 
 
 
c893785
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import base64
import streamlit as st
from streamlit_chat import message
from streamlit_extras.colored_header import colored_header
from streamlit_extras.add_vertical_space import add_vertical_space
from datetime import datetime
import requests
from gradio_client import Client
import datetime as dt
import urllib.parse


st.set_page_config(page_title="HugChat - An LLM-powered Streamlit app")

API_TOKEN = st.secrets['HF_TOKEN']
API_URL = "https://api-inference.huggingface.co/models/mistralai/Mixtral-8x7B-Instruct-v0.1"
headers = {"Authorization": f"Bearer {str(API_TOKEN)}"}

API_URL1 = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"

soil_types = {
    "Sais plain": "Brown limestone, vertisols, lithosols, and regosols",
    "Chaouïa, Doukkala, and Abda plains": "Rendzines associated with lithosols in the Atlantic coast and isohumic and vertisols inland",
    "Eastern High Plateaux and Moulouya Valley": "Sierozems and fluvisols",
    "Rif": "Brown soils associated with lithosols and regosols or vertisols",
    "Mamora and Zemmour plateau": "Sandy soil",
    "Middle Atlas": "Brown soils and rendzinas",
    "High Atlas": "Lithosols and regosols, in association with brown soils and sierozems",
    "Loukkos": "Mostly gleysols and brunified",
    "Rharb plain": "Gleysols and vertisols",
    "Central plateau": "In forested areas, soils are brown associated with lithosols and regosols. Elsewhere (Zaer), vertisols and gleysols dominate",
    "Plains and plateaux of north of the Atlas": "Lithosols (Rehamnas, Jebilete), sierozems associated with lithosols",
    "Argan zone": "Soils are mostly lithosols and regosols, associated with fluvisols and saline soils on lowlands",
    "Presaharan soils": "Lithosols and regosols in association with sierozems and regs",
    "Saharan zone": "Yermosols, associated with sierozems, lithosols, and saline soils"
    }

def get_text():
    input_text = st.text_input("You: ", "", key="input")
    return input_text

def get_weather_data(city):
    base_url = "http://api.openweathermap.org/data/2.5/weather?"
    api_key = "84f9ed7c3738f567e5f1cbf2068d96a6"  # API key
    encoded_api_key = urllib.parse.quote(api_key)  # URL encoding the API key

    url = base_url + "appid=" + encoded_api_key + "&q=" + city

    try:
        response = requests.get(url)
        response.raise_for_status()
        weather_data = response.json()
        
        # Processing the weather data
        temp_kelvin = weather_data['main']['temp']
        humidity = weather_data['main']['humidity']
        weather_condition = weather_data['weather'][0]['description']

        # Converting temperature to Celsius
        temp_celsius = temp_kelvin - 273.15

        return {
            "temperature": f"{temp_celsius:.2f}C",
            "humidity": f"{humidity}%",
            "weather_condition": weather_condition
        }
    except requests.exceptions.HTTPError as err:
        print(f"HTTP error: {err}")
        return None
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")
        return None

def query(payload, api_url):
	response = requests.post(api_url, headers=headers, json=payload)
	return response.json()
	
def translate(text,source="English",target="Moroccan Arabic"):
    client = Client("https://facebook-seamless-m4t-v2-large.hf.space/--replicas/2bmbx/")
    result = client.predict(
            text,	# str  in 'Input text' Textbox component
            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
            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
                                api_name="/t2tt"
    )
    print(result)
    return result

def search_url(search_query):
    API_KEY = st.secrets['API_TOKEN']
    SEARCH_ENGINE_ID = st.secrets['SEARCH_ENGINE_ID']
    
    url = 'https://www.googleapis.com/customsearch/v1'

    params = {
        'q': search_query,
        'key': API_KEY,
        'cx': SEARCH_ENGINE_ID,
    }

    response = requests.get(url, params=params)

    results = response.json()

    # print(results)

    if 'items' in results:
        for i in range(min(5, len(results['items']))):
            print(f"Link {i + 1}: {results['items'][i]['link']}")
        return results['items'][:5]
    else:
        print("No search results found.")
        return None

def get_search_query(response):
    instruction = f'''
        Based on these information, generate a short summarized search terms. Don't include weather specifications.
        Information : {response} 
        Search term keyword:
    '''
    
    output = query({"inputs": instruction, "parameters":{"max_new_tokens":40, "temperature":.3, "return_full_text":False}}, API_URL1)
    print(instruction)
    print(output)
    ss = output[0]['generated_text'][:output[0]['generated_text'].find('\n')]
    print(ss)
    return ss

# Function to generate a response from the chatbot
def generate_response(user_input, region, date):

    city = "Fez"
    weather_info = get_weather_data(city)
    if weather_info:
        print(weather_info)
        
    user_input_translated = str(translate(user_input, "Moroccan Arabic", "English"))
    name = 'Fellah'
    date = date
    location = 'Fes, Morocco'
    soil_type = soil_types[region]  # Use the selected region's soil type
    humidity = weather_info["humidity"]
    weather = weather_info["weather_condition"]
    temp = weather_info["temperature"]
    # agriculture = 'olives'

    # Add your chatbot logic here
    # For simplicity, the bot echoes the user's input in this example

    instruction = f'''
    <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
    Location: {location},
    Current Month : {date}
    land type: {soil_types[region]}
    humidity: {humidity}
    weather: {weather}
    temperature: {temp}
    Question: {user_input_translated}[/INST]</s>
    '''

    output = query({"inputs": instruction, "parameters":{"max_new_tokens":250, "temperature":1, "return_full_text":False}}, API_URL)
    # print(headers)
    print(instruction)
    print(output)
    return f"Bot: {translate(output[0]['generated_text'])}"

def sidebar_bg(side_bg):

   side_bg_ext = 'png'

   st.markdown(
      f"""
      <style>
      [data-testid="stSidebar"] > div:first-child {{
          background: url(data:image/{side_bg_ext};base64,{base64.b64encode(open(side_bg, "rb").read()).decode()});
      }}
      </style>
      """,
      unsafe_allow_html=True,
      )

def main():
    # Sidebar contents
    with st.sidebar:
        st.title('Smart فْلاّح 🌱👩🏻‍🌾')
        st.markdown('''
        ## About
        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.
        
        💡 Note: No API key required!
        ''')
        add_vertical_space(5)
        st.write('Made with ❤️ by [llama-crew](https://huggingface.co/smart-fellah)')

    # Generate empty lists for generated and past.
    ## generated stores AI generated responses
    if 'generated' not in st.session_state:
        st.session_state['generated'] = ["واحد السلام عليكم 👋🏻، كيفاش نقدر نعاونك؟"]
    ## past stores User's questions
    if 'past' not in st.session_state:
        st.session_state['past'] = ['سلام!']

    # sidebar_bg('bg.jpg')
    # Layout of input/response containers
    input_container = st.container()
    selected_region = st.selectbox("Choose a region:", list(soil_types.keys()))

    if st.button("Clear Chat"):
        st.session_state['past'] = []
        st.session_state['generated'] = []

    colored_header(label='', description='', color_name='blue-30')
    response_container = st.container()
    
    date = datetime.now().month

    # User input
    ## Function for taking user provided prompt as input
    
    ## Applying the user input box
    with input_container:
        user_input = get_text()

    # Response output
    ## Function for taking user prompt as input followed by producing AI generated responses

    ## Conditional display of AI generated responses as a function of user provided prompts
    with response_container:
        if user_input:
            response = generate_response(user_input,str(selected_region), str(date))
            st.session_state.past.append(user_input)
            st.session_state.generated.append(response)
            
        if st.session_state['generated']:
            for i in range(len(st.session_state['generated'])):
                message(st.session_state['past'][i], is_user=True, key=str(i) + '_user', logo="https://i.pinimg.com/originals/d5/b2/13/d5b21384ccaaa6f9ef32986f17c50638.png")
                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")

                # Add Google icon button to retrieve links
                if st.button(f"Double-Check Response", key=f"google_button_{i}"):
                    search_query = get_search_query(st.session_state['generated'][i])
                    retrieved_links = search_url(search_query)
                    if retrieved_links:
                        st.markdown("**Google Search Results:**")
                        for j, link in enumerate(retrieved_links):
                            st.markdown(f"{j + 1}. [{link['title']}]({link['link']})")

                            # Display Google logo
                            google_logo_url = "https://www.gstatic.com/webp/gallery/2.jpg"
                            st.image(google_logo_url, width=50, caption="Google Logo")
        
if __name__ == "__main__":
    main()