Emmanuel Frimpong Asante
		
	commited on
		
		
					Commit 
							
							·
						
						ec08f1b
	
1
								Parent(s):
							
							6823ab1
								
update space
Browse files
    	
        app.py
    CHANGED
    
    | @@ -10,6 +10,8 @@ import numpy as np | |
| 10 | 
             
            from huggingface_hub import login
         | 
| 11 | 
             
            from pymongo import MongoClient
         | 
| 12 | 
             
            from transformers import AutoModelForCausalLM, AutoTokenizer
         | 
|  | |
|  | |
| 13 |  | 
| 14 | 
             
            # Load environment variables from .env file
         | 
| 15 | 
             
            dotenv.load_dotenv()
         | 
| @@ -32,6 +34,8 @@ MONGO_URI = os.getenv("MONGO_URI") | |
| 32 | 
             
            logger.info("Connecting to MongoDB.")
         | 
| 33 | 
             
            client = MongoClient(MONGO_URI)
         | 
| 34 | 
             
            db = client.poultry_farm  # Connect to the 'poultry_farm' database
         | 
|  | |
|  | |
| 35 |  | 
| 36 | 
             
            # GPU Setup for TensorFlow
         | 
| 37 | 
             
            logger.info("TensorFlow version: %s", tf.__version__)
         | 
| @@ -74,8 +78,6 @@ def load_model_with_device(model_path, device_name): | |
| 74 | 
             
            device_name = '/GPU:0' if len(tf.config.list_physical_devices('GPU')) > 0 else '/CPU:0'
         | 
| 75 | 
             
            logger.info("Loading disease detection model.")
         | 
| 76 | 
             
            my_model = load_model_with_device('models/Final_Chicken_disease_model.h5', device_name)
         | 
| 77 | 
            -
            logger.info("Loading authentication model.")
         | 
| 78 | 
            -
            auth_model = load_model_with_device('models/auth_model.h5', device_name)
         | 
| 79 |  | 
| 80 | 
             
            # Disease names and recommendations
         | 
| 81 | 
             
            name_disease = {0: 'Coccidiosis', 1: 'Healthy', 2: 'New Castle Disease', 3: 'Salmonella'}
         | 
| @@ -172,7 +174,7 @@ class PoultryFarmBot: | |
| 172 | 
             
                        f"Here is some information about {disease_name}: causes, symptoms, and treatment methods "
         | 
| 173 | 
             
                        "to effectively manage this condition on a poultry farm."
         | 
| 174 | 
             
                    )
         | 
| 175 | 
            -
                    response =  | 
| 176 | 
             
                    return response.replace(prompt, "").strip()
         | 
| 177 |  | 
| 178 | 
             
                def diagnose_disease(self, image):
         | 
| @@ -191,6 +193,65 @@ class PoultryFarmBot: | |
| 191 | 
             
                    logger.warning("No image provided for diagnosis.")
         | 
| 192 | 
             
                    return "Please provide an image of poultry fecal matter for disease detection.", None, None, None
         | 
| 193 |  | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 194 | 
             
            # Initialize the bot instance
         | 
| 195 | 
             
            logger.info("Initializing PoultryFarmBot instance.")
         | 
| 196 | 
             
            bot = PoultryFarmBot(db)
         | 
| @@ -207,8 +268,8 @@ if tokenizer.pad_token is None: | |
| 207 | 
             
                tokenizer.add_special_tokens({'pad_token': '[PAD]'})
         | 
| 208 | 
             
                model.resize_token_embeddings(len(tokenizer))
         | 
| 209 |  | 
| 210 | 
            -
            # Llama  | 
| 211 | 
            -
            def  | 
| 212 | 
             
                """
         | 
| 213 | 
             
                Generate a response using the Llama 2 model.
         | 
| 214 |  | 
| @@ -240,31 +301,43 @@ def llama2_response(user_input): | |
| 240 | 
             
                    return f"Error generating response: {str(e)}"
         | 
| 241 |  | 
| 242 | 
             
            # Main chatbot function
         | 
| 243 | 
            -
            def chatbot_response(image, text):
         | 
| 244 | 
             
                """
         | 
| 245 | 
             
                Handle user input and generate appropriate responses.
         | 
| 246 |  | 
| 247 | 
             
                Args:
         | 
| 248 | 
             
                    image (numpy.ndarray): Image input for disease detection.
         | 
| 249 | 
             
                    text (str): Text input for general queries.
         | 
|  | |
|  | |
| 250 |  | 
| 251 | 
             
                Returns:
         | 
| 252 | 
             
                    str: Response generated by the chatbot.
         | 
| 253 | 
             
                """
         | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 254 | 
             
                # If an image is provided, diagnose the disease
         | 
| 255 | 
             
                if image is not None:
         | 
| 256 | 
             
                    logger.info("Image input detected. Proceeding with disease diagnosis.")
         | 
| 257 | 
             
                    diagnosis, name, status, recom = bot.diagnose_disease(image)
         | 
| 258 | 
             
                    if name and status and recom:
         | 
| 259 | 
             
                        logger.info("Diagnosis complete.")
         | 
|  | |
| 260 | 
             
                        return diagnosis
         | 
| 261 | 
             
                    else:
         | 
| 262 | 
             
                        logger.warning("Diagnosis incomplete.")
         | 
|  | |
| 263 | 
             
                        return diagnosis
         | 
| 264 | 
             
                else:
         | 
| 265 | 
             
                    # Generate a response using Llama 2 for general text input
         | 
| 266 | 
             
                    logger.info("Text input detected. Generating response.")
         | 
| 267 | 
            -
                     | 
|  | |
|  | |
| 268 |  | 
| 269 | 
             
            # Gradio interface
         | 
| 270 | 
             
            def build_gradio_interface():
         | 
| @@ -294,6 +367,19 @@ def build_gradio_interface(): | |
| 294 | 
             
                                lines=3,
         | 
| 295 | 
             
                                elem_id="user-input",
         | 
| 296 | 
             
                            )
         | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 297 |  | 
| 298 | 
             
                    output_box = gr.Textbox(
         | 
| 299 | 
             
                        label="Response",
         | 
| @@ -311,7 +397,7 @@ def build_gradio_interface(): | |
| 311 | 
             
                    # Connect the submit button to the chatbot response function
         | 
| 312 | 
             
                    submit_button.click(
         | 
| 313 | 
             
                        fn=chatbot_response,
         | 
| 314 | 
            -
                        inputs=[fecal_image, user_input],
         | 
| 315 | 
             
                        outputs=[output_box]
         | 
| 316 | 
             
                    )
         | 
| 317 | 
             
                logger.info("Gradio interface built successfully.")
         | 
|  | |
| 10 | 
             
            from huggingface_hub import login
         | 
| 11 | 
             
            from pymongo import MongoClient
         | 
| 12 | 
             
            from transformers import AutoModelForCausalLM, AutoTokenizer
         | 
| 13 | 
            +
            from datetime import datetime
         | 
| 14 | 
            +
            from werkzeug.security import generate_password_hash, check_password_hash
         | 
| 15 |  | 
| 16 | 
             
            # Load environment variables from .env file
         | 
| 17 | 
             
            dotenv.load_dotenv()
         | 
|  | |
| 34 | 
             
            logger.info("Connecting to MongoDB.")
         | 
| 35 | 
             
            client = MongoClient(MONGO_URI)
         | 
| 36 | 
             
            db = client.poultry_farm  # Connect to the 'poultry_farm' database
         | 
| 37 | 
            +
            enquiries_collection = db.enquiries  # Collection to store farmer enquiries
         | 
| 38 | 
            +
            users_collection = db.users  # Collection to store user credentials
         | 
| 39 |  | 
| 40 | 
             
            # GPU Setup for TensorFlow
         | 
| 41 | 
             
            logger.info("TensorFlow version: %s", tf.__version__)
         | 
|  | |
| 78 | 
             
            device_name = '/GPU:0' if len(tf.config.list_physical_devices('GPU')) > 0 else '/CPU:0'
         | 
| 79 | 
             
            logger.info("Loading disease detection model.")
         | 
| 80 | 
             
            my_model = load_model_with_device('models/Final_Chicken_disease_model.h5', device_name)
         | 
|  | |
|  | |
| 81 |  | 
| 82 | 
             
            # Disease names and recommendations
         | 
| 83 | 
             
            name_disease = {0: 'Coccidiosis', 1: 'Healthy', 2: 'New Castle Disease', 3: 'Salmonella'}
         | 
|  | |
| 174 | 
             
                        f"Here is some information about {disease_name}: causes, symptoms, and treatment methods "
         | 
| 175 | 
             
                        "to effectively manage this condition on a poultry farm."
         | 
| 176 | 
             
                    )
         | 
| 177 | 
            +
                    response = llama3_response(prompt)
         | 
| 178 | 
             
                    return response.replace(prompt, "").strip()
         | 
| 179 |  | 
| 180 | 
             
                def diagnose_disease(self, image):
         | 
|  | |
| 193 | 
             
                    logger.warning("No image provided for diagnosis.")
         | 
| 194 | 
             
                    return "Please provide an image of poultry fecal matter for disease detection.", None, None, None
         | 
| 195 |  | 
| 196 | 
            +
                def log_enquiry(self, enquiry_type, content, response, user_id):
         | 
| 197 | 
            +
                    """
         | 
| 198 | 
            +
                    Log a farmer's enquiry in the database.
         | 
| 199 | 
            +
             | 
| 200 | 
            +
                    Args:
         | 
| 201 | 
            +
                        enquiry_type (str): Type of the enquiry ('image' or 'text').
         | 
| 202 | 
            +
                        content (str): The content of the enquiry.
         | 
| 203 | 
            +
                        response (str): The response given by the system.
         | 
| 204 | 
            +
                        user_id (str): The ID of the user making the enquiry.
         | 
| 205 | 
            +
                    """
         | 
| 206 | 
            +
                    enquiry = {
         | 
| 207 | 
            +
                        "user_id": user_id,
         | 
| 208 | 
            +
                        "enquiry_type": enquiry_type,
         | 
| 209 | 
            +
                        "content": content,
         | 
| 210 | 
            +
                        "response": response,
         | 
| 211 | 
            +
                        "timestamp": datetime.utcnow()
         | 
| 212 | 
            +
                    }
         | 
| 213 | 
            +
                    logger.info(f"Logging enquiry: {enquiry}")
         | 
| 214 | 
            +
                    enquiries_collection.insert_one(enquiry)
         | 
| 215 | 
            +
             | 
| 216 | 
            +
                def authenticate_user(self, username, password):
         | 
| 217 | 
            +
                    """
         | 
| 218 | 
            +
                    Authenticate a user with username and password.
         | 
| 219 | 
            +
             | 
| 220 | 
            +
                    Args:
         | 
| 221 | 
            +
                        username (str): Username of the user.
         | 
| 222 | 
            +
                        password (str): Password of the user.
         | 
| 223 | 
            +
             | 
| 224 | 
            +
                    Returns:
         | 
| 225 | 
            +
                        dict: User information if authentication is successful, None otherwise.
         | 
| 226 | 
            +
                    """
         | 
| 227 | 
            +
                    logger.info(f"Authenticating user: {username}")
         | 
| 228 | 
            +
                    user = users_collection.find_one({"username": username})
         | 
| 229 | 
            +
                    if user and check_password_hash(user['password'], password):
         | 
| 230 | 
            +
                        logger.info("Authentication successful.")
         | 
| 231 | 
            +
                        return user
         | 
| 232 | 
            +
                    logger.warning("Authentication failed.")
         | 
| 233 | 
            +
                    return None
         | 
| 234 | 
            +
             | 
| 235 | 
            +
                def register_user(self, username, password):
         | 
| 236 | 
            +
                    """
         | 
| 237 | 
            +
                    Register a new user with username and password.
         | 
| 238 | 
            +
             | 
| 239 | 
            +
                    Args:
         | 
| 240 | 
            +
                        username (str): Username of the new user.
         | 
| 241 | 
            +
                        password (str): Password of the new user.
         | 
| 242 | 
            +
             | 
| 243 | 
            +
                    Returns:
         | 
| 244 | 
            +
                        bool: True if registration is successful, False otherwise.
         | 
| 245 | 
            +
                    """
         | 
| 246 | 
            +
                    logger.info(f"Registering user: {username}")
         | 
| 247 | 
            +
                    if users_collection.find_one({"username": username}):
         | 
| 248 | 
            +
                        logger.warning("Username already exists.")
         | 
| 249 | 
            +
                        return False
         | 
| 250 | 
            +
                    hashed_password = generate_password_hash(password)
         | 
| 251 | 
            +
                    users_collection.insert_one({"username": username, "password": hashed_password})
         | 
| 252 | 
            +
                    logger.info("User registration successful.")
         | 
| 253 | 
            +
                    return True
         | 
| 254 | 
            +
             | 
| 255 | 
             
            # Initialize the bot instance
         | 
| 256 | 
             
            logger.info("Initializing PoultryFarmBot instance.")
         | 
| 257 | 
             
            bot = PoultryFarmBot(db)
         | 
|  | |
| 268 | 
             
                tokenizer.add_special_tokens({'pad_token': '[PAD]'})
         | 
| 269 | 
             
                model.resize_token_embeddings(len(tokenizer))
         | 
| 270 |  | 
| 271 | 
            +
            # Llama 3 response generation
         | 
| 272 | 
            +
            def llama3_response(user_input):
         | 
| 273 | 
             
                """
         | 
| 274 | 
             
                Generate a response using the Llama 2 model.
         | 
| 275 |  | 
|  | |
| 301 | 
             
                    return f"Error generating response: {str(e)}"
         | 
| 302 |  | 
| 303 | 
             
            # Main chatbot function
         | 
| 304 | 
            +
            def chatbot_response(image, text, username, password):
         | 
| 305 | 
             
                """
         | 
| 306 | 
             
                Handle user input and generate appropriate responses.
         | 
| 307 |  | 
| 308 | 
             
                Args:
         | 
| 309 | 
             
                    image (numpy.ndarray): Image input for disease detection.
         | 
| 310 | 
             
                    text (str): Text input for general queries.
         | 
| 311 | 
            +
                    username (str): Username for authentication.
         | 
| 312 | 
            +
                    password (str): Password for authentication.
         | 
| 313 |  | 
| 314 | 
             
                Returns:
         | 
| 315 | 
             
                    str: Response generated by the chatbot.
         | 
| 316 | 
             
                """
         | 
| 317 | 
            +
                user = bot.authenticate_user(username, password)
         | 
| 318 | 
            +
                if not user:
         | 
| 319 | 
            +
                    return "Authentication failed. Please check your username and password."
         | 
| 320 | 
            +
             | 
| 321 | 
            +
                user_id = user['_id']
         | 
| 322 | 
            +
             | 
| 323 | 
             
                # If an image is provided, diagnose the disease
         | 
| 324 | 
             
                if image is not None:
         | 
| 325 | 
             
                    logger.info("Image input detected. Proceeding with disease diagnosis.")
         | 
| 326 | 
             
                    diagnosis, name, status, recom = bot.diagnose_disease(image)
         | 
| 327 | 
             
                    if name and status and recom:
         | 
| 328 | 
             
                        logger.info("Diagnosis complete.")
         | 
| 329 | 
            +
                        bot.log_enquiry("image", "Image Enquiry", diagnosis, user_id)
         | 
| 330 | 
             
                        return diagnosis
         | 
| 331 | 
             
                    else:
         | 
| 332 | 
             
                        logger.warning("Diagnosis incomplete.")
         | 
| 333 | 
            +
                        bot.log_enquiry("image", "Image Enquiry", diagnosis, user_id)
         | 
| 334 | 
             
                        return diagnosis
         | 
| 335 | 
             
                else:
         | 
| 336 | 
             
                    # Generate a response using Llama 2 for general text input
         | 
| 337 | 
             
                    logger.info("Text input detected. Generating response.")
         | 
| 338 | 
            +
                    response = llama3_response(text)
         | 
| 339 | 
            +
                    bot.log_enquiry("text", text, response, user_id)
         | 
| 340 | 
            +
                    return response
         | 
| 341 |  | 
| 342 | 
             
            # Gradio interface
         | 
| 343 | 
             
            def build_gradio_interface():
         | 
|  | |
| 367 | 
             
                                lines=3,
         | 
| 368 | 
             
                                elem_id="user-input",
         | 
| 369 | 
             
                            )
         | 
| 370 | 
            +
                            username = gr.Textbox(
         | 
| 371 | 
            +
                                label="Username",
         | 
| 372 | 
            +
                                placeholder="Enter your username",
         | 
| 373 | 
            +
                                lines=1,
         | 
| 374 | 
            +
                                elem_id="username-input",
         | 
| 375 | 
            +
                            )
         | 
| 376 | 
            +
                            password = gr.Textbox(
         | 
| 377 | 
            +
                                label="Password",
         | 
| 378 | 
            +
                                placeholder="Enter your password",
         | 
| 379 | 
            +
                                type="password",
         | 
| 380 | 
            +
                                lines=1,
         | 
| 381 | 
            +
                                elem_id="password-input",
         | 
| 382 | 
            +
                            )
         | 
| 383 |  | 
| 384 | 
             
                    output_box = gr.Textbox(
         | 
| 385 | 
             
                        label="Response",
         | 
|  | |
| 397 | 
             
                    # Connect the submit button to the chatbot response function
         | 
| 398 | 
             
                    submit_button.click(
         | 
| 399 | 
             
                        fn=chatbot_response,
         | 
| 400 | 
            +
                        inputs=[fecal_image, user_input, username, password],
         | 
| 401 | 
             
                        outputs=[output_box]
         | 
| 402 | 
             
                    )
         | 
| 403 | 
             
                logger.info("Gradio interface built successfully.")
         |