acecalisto3 commited on
Commit
ac588ec
1 Parent(s): 55f620f

Update app2.py

Browse files
Files changed (1) hide show
  1. app2.py +77 -81
app2.py CHANGED
@@ -16,13 +16,15 @@ from urllib.parse import urljoin
16
  import logging
17
  from sqlalchemy.orm import Session
18
  from sqlalchemy.future import select
 
 
19
 
20
  Base = declarative_base()
21
 
22
  class Article(Base):
23
  __tablename__ = 'articles'
24
  id = Column(Integer, primary_key=True)
25
- url = Column('url', String(2048), nullable=False, unique=True) # Increased URL length limit
26
  title = Column('title', String(255))
27
  content = Column('content', Text())
28
  hash_value = Column('hash', String(32))
@@ -43,6 +45,7 @@ monitoring_tasks = {}
43
  url_monitoring_intervals = {}
44
  change_counts = {}
45
  history = []
 
46
 
47
  async def create_db_engine(db_url):
48
  try:
@@ -212,15 +215,15 @@ async def chatbot_response(message: str, history: List[Tuple[str, str]]):
212
  return history, history
213
 
214
 
215
- async def update_db_status(db_status):
216
  while True:
217
  try:
218
  await db_session.execute("SELECT 1")
219
  db_status = "Connected"
220
  except SQLAlchemyError:
221
  db_status = "Disconnected"
 
222
  await asyncio.sleep(60) # Check every minute
223
- return db_status
224
 
225
 
226
  async def update_feed_content(): # Remove db_session parameter
@@ -243,11 +246,11 @@ async def update_feed_content(): # Remove db_session parameter
243
  logger.error(f"Database error: {e}")
244
  return None
245
 
246
- async def periodic_update_with_error_handling(db_session):
247
  while True:
248
  try:
249
  await asyncio.sleep(300) # Wait for 5 minutes
250
- await update_feed_content(db_session)
251
  except Exception as e:
252
  logger.error(f"Error in periodic update: {e}")
253
 
@@ -260,86 +263,79 @@ async def main():
260
 
261
  demo = gr.Blocks()
262
 
263
- with demo:
264
- gr.Markdown("# Website Monitor and Chatbot")
265
-
266
- with gr.Row():
267
- with gr.Column():
268
- db_url = gr.Textbox(
269
- label="Database URL", value="sqlite:///monitoring.db")
270
- db_status = gr.Textbox(label="Database Status",
271
- interactive=False,
272
- value="Connected")
273
-
274
- with gr.Column():
275
- with gr.Tab("Configuration"):
276
- target_urls = gr.Textbox(
277
- label="Target URLs (comma-separated)",
278
- placeholder=
279
- "https://example.com, https://another-site.com")
280
- storage_location = gr.Textbox(
281
- label="Storage Location (CSV file path)",
282
- placeholder="/path/to/your/file.csv")
283
- feed_rss_checkbox = gr.Checkbox(label="Enable RSS Feed")
284
- start_button = gr.Button("Start Monitoring")
285
- stop_button = gr.Button("Stop Monitoring")
286
- status_text = gr.Textbox(label="Status",
287
- interactive=False)
288
- history_text = gr.Textbox(label="History",
289
- lines=10,
290
- interactive=False)
291
-
292
- with gr.Tab("User-End View"):
293
- feed_content = gr.JSON(label="RSS Feed Content")
294
-
295
- with gr.Tab("Chatbot"):
296
- chatbot_interface = gr.Chatbot(type='messages')
297
- message_input = gr.Textbox(
298
- placeholder="Type your message here...")
299
- send_button = gr.Button("Send")
300
-
301
- async def on_start_click(target_urls_str: str, storage_loc: str,
302
- feed_enabled: bool):
303
- urls = [url.strip() for url in target_urls_str.split(",")]
304
- await start_monitoring(urls,
305
- storage_loc if storage_loc else None,
306
- feed_enabled)
307
- return "Monitoring started for valid URLs."
308
-
309
- async def on_stop_click():
310
- for url in list(monitoring_tasks.keys()):
311
- stop_monitoring(url)
312
- return "Monitoring stopped for all URLs."
313
-
314
- start_button.click(
315
- on_start_click,
316
- inputs=[target_urls, storage_location, feed_rss_checkbox],
317
- outputs=[status_text])
318
- stop_button.click(on_stop_click, outputs=[status_text])
319
- send_button.click(
320
- chatbot_response,
321
- inputs=[message_input, chatbot_interface],
322
- outputs=[chatbot_interface, message_input])
323
-
324
- # Set up the timer
325
- feed_updater = gr.Timer(interval=300)
326
- feed_updater.tick(fn=update_feed_content,
327
- outputs=feed_content)
328
-
329
- # Create background tasks
330
- update_tasks = [
331
- asyncio.create_task(periodic_update_with_error_handling(db_session)),
332
- asyncio.create_task(update_db_status(db_status))
333
- ]
334
 
335
  # Launch the demo
336
  await demo.launch()
337
 
338
- # Wait for background tasks to complete
339
- for task in update_tasks:
340
- task.cancel()
341
- await asyncio.gather(*update_tasks, return_exceptions=True)
342
-
343
  except Exception as e:
344
  logger.error(f"Error in main: {e}")
345
  finally:
 
16
  import logging
17
  from sqlalchemy.orm import Session
18
  from sqlalchemy.future import select
19
+ from bs4 import BeautifulSoup
20
+ import validators
21
 
22
  Base = declarative_base()
23
 
24
  class Article(Base):
25
  __tablename__ = 'articles'
26
  id = Column(Integer, primary_key=True)
27
+ url = Column('url', String(2048), nullable=False, unique=True)
28
  title = Column('title', String(255))
29
  content = Column('content', Text())
30
  hash_value = Column('hash', String(32))
 
45
  url_monitoring_intervals = {}
46
  change_counts = {}
47
  history = []
48
+ db_session = None # Initialize db_session globally
49
 
50
  async def create_db_engine(db_url):
51
  try:
 
215
  return history, history
216
 
217
 
218
+ async def update_db_status(db_status_textbox):
219
  while True:
220
  try:
221
  await db_session.execute("SELECT 1")
222
  db_status = "Connected"
223
  except SQLAlchemyError:
224
  db_status = "Disconnected"
225
+ yield db_status # Use a generator to update the textbox
226
  await asyncio.sleep(60) # Check every minute
 
227
 
228
 
229
  async def update_feed_content(): # Remove db_session parameter
 
246
  logger.error(f"Database error: {e}")
247
  return None
248
 
249
+ async def periodic_update_with_error_handling():
250
  while True:
251
  try:
252
  await asyncio.sleep(300) # Wait for 5 minutes
253
+ await update_feed_content()
254
  except Exception as e:
255
  logger.error(f"Error in periodic update: {e}")
256
 
 
263
 
264
  demo = gr.Blocks()
265
 
266
+ with demo:
267
+ gr.Markdown("# Website Monitor and Chatbot")
268
+
269
+ with gr.Row():
270
+ with gr.Column():
271
+ db_url = gr.Textbox(
272
+ label="Database URL", value="sqlite:///monitoring.db")
273
+ db_status_textbox = gr.Textbox(label="Database Status",
274
+ interactive=False,
275
+ value="Connected")
276
+
277
+ with gr.Column():
278
+ with gr.Tab("Configuration"):
279
+ target_urls = gr.Textbox(
280
+ label="Target URLs (comma-separated)",
281
+ placeholder=
282
+ "https://example.com, https://another-site.com")
283
+ storage_location = gr.Textbox(
284
+ label="Storage Location (CSV file path)",
285
+ placeholder="/path/to/your/file.csv")
286
+ feed_rss_checkbox = gr.Checkbox(label="Enable RSS Feed")
287
+ start_button = gr.Button("Start Monitoring")
288
+ stop_button = gr.Button("Stop Monitoring")
289
+ status_text = gr.Textbox(label="Status",
290
+ interactive=False)
291
+ history_text = gr.Textbox(label="History",
292
+ lines=10,
293
+ interactive=False)
294
+
295
+ with gr.Tab("User-End View"):
296
+ feed_content = gr.JSON(label="RSS Feed Content")
297
+
298
+ with gr.Tab("Chatbot"):
299
+ chatbot_interface = gr.Chatbot(type='messages')
300
+ message_input = gr.Textbox(
301
+ placeholder="Type your message here...")
302
+ send_button = gr.Button("Send")
303
+
304
+ async def on_start_click(target_urls_str: str, storage_loc: str,
305
+ feed_enabled: bool):
306
+ urls = [url.strip() for url in target_urls_str.split(",")]
307
+ await start_monitoring(urls,
308
+ storage_loc if storage_loc else None,
309
+ feed_enabled)
310
+ return "Monitoring started for valid URLs."
311
+
312
+ async def on_stop_click():
313
+ for url in list(monitoring_tasks.keys()):
314
+ stop_monitoring(url)
315
+ return "Monitoring stopped for all URLs."
316
+
317
+ start_button.click(
318
+ on_start_click,
319
+ inputs=[target_urls, storage_location, feed_rss_checkbox],
320
+ outputs=[status_text])
321
+ stop_button.click(on_stop_click, outputs=[status_text])
322
+ send_button.click(
323
+ chatbot_response,
324
+ inputs=[message_input, chatbot_interface],
325
+ outputs=[chatbot_interface, message_input])
326
+
327
+ # Set up the timer
328
+ feed_updater = gr.Timer(interval=300)
329
+ feed_updater.tick(fn=update_feed_content,
330
+ outputs=feed_content)
331
+
332
+ # Create background tasks
333
+ demo.load(update_db_status, outputs=db_status_textbox)
334
+ asyncio.create_task(periodic_update_with_error_handling())
 
 
335
 
336
  # Launch the demo
337
  await demo.launch()
338
 
 
 
 
 
 
339
  except Exception as e:
340
  logger.error(f"Error in main: {e}")
341
  finally: