File size: 5,160 Bytes
743528d
 
 
 
 
 
 
 
 
 
 
 
18b0da7
5c1ce5a
18b0da7
 
6a742f6
 
 
 
 
 
18b0da7
40e5ddb
6a742f6
 
18b0da7
6a742f6
18b0da7
743528d
 
 
6a742f6
743528d
 
 
18b0da7
6a742f6
18b0da7
6a742f6
743528d
 
6a742f6
743528d
 
 
 
18b0da7
 
 
743528d
 
 
 
18b0da7
5c1ce5a
743528d
6a742f6
18b0da7
6a742f6
743528d
6a742f6
 
 
 
743528d
 
 
 
5c1ce5a
 
6a742f6
 
5c1ce5a
743528d
 
 
40e5ddb
 
6a742f6
 
40e5ddb
5c1ce5a
 
 
6a742f6
 
18b0da7
 
 
 
743528d
6a742f6
743528d
 
 
 
 
6a742f6
 
743528d
ec8c7fc
6a742f6
18b0da7
 
 
6a742f6
18b0da7
6a742f6
18b0da7
6a742f6
18b0da7
 
6a742f6
18b0da7
 
 
 
 
 
6a742f6
 
18b0da7
 
 
6a742f6
 
18b0da7
6a742f6
18b0da7
 
 
743528d
 
18b0da7
 
 
6a742f6
5c1ce5a
705f1aa
 
 
18b0da7
6a742f6
743528d
6a742f6
bd99431
40e5ddb
5c1ce5a
6a742f6
705f1aa
1c0b4dd
18b0da7
6a742f6
18b0da7
 
 
6a742f6
 
 
 
 
 
18b0da7
 
705f1aa
18b0da7
 
 
 
 
705f1aa
18b0da7
743528d
18b0da7
 
 
 
5c1ce5a
18b0da7
 
 
6a742f6
18b0da7
 
743528d
5c1ce5a
 
6a742f6
 
5c1ce5a
 
 
 
6a742f6
 
18b0da7
 
 
 
6a742f6
 
5c1ce5a
743528d
 
 
18b0da7
 
 
 
 
 
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
import os
import gradio as gr
from dotenv import load_dotenv
from PIL import Image
import base64
import io
import hashlib
import traceback
from openai import AzureOpenAI

load_dotenv()

# ===============================
# AZURE CONFIG
# ===============================
client = AzureOpenAI(
    api_key=os.getenv("AZURE_OPENAI_API_KEY"),
    api_version=os.getenv(
        "AZURE_OPENAI_API_VERSION",
        "2024-02-15-preview"
    ),
    azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT")
)

AZURE_DEPLOYMENT = os.getenv("AZURE_OPENAI_DEPLOYMENT")

# ===============================
# IMAGE CACHE ONLY
# ===============================
crop_cache = {}


def get_hash(image_bytes):
    return hashlib.md5(image_bytes).hexdigest()


# ===============================
# IDENTIFY CROP
# ===============================
def identify_crop(image_file, crop_state):

    if image_file is None:
        return "❌ Please upload a crop image.", crop_state

    try:
        img = Image.open(image_file)

        if img.width > 1000 or img.height > 1000:
            img.thumbnail((1000, 1000))

        if img.mode != "RGB":
            img = img.convert("RGB")

        buffer = io.BytesIO()
        img.save(buffer, format="JPEG", quality=85)

        image_bytes = buffer.getvalue()
        image_hash = get_hash(image_bytes)

        # βœ… cache
        if image_hash in crop_cache:
            result = crop_cache[image_hash]
            return f"🌾 Cached Crop Result:\n\n{result}", result

        image_base64 = base64.b64encode(image_bytes).decode()

        response = client.chat.completions.create(
            model=AZURE_DEPLOYMENT,
            messages=[
                {
                    "role": "system",
                    "content":
                    "You are an expert agricultural scientist."
                },
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text":
                            "Identify this crop briefly."
                        },
                        {
                            "type": "image_url",
                            "image_url": {
                                "url":
                                f"data:image/jpeg;base64,{image_base64}"
                            },
                        },
                    ],
                },
            ],
            max_tokens=300,
        )

        result = response.choices[0].message.content
        crop_cache[image_hash] = result

        # βœ… SAVE ONLY IN SESSION
        return f"🌾 Crop Identification:\n\n{result}", result

    except Exception:
        return traceback.format_exc(), crop_state


# ===============================
# CHATBOT
# ===============================
def ask_chatbot(message, crop_state):

    if not crop_state:
        return "⚠️ Please upload and identify a crop image first."

    context = f"\nCrop Info:\n{crop_state}\n"

    response = client.chat.completions.create(
        model=AZURE_DEPLOYMENT,
        messages=[
            {
                "role": "system",
                "content":
                "You are a farming advisor. Give direct practical answers."
            },
            {
                "role": "user",
                "content": context + message
            }
        ],
        max_tokens=400,
    )

    return response.choices[0].message.content


# ===============================
# CHAT UI
# ===============================
def chat_ui(message, history, crop_state):

    if history is None:
        history = []

    if not message:
        return history, "", crop_state

    reply = ask_chatbot(message, crop_state)

    history.append([message, reply])

    return history, "", crop_state


# ===============================
# UI
# ===============================
with gr.Blocks(title="Crop Prediction") as demo:

    gr.Markdown(
        "# 🌾 Smart Crop Identification & Farming Assistant"
    )

    # βœ… SESSION MEMORY
    crop_state = gr.State(None)

    with gr.Row():

        with gr.Column():
            image_input = gr.Image(
                type="filepath",
                label="Upload Crop Image"
            )

            identify_btn = gr.Button("πŸ” Identify Crop")

            image_output = gr.Textbox(
                lines=10,
                label="Result"
            )

        with gr.Column():
            chatbot = gr.Chatbot(height=400)
            msg = gr.Textbox(
                placeholder="Ask about soil, disease..."
            )
            send = gr.Button("Send")

    identify_btn.click(
        identify_crop,
        [image_input, crop_state],
        [image_output, crop_state]
    )

    send.click(
        chat_ui,
        [msg, chatbot, crop_state],
        [chatbot, msg, crop_state]
    )

    msg.submit(
        chat_ui,
        [msg, chatbot, crop_state],
        [chatbot, msg, crop_state]
    )


if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        pwa=True,
        favicon_path="favicon.ico"
    )