POS_Sprint_6 #8

Merged
s426229 merged 11 commits from POS_Sprint_6 into develop 2021-01-27 18:31:09 +01:00
9 changed files with 204 additions and 24 deletions
Showing only changes of commit 8b51fa1310 - Show all commits

View File

@ -18,6 +18,7 @@ using Klient.Droid.Modules;
using Android.Provider; using Android.Provider;
using Android.Content; using Android.Content;
using Android.Graphics; using Android.Graphics;
using Newtonsoft.Json.Linq;
using Com.Xamarin.Formsviewgroup; using Com.Xamarin.Formsviewgroup;
using Android.Icu.Text; using Android.Icu.Text;
@ -341,22 +342,20 @@ namespace Klient.Droid
if(response.StatusCode == HttpStatusCode.OK) if(response.StatusCode == HttpStatusCode.OK)
{ {
var jsonString = await response.Content.ReadAsStringAsync(); var jsonString = await response.Content.ReadAsStringAsync();
dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
FindViewById<TextView>(Resource.Id.ErrorPhoto).Text = "Przesłano zdjęcie!"; FindViewById<TextView>(Resource.Id.ErrorPhoto).Text = "Przesłano zdjęcie!";
SetContentView(Resource.Layout.ekranZLinkami); SetContentView(Resource.Layout.ekranZLinkami);
var second_response = await client.GetAsync("http://10.0.2.2:5001/api/Search", jsonObject.response); var second_response = await client.GetAsync($"http://10.0.2.2:5001/api/Search/{jsonString}");
if(second_response.StatusCode == HttpStatusCode.OK) if(second_response.StatusCode == HttpStatusCode.OK)
{ {
var second_jsonString = await response.Content.ReadAsStringAsync(); var second_jsonString = await second_response.Content.ReadAsStringAsync();
dynamic second_jsonObject = JsonConvert.DeserializeObject(second_jsonString);
List<SearchResult> fullLink = JsonConvert.DeserializeObject<List<SearchResult>>(second_jsonObject); List<SearchResult> fullLink = JsonConvert.DeserializeObject<List<SearchResult>>(second_jsonString);
int end = 10; int end = 10;
if (fullLink.Count < 10) end = fullLink.Count; if (fullLink.Count < 10) end = fullLink.Count;
for (int i = 0; i < end; i++) for (int i = 0; i < end; i++)
{ {
FindViewById<TextView>(Resource.Id.links).Text = FindViewById<TextView>(Resource.Id.links).Text + fullLink[i].Title + ": " + fullLink[i].Link + "\n\n"; FindViewById<TextView>(Resource.Id.links).Text = FindViewById<TextView>(Resource.Id.links).Text + fullLink[i].title + ": " + fullLink[i].link + "\n\n";
} }
} }
else else
@ -440,7 +439,8 @@ namespace Klient.Droid
{ {
var jsonString = await response.Content.ReadAsStringAsync(); var jsonString = await response.Content.ReadAsStringAsync();
dynamic jsonObject = JsonConvert.DeserializeObject(jsonString); dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
List<string> history = JsonConvert.DeserializeObject<List<string>>(jsonObject.history); var hs = (JArray)jsonObject.history;
List<string> history = hs.ToObject<List<string>>();
int end = 10; int end = 10;
int temp; int temp;
if (history.Count < 10) end = history.Count; if (history.Count < 10) end = history.Count;

View File

@ -13,8 +13,8 @@ namespace Klient.Droid.Modules
{ {
public class SearchResult public class SearchResult
{ {
public string Title { get; set; } public string title { get; set; }
public string Link { get; set; } public string link { get; set; }
public string Snippet { get; set; } public string snippet { get; set; }
} }
} }

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.DTO
{
public class UserHistoryDto
{
public List<string> History { get; set; }
public UserDto User { get; set; }
}
}

View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Framework
{
public class OCRResponseData
{
/// <summary>
/// Error message
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Available pages
/// </summary>
public int AvailablePages { get; set; }
/// <summary>
/// OCRed text
/// </summary>
public List<List<string>> OCRText { get; set; }
/// <summary>
/// Output file1 URL
/// </summary>
public string OutputFileUrl { get; set; }
/// <summary>
/// Output file2 URL
/// </summary>
public string OutputFileUrl2 { get; set; }
/// <summary>
/// Output file3 URL
/// </summary>
public string OutputFileUrl3 { get; set; }
/// <summary>
/// Reserved
/// </summary>
public List<List<string>> Reserved { get; set; }
/// <summary>
/// OCRWords
/// </summary>
public List<List<OCRWSWord>> OCRWords { get; set; }
/// <summary>
/// Task description
/// </summary>
public string TaskDescription { get; set; }
/// <summary>
/// Constructor
/// </summary>
public OCRResponseData()
{
OCRText = new List<List<string>>();
Reserved = new List<List<string>>();
OCRWords = new List<List<OCRWSWord>>();
}
}
public class OCRWSWord
{
public int Top;
public int Left;
public int Height;
public int Width;
public string OCRWord;
}
}

View File

@ -15,6 +15,7 @@ namespace Serwer.Infrastructure.Mappers
=> new MapperConfiguration(cfg => => new MapperConfiguration(cfg =>
{ {
cfg.CreateMap<User, UserDto>(); cfg.CreateMap<User, UserDto>();
cfg.CreateMap<UserHistory, UserHistoryDto>();
}) })
.CreateMapper(); .CreateMapper();
} }

View File

@ -1,5 +1,7 @@
using Serwer.Core.Domain; using AutoMapper;
using Serwer.Core.Domain;
using Serwer.Core.Repositories; using Serwer.Core.Repositories;
using Serwer.Infrastructure.DTO;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -12,13 +14,15 @@ namespace Serwer.Infrastructure.Services
{ {
private readonly IHistoryRepository _historyRepository; private readonly IHistoryRepository _historyRepository;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
public HistoryService(IHistoryRepository historyRepository, IUserRepository userRepository) private readonly IMapper _mapper;
public HistoryService(IHistoryRepository historyRepository, IUserRepository userRepository, IMapper mapper)
{ {
_historyRepository = historyRepository; _historyRepository = historyRepository;
_userRepository = userRepository; _userRepository = userRepository;
_mapper = mapper;
} }
public async Task<UserHistory> GetAsync(Guid userId) public async Task<UserHistoryDto> GetAsync(Guid userId)
{ {
var user = await _userRepository.GetAsync(userId); var user = await _userRepository.GetAsync(userId);
if(user == null) if(user == null)
@ -26,7 +30,7 @@ namespace Serwer.Infrastructure.Services
throw new Exception("Coś poszło nie tak."); throw new Exception("Coś poszło nie tak.");
} }
var history = await _historyRepository.GetAsync(user); var history = await _historyRepository.GetAsync(user);
return history; return _mapper.Map<UserHistoryDto>(history);
} }
} }
} }

View File

@ -1,4 +1,5 @@
using Serwer.Core.Domain; using Serwer.Core.Domain;
using Serwer.Infrastructure.DTO;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -9,6 +10,6 @@ namespace Serwer.Infrastructure.Services
{ {
public interface IHistoryService public interface IHistoryService
{ {
Task<UserHistory> GetAsync(Guid userId); Task<UserHistoryDto> GetAsync(Guid userId);
} }
} }

View File

@ -1,8 +1,11 @@
using Serwer.Core.Domain; using Newtonsoft.Json;
using Serwer.Core.Domain;
using Serwer.Infrastructure.Framework;
using Serwer.Infrastructure.Settings; using Serwer.Infrastructure.Settings;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Tesseract; using Tesseract;
@ -19,12 +22,64 @@ namespace Serwer.Infrastructure.Services
} }
public async Task<string> Process(string name, string contentType, byte[] bytes) public async Task<string> Process(string name, string contentType, byte[] bytes)
{ {
string license_code = "FC935C59-F248-48A3-9970-8A6BDB66FA86";
string user_name = "poszukiwacz";
string ocrURL = @"http://www.ocrwebservice.com/restservices/processDocument?gettext=true&outputformat=txt&language=polish";
byte[] uploadData = bytes;
HttpWebRequest request = CreateHttpRequest(ocrURL, user_name, license_code, "POST");
request.ContentLength = uploadData.Length;
// Send request
using (System.IO.Stream post = request.GetRequestStream())
{
post.Write(uploadData, 0, (int)uploadData.Length);
}
try
{
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Parse JSON response
string strJSON = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
OCRResponseData ocrResponse = JsonConvert.DeserializeObject<OCRResponseData>(strJSON);
return await Task.FromResult(ocrResponse.OCRText.First().First());
}
}
catch (WebException wex)
{
var x = string.Format("OCR API Error. HTTPCode:{0}", ((HttpWebResponse)wex.Response).StatusCode);
throw wex;
}
/*
var engine = new TesseractEngine(System.IO.Path.Combine(_env, "tessdata"),"eng+equ", EngineMode.Default); var engine = new TesseractEngine(System.IO.Path.Combine(_env, "tessdata"),"eng+equ", EngineMode.Default);
var img = Pix.LoadFromMemory(bytes); var img = Pix.LoadFromMemory(bytes);
var res = engine.Process(img); var res = engine.Process(img);
var txt = res.GetText(); var txt = res.GetText();
return await Task.FromResult(txt); return await Task.FromResult(txt);
*/
}
private static HttpWebRequest CreateHttpRequest(string address_url, string user_name, string license_code, string http_method)
{
Uri address = new Uri(address_url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
byte[] authBytes = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", user_name, license_code).ToCharArray());
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);
request.Method = http_method;
request.Timeout = 600000;
// Specify Response format to JSON or XML (application/json or application/xml)
request.ContentType = "application/json";
return request;
} }
} }
} }

View File

@ -35,6 +35,30 @@ namespace Serwer.Infrastructure.Services
} }
await _historyRepository.AddAsync(user, query); await _historyRepository.AddAsync(user, query);
var queries = query.Split('.').ToList();
if (queries.Count > 2)
{
var q0 = queries[0].Split(' ');
if (q0.Length < 3)
{
queries.RemoveAt(0);
}
if(queries.Last().Length < 5)
{
queries.RemoveAt(queries.Count - 1);
}
}
query = String.Join(".", queries);
var result = await sendRequest(query);
if(result.Count == 0)
{
result = await sendRequest(queries.Last());
}
return result;
}
private async Task<List<SearchResultDTO>> sendRequest(string query)
{
WebRequest webRequest = WebRequest.Create($"https://www.googleapis.com/customsearch/v1?key={apiKey}&cx={searchEngineId}&q={query}"); WebRequest webRequest = WebRequest.Create($"https://www.googleapis.com/customsearch/v1?key={apiKey}&cx={searchEngineId}&q={query}");
using (var stream = new StreamReader(webRequest.GetResponse().GetResponseStream())) using (var stream = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{ {
@ -42,7 +66,9 @@ namespace Serwer.Infrastructure.Services
dynamic jsonData = JsonConvert.DeserializeObject(response); dynamic jsonData = JsonConvert.DeserializeObject(response);
var results = new List<SearchResultDTO>(); var results = new List<SearchResultDTO>();
foreach(var item in jsonData.items) try
{
foreach (var item in jsonData.items)
{ {
results.Add(new SearchResultDTO results.Add(new SearchResultDTO
{ {
@ -53,6 +79,11 @@ namespace Serwer.Infrastructure.Services
} }
return results; return results;
} }
catch(Exception)
{
return results;
}
}
} }
} }
} }