routes.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import pandas as pd
  2. import mysql.connector
  3. import os
  4. from flask_cors import CORS
  5. from flask import (
  6. Blueprint, request, jsonify
  7. )
  8. conn = None
  9. bp = Blueprint('routes', __name__,)
  10. @bp.route('/chat/request', methods=('GET', 'POST'))
  11. def handle_request():
  12. user_input = request.args.get('question')
  13. top_matches = find_closest_match(user_input)
  14. recommendations = []
  15. for similarity, name, ruleId in top_matches:
  16. finalValue = f"https://communityrule.info/create/?r={ruleId}"
  17. recommendations.append({
  18. 'community': name,
  19. 'link': finalValue,
  20. })
  21. return jsonify(recommendations)
  22. def get_db_connection():
  23. global conn
  24. if conn is None or not conn.is_connected():
  25. conn = mysql.connector.connect(
  26. host=os.getenv('CLOUDRON_MYSQL_HOST'),
  27. user=os.getenv('CLOUDRON_MYSQL_USERNAME'),
  28. port=os.getenv('CLOUDRON_MYSQL_PORT'),
  29. password=os.getenv('CLOUDRON_MYSQL_PASSWORD'),
  30. database=os.getenv('CLOUDRON_MYSQL_DATABASE')
  31. )
  32. print("Database connection was successful")
  33. return conn
  34. def find_closest_match(user_input):
  35. conn = get_db_connection()
  36. max_similarity_curr = -1
  37. closest_value = None
  38. rule_id = None
  39. user_tokens = user_input.split()
  40. results = []
  41. cursor = conn.cursor()
  42. cursor.execute("SELECT summary, modules, name, rule_id FROM rules")
  43. rows = cursor.fetchall()
  44. cursor.close()
  45. # Compare user input with each value in the compare columns
  46. for compare_value1, compare_value2, return_value, ruleId in rows:
  47. # Convert compare_value2 to string if it's a float
  48. if isinstance(compare_value1, float):
  49. compare_value1 = str(compare_value1)
  50. if isinstance(compare_value2, float):
  51. compare_value2 = str(compare_value2)
  52. # Split compare_value2 into tokens
  53. compare_tokens1 = compare_value1.split()
  54. compare_tokens2 = compare_value2.split()
  55. # Calculate similarity between user input and compare_value1 and compare_value2
  56. similarity1 = similarity_score(user_tokens, compare_tokens1)
  57. similarity2 = similarity_score(user_tokens, compare_tokens2)
  58. # Take the maximum similarity between similarity1 and similarity2
  59. max_similarity_curr = max(similarity1, similarity2)
  60. # Update closest value if current similarity is greater
  61. #if max_similarity_curr > max_similarity:
  62. #max_similarity = max_similarity_curr
  63. #closest_value = return_value
  64. #rule_id = ruleId
  65. results.append((max_similarity_curr, return_value, ruleId))
  66. # print(results)
  67. results.sort(reverse=True, key=lambda x: x[0])
  68. return results[:3]
  69. def similarity_score(set1, set2):
  70. # Calculate the intersection of the two sets
  71. intersection = len(set(set1).intersection(set(set2)))
  72. # Calculate the union of the two sets
  73. union = len(set(set1).union(set(set2)))
  74. # Calculate the Jaccard similarity coefficient
  75. if union == 0:
  76. return 0
  77. else:
  78. return intersection / union