Emmanuel Frimpong Asante commited on
Commit
bd07a7b
·
1 Parent(s): 119d04f

update space

Browse files
Files changed (2) hide show
  1. app.py +35 -71
  2. utils.py +4 -1
app.py CHANGED
@@ -11,11 +11,16 @@ from werkzeug.security import generate_password_hash, check_password_hash
11
  from utils import PoultryFarmBot, llama3_response
12
  from chatbot_interface import build_chatbot_interface # Importing chatbot interface function
13
  from transformers import AutoModelForCausalLM, AutoTokenizer
 
14
 
15
  # Setup logging for better monitoring
16
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
17
  logger = logging.getLogger(__name__)
18
 
 
 
 
 
19
  # MongoDB Setup for logging and audit
20
  MONGO_URI = os.environ.get("MONGO_URI")
21
  if not MONGO_URI:
@@ -106,77 +111,36 @@ def authenticate_user(username, password):
106
  else:
107
  return False, None
108
 
109
- # Gradio authentication interface
110
- def build_auth_interface():
111
- """
112
- Build the authentication interface for the chatbot.
113
-
114
- Returns:
115
- gr.Blocks: Gradio Blocks object representing the authentication interface.
116
- """
117
- try:
118
- logger.info("Building Gradio authentication interface.")
119
- with gr.Blocks(theme=gr.themes.Base()) as auth_interface:
120
- gr.Markdown("# 🐔 Poultry Management Chatbot - Authentication")
121
- gr.Markdown("Please enter your credentials to access the poultry management chatbot.")
122
-
123
- username = gr.Textbox(
124
- label="Username",
125
- placeholder="Enter your username",
126
- lines=1,
127
- elem_id="username-input",
128
- )
129
- password = gr.Textbox(
130
- label="Password",
131
- placeholder="Enter your password",
132
- type="password",
133
- lines=1,
134
- elem_id="password-input",
135
- )
136
- auth_button = gr.Button(
137
- "Login",
138
- variant="primary",
139
- elem_id="login-button"
140
- )
141
- output_box = gr.Textbox(
142
- label="Authentication Status",
143
- placeholder="Status will appear here...",
144
- interactive=False,
145
- lines=3,
146
- elem_id="auth-output",
147
- )
148
-
149
- # Function to authenticate user and navigate to chatbot if successful
150
- def handle_login(username, password):
151
- success, user = authenticate_user(username, password)
152
- if success:
153
- logger.info("Authentication successful. Redirecting to chatbot.")
154
- return "Authentication successful. Redirecting to chatbot...", user
155
- else:
156
- logger.warning("Authentication failed. Incorrect username or password.")
157
- return "Authentication failed. Please check your username and password.", None
158
-
159
- auth_button.click(fn=handle_login, inputs=[username, password], outputs=[output_box])
160
- logger.info("Authentication interface built successfully.")
161
- return auth_interface
162
- except Exception as e:
163
- logger.error(f"Error building authentication interface: {e}")
164
- raise RuntimeError("Could not build the authentication interface. Please check the configuration.")
165
-
166
- # Launch the Gradio interface
167
  if __name__ == "__main__":
168
  try:
169
- logger.info("Launching Gradio authentication interface.")
170
- auth_interface = build_auth_interface()
171
-
172
- def launch_chatbot(auth_output, user):
173
- if "successful" in auth_output.lower() and user is not None:
174
- logger.info("Launching Gradio chatbot interface.")
175
- chatbot_interface = build_chatbot_interface(user)
176
- chatbot_interface.queue().launch(debug=True, share=True)
177
-
178
- # Launch the authentication interface with callback to chatbot on success
179
- auth_interface.queue().launch(debug=True, share=True, success=launch_chatbot)
180
  except Exception as e:
181
- logger.error(f"Failed to launch Gradio interface: {e}")
182
- raise RuntimeError("Could not launch the Gradio interface. Please check the application setup.")
 
11
  from utils import PoultryFarmBot, llama3_response
12
  from chatbot_interface import build_chatbot_interface # Importing chatbot interface function
13
  from transformers import AutoModelForCausalLM, AutoTokenizer
14
+ from flask import Flask, render_template, request, redirect, url_for, session
15
 
16
  # Setup logging for better monitoring
17
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
18
  logger = logging.getLogger(__name__)
19
 
20
+ # Flask app setup
21
+ app = Flask(__name__)
22
+ app.secret_key = os.environ.get("SECRET_KEY", "default_secret_key")
23
+
24
  # MongoDB Setup for logging and audit
25
  MONGO_URI = os.environ.get("MONGO_URI")
26
  if not MONGO_URI:
 
111
  else:
112
  return False, None
113
 
114
+ # Flask routes for AdminLTE authentication
115
+ @app.route('/', methods=['GET', 'POST'])
116
+ def login():
117
+ if request.method == 'POST':
118
+ username = request.form['username']
119
+ password = request.form['password']
120
+ success, user = authenticate_user(username, password)
121
+ if success:
122
+ logger.info("Authentication successful for user: %s", username)
123
+ session['username'] = username
124
+ return redirect(url_for('chatbot'))
125
+ else:
126
+ logger.warning("Authentication failed for user: %s", username)
127
+ return render_template('login.html', error="Invalid username or password.")
128
+ return render_template('login.html')
129
+
130
+ @app.route('/chatbot')
131
+ def chatbot():
132
+ if 'username' not in session:
133
+ return redirect(url_for('login'))
134
+ username = session['username']
135
+ logger.info("Launching Gradio chatbot interface for user: %s", username)
136
+ chatbot_interface = build_chatbot_interface({'username': username})
137
+ return chatbot_interface.launch(inline=True, share=True)
138
+
139
+ # Launch the Flask application
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  if __name__ == "__main__":
141
  try:
142
+ logger.info("Launching Flask server for AdminLTE authentication.")
143
+ app.run(host='0.0.0.0', port=5000, debug=True)
 
 
 
 
 
 
 
 
 
144
  except Exception as e:
145
+ logger.error(f"Failed to launch Flask server: {e}")
146
+ raise RuntimeError("Could not launch the Flask server. Please check the application setup.")
utils.py CHANGED
@@ -72,7 +72,7 @@ def llama3_response(user_input, tokenizer, model):
72
  logger.error(f"Error generating response: {str(e)}")
73
  return f"Error generating response: {str(e)}"
74
 
75
- def chatbot_response(image, text, username, password):
76
  """
77
  Handle user input and generate appropriate responses.
78
 
@@ -81,6 +81,9 @@ def chatbot_response(image, text, username, password):
81
  text (str): Text input for general queries.
82
  username (str): Username for authentication.
83
  password (str): Password for authentication.
 
 
 
84
 
85
  Returns:
86
  str: Response generated by the chatbot.
 
72
  logger.error(f"Error generating response: {str(e)}")
73
  return f"Error generating response: {str(e)}"
74
 
75
+ def chatbot_response(image, text, username, password, bot, tokenizer, model):
76
  """
77
  Handle user input and generate appropriate responses.
78
 
 
81
  text (str): Text input for general queries.
82
  username (str): Username for authentication.
83
  password (str): Password for authentication.
84
+ bot (PoultryFarmBot): Instance of PoultryFarmBot for handling disease detection.
85
+ tokenizer (AutoTokenizer): Tokenizer for generating responses.
86
+ model (AutoModelForCausalLM): Pre-trained language model for generating responses.
87
 
88
  Returns:
89
  str: Response generated by the chatbot.