File size: 7,837 Bytes
9fc6d1f
e42f508
52e4886
 
 
e42f508
 
 
52e4886
 
637fb50
e42f508
d0caafa
52e4886
 
 
e42f508
 
 
 
 
 
52e4886
e42f508
 
 
 
 
 
 
 
 
 
 
52e4886
 
 
b9f8ea0
52e4886
b9f8ea0
 
e42f508
b9f8ea0
 
 
e42f508
 
 
 
 
52e4886
e42f508
52e4886
e42f508
 
 
 
b9f8ea0
e42f508
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e4886
 
 
a785f2a
4611bf9
e42f508
9fc6d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e42f508
52e4886
 
9fc6d1f
52e4886
 
9fc6d1f
52e4886
 
 
 
9fc6d1f
52e4886
 
 
 
9fc6d1f
52e4886
 
9fc6d1f
52e4886
9fc6d1f
52e4886
 
e42f508
 
52e4886
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fc6d1f
 
e42f508
 
52e4886
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
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
import requests
from gradio_client import Client

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)}"}
def get_text():
        input_text = st.text_input("You: ", "", key="input")
        return input_text

def query(payload):
	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


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

    user_input_translated = str(translate(user_input, "Moroccan Arabic", "English"))
    name = 'Mohammed'
    date = 'December'
    location = 'Fes, Morocco'
    soil_type = 'loam soil'
    humidity = '40%'
    weather = 'Sunny/Haze'
    temp = '10C'
    # 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_type}
humidity: {humidity}
weather: {weather}
temperature: {temp}
 Question: {user_input_translated}[/INST]</s>
    '''
    prompt = f'''
    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
Location: {location},
land type: {soil_type}
humidity: {humidity}
weather: {weather}
temperature: {temp}
    '''
#     output = query({"inputs": f'''
# PROMPT: {prompt}
# QUESTION: {user_input}
# ANSWER: 
# ''',})

    output = query({"inputs": instruction, "parameters":{"max_new_tokens":250, "temperature":1, "return_full_text":False}})
    # 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 [Med Machrouh](https://hf.co/medmac01)')

    # 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()

    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()

    # 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)
            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")

if __name__ == "__main__":
    main()