diff --git a/Server/ReasnAPI/ReasnAPI/Services/RecomendationService.cs b/Server/ReasnAPI/ReasnAPI/Services/RecomendationService.cs index 1634ba17..d982c513 100644 --- a/Server/ReasnAPI/ReasnAPI/Services/RecomendationService.cs +++ b/Server/ReasnAPI/ReasnAPI/Services/RecomendationService.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using ReasnAPI.Mappers; using ReasnAPI.Models.Recomendation; +using Npgsql; namespace ReasnAPI.Services { @@ -17,12 +18,13 @@ public class RecomendationService private readonly HttpClient httpClient; private readonly ReasnContext context; private readonly string flaskApiUrl; + private readonly string _connectionString; public RecomendationService(HttpClient httpClient, ReasnContext context, IConfiguration configuration) { this.httpClient = httpClient; this.context = context; - this.flaskApiUrl = $"{configuration.GetValue("FlaskApi:BaseUrl")}/similar-tags"; + _connectionString = configuration.GetConnectionString("DefaultValue"); } public async Task> GetEventsByInterest(List interestsDto) @@ -32,28 +34,20 @@ public async Task> GetEventsByInterest(List inte try { - var response = await httpClient.PostAsJsonAsync(flaskApiUrl, interests); + var similarTags = await GetSimilarTagsFromDb(interests); - if (!response.IsSuccessStatusCode) - { - throw new HttpRequestException( - $"Error fetching tags from Flask API. Status code: {response.StatusCode}"); - } - - var tagInfoList = await response.Content.ReadFromJsonAsync>(); - - if (tagInfoList == null || tagInfoList.Count == 0) + if (similarTags == null || similarTags.Count == 0) { return new List(); } - var tagNames = tagInfoList.Select(t => t.Tag_Name).ToList(); - var interestNames = tagInfoList.Select(t => t.Interest_Name).ToList(); - var values = tagInfoList.Select(t => t.Value).ToList(); + var tagNames = similarTags.Select(t => t.Tag_Name).ToList(); + var interestNames = similarTags.Select(t => t.Interest_Name).ToList(); + var values = similarTags.Select(t => t.Value).ToList(); for (int i = 0; i < values.Count; i++) { - values[i] *= interestsLevels[interestNames.IndexOf(tagInfoList[i].Interest_Name)]; + values[i] *= interestsLevels[interestNames.IndexOf(similarTags[i].Interest_Name)]; } var events = await context.Events @@ -67,8 +61,8 @@ public async Task> GetEventsByInterest(List inte .Sum(t => values[tagNames.IndexOf(t.Name)]) }) .OrderByDescending(e => e.TotalTagValue) - .Select(e => e.Event) - .ToListAsync(); ; + .Select(e => e.Event) + .ToListAsync(); var eventDtos = events.Select(e => e.ToDto()).ToList(); @@ -80,5 +74,43 @@ public async Task> GetEventsByInterest(List inte throw; } } + + public async Task> GetSimilarTagsFromDb(List interests) + { + var similarTags = new List(); + + await using var conn = new NpgsqlConnection(_connectionString); + await conn.OpenAsync(); + + await using var cmd = new NpgsqlCommand(); + cmd.Connection = conn; + + + var query = @" + SELECT DISTINCT tag_name, interest_name, value + FROM common.related + WHERE interest_name = any(@interests) AND value > 0.3 + "; + + cmd.CommandText = query; + cmd.Parameters.AddWithValue("interests", interests.ToArray()); + + await using var reader = await cmd.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + var tag_name = reader.GetString(reader.GetOrdinal("tag_name")); + var interest_name = reader.GetString(reader.GetOrdinal("interest_name")); + var value = reader.GetDecimal(reader.GetOrdinal("value")); + + similarTags.Add(new TagInfo + { + Tag_Name = tag_name, + Interest_Name = interest_name, + Value = (double)value + }); + } + + return similarTags; + } } } diff --git a/recomendation.py b/recomendation.py deleted file mode 100644 index 6577f83c..00000000 --- a/recomendation.py +++ /dev/null @@ -1,57 +0,0 @@ -from flask import Flask, request, jsonify -import psycopg2 -import psycopg2.extras - -app = Flask(__name__) - -def connect_to_db(): - conn = psycopg2.connect( - dbname="reasn", - user="dba", - password="sql", - host="localhost", - port="5432" - ) - return conn - -def get_similar_tags_from_db(conn, interests): - with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur: - query = """ - SELECT DISTINCT tag_name, interest_name, value - FROM common.related - WHERE interest_name IN %s AND value > 0.3 - """ - cur.execute(query, (tuple(interests),)) - results = cur.fetchall() - - # Printowanie wyników - for row in results: - print(f"tag_name: {row['tag_name']}, interest_name: {row['interest_name']}, value: {row['value']}") - - return [{'tag_name': row['tag_name'], 'interest_name': row['interest_name'], 'value': row['value']} for row in results] - - -@app.route('/similar-tags', methods=['POST']) -def get_similar_tags(): - data = request.get_json() - - if isinstance(data, list): - interests = data # Treat data as a list of interests directly - elif isinstance(data, dict): - interests = data.get('interests', []) - else: - return jsonify({'error': 'Invalid JSON data format'}), 400 - - if not interests: - return jsonify({'error': 'No interests provided'}), 400 - - conn = connect_to_db() - try: - similar_tags = get_similar_tags_from_db(conn, interests) - - return jsonify(similar_tags) - finally: - conn.close() - -if __name__ == '__main__': - app.run(host='0.0.0.0', port=5000, debug=True)