Skip to content

Commit

Permalink
Add project files.
Browse files Browse the repository at this point in the history
  • Loading branch information
intisor committed Oct 3, 2024
1 parent 25e746f commit 8238f46
Show file tree
Hide file tree
Showing 85 changed files with 74,987 additions and 0 deletions.
133 changes: 133 additions & 0 deletions Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Parser;
using MalfuzatExplorer.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace MalfuzatExplorer.Controllers
{
public class HomeController : Controller
{
private string pdfPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Malfuzat", "Malfuzat-1.pdf");


public IActionResult Index()
{
var model = new MalfuzatModel();
return View(model);
}
[HttpPost]
public async Task<IActionResult> Search(MalfuzatModel model)
{
if (string.IsNullOrEmpty(model.Query))
{
ModelState.AddModelError("", "Please enter a valid Search query.");
return View("Index", model);
}

List<string> results = await SearchPdfForQueryAsync(model.Query);
if (results.Count == 0)
{
model.Results = new List<string> { $"No results found for '{model.Query}'." };
}
else
{
model.Results = results;
}

for (int i = 0; i < results.Count; i++)
{
results[i] = await SpecialLanguageAsync(results[i], model.Query);
}

model.Results = results;
return View("Index", model);
}

public IActionResult Privacy()
{
return View();
}

public async Task<List<string>> SearchPdfForQueryAsync(string query)
{
List<string> results = new List<string>();
try
{
if (!System.IO.File.Exists(pdfPath))
{
throw new FileNotFoundException("PDF file not found.");
}

using (PdfReader reader = new PdfReader(pdfPath))
using (PdfDocument document = new PdfDocument(reader))
{


for (int i = 1; i <= document.GetNumberOfPages(); i++)
{
string pageText = PdfTextExtractor.GetTextFromPage(document.GetPage(i));
if (pageText.Contains(query, StringComparison.OrdinalIgnoreCase))
{
string result = $"Found on leaf {i}: " + await GetContextAroundQueryAsync(pageText, query);

results.Add(result);
}
}
}
}
catch (Exception ex)
{
results.Add("An error occurred while searching the PDF.");
}

return results;
}

public async Task<string> GetContextAroundQueryAsync(string content, string query)
{
query = query.Trim();
string[] words = content.Split(new[] { ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries);

// Find the index of the query word in the words array
int queryIndex = Array.FindIndex(words, w => w.Contains(query, StringComparison.OrdinalIgnoreCase));
if (queryIndex < 0)
return "Query not found";
int start = Math.Max(0, queryIndex - 100);
int end = Math.Min(words.Length, queryIndex + 100 + query.Length);
string result = string.Join(" ", words.Skip(start).Take(end - start));
//result = result.Replace("\n", "<br/>").Replace("\r", "");
result = await HighlightQueryAsync(result, query);
return result;
}


private async Task<string> HighlightQueryAsync(string text, string query)
{
return await Task.Run(() =>
Regex.Replace(text, Regex.Escape(query), $"<mark>{query}</mark>", RegexOptions.IgnoreCase)
);
}


public async Task<string> SpecialLanguageAsync(string result, string query)
{
result = await HighlightQueryAsync(result, query);
string pattern = @"[\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]+";
string highlightedResult = Regex.Replace(result, pattern, match =>
{
return $"<span class=\"special\" dir=\"rtl\">{match.Value}</span>";
});

return highlightedResult;
}


[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
14 changes: 14 additions & 0 deletions MalfuzatExplorer.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="itext7" Version="8.0.5" />
<PackageReference Include="NEST" Version="7.17.5" />
</ItemGroup>

</Project>
25 changes: 25 additions & 0 deletions MalfuzatExplorer.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.35122.118
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MalfuzatExplorer", "MalfuzatExplorer.csproj", "{93516313-8C32-4067-9259-FFA6B9CA20D4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{93516313-8C32-4067-9259-FFA6B9CA20D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{93516313-8C32-4067-9259-FFA6B9CA20D4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{93516313-8C32-4067-9259-FFA6B9CA20D4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{93516313-8C32-4067-9259-FFA6B9CA20D4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {12204907-4075-49F3-BDE4-E4EA6B7983B5}
EndGlobalSection
EndGlobal
9 changes: 9 additions & 0 deletions Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace MalfuzatExplorer.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
9 changes: 9 additions & 0 deletions Models/MalfuzatModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace MalfuzatExplorer.Models
{
public class MalfuzatModel
{
public string Query { get; set; }
public List<string> Results {get; set; } = new List<string>();
public int PageNumber { get; set; }
}
}
31 changes: 31 additions & 0 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
//app.MapControllerRoute(
// name: "indexPdf",
// pattern: "index-pdf",
// defaults: new { controller = "Malfuzat", action = "IndexPdf" }
//);
app.Run();
38 changes: 38 additions & 0 deletions Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:37769",
"sslPort": 44356
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5278",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7163;http://localhost:5278",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
80 changes: 80 additions & 0 deletions Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
@model MalfuzatExplorer.Models.MalfuzatModel
@{
ViewData["Title"] = "Home Page";
}
<div class="container">
<h2 class="display-4">Welcome to Malfuzat Explorer</h2>
<p>Search for your favorite Malfuzat contents</p>
@if (Model!= null)
{
<form asp-action="Search" method="post" class="mb-4">
<div class="form-group">
<div class="row">
<div class="col-md-9">
<input type="text" name="Query" value="@Model.Query" class="form-control" />
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-primary w-100">Search</button>
</div>
</div>
</div>
</form>
@if (Model.Results.Count > 0)
{
<h4>Search Results: (@Model.Results.Count) </h4>
<ul class="list-group">
@for (int i = 0; i < Model.Results.Count; i++)
{
var item = Model.Results[i];
var cssClass = i % 2 == 0 ? "list-group-item even" : "list-group-item odd";
<li class="@cssClass">
<p>@Html.Raw(item)</p>
</li>
}
</ul>
}

}
</div>

<style>
mark {
background-color: yellow;
color: black;
}
.special[dir="rtl"] {
text-align: right;
direction: rtl;
color: limegreen;
font-weight: bold;
font-family: 'Noto Nastaliq Urdu', 'Amiri', serif;
}
.container {
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}
.btn:hover {
background-color: #0056b3;
}
.list-group-item {
padding: 1rem;
margin-bottom: 0.5rem;
background-color: #f8f9fa;
border: 1px solid #ddd;
border-radius: 4px;
}
.list-group-item.odd {
background-color: #f8f9fa;
}
.list-group-item.even {
background-color: #d1ecf1;
}
</style>
9 changes: 9 additions & 0 deletions Views/Home/Privacy.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<p>Use this page to detail your site's privacy policy.</p>

<p>Created by <a href="https://www.linkedin.com/in/intitech07/"> Abdulawwal Intisor. </a></p>

25 changes: 25 additions & 0 deletions Views/Shared/Error.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
Loading

0 comments on commit 8238f46

Please sign in to comment.