-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
346 lines (309 loc) · 12.4 KB
/
Program.cs
File metadata and controls
346 lines (309 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
using com.sun.tools.javac.util;
using com.sun.xml.@internal.xsom.impl.parser;
using edu.stanford.nlp.ie.crf;
using edu.stanford.nlp.ling;
using edu.stanford.nlp.parser.lexparser;
using edu.stanford.nlp.pipeline;
using edu.stanford.nlp.process;
using edu.stanford.nlp.tagger.maxent;
using edu.stanford.nlp.time;
using edu.stanford.nlp.trees;
using edu.stanford.nlp.util;
using java.util;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.JsonPatch.Adapters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OData.ModelBuilder;
using Microsoft.OpenApi.Models;
using OneOf;
using RandomAPIApp.DTOs;
using RandomAPIApp.Options;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using List = java.util.List;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions<JWTOptions>()
.Bind(builder.Configuration.GetSection(nameof(JWTOptions)));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme,
options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = builder.Configuration.GetSection($"{nameof(JWTOptions)}:{nameof(JWTOptions.Issuer)}").Value,
ValidAudience = builder.Configuration.GetSection($"{nameof(JWTOptions)}:{nameof(JWTOptions.Audience)}").Value,
IssuerSigningKeys = new[]{
CreateSymmetricKey(builder.Configuration.GetSection($"{nameof(JWTOptions)}:{nameof(JWTOptions.Secret)}").Value ??
throw new InvalidOperationException("JWT secret is not set"))
},
ValidateLifetime = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine($"Auth failed: {context.Exception.GetType().Name} - {context.Exception.Message}");
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
return Task.CompletedTask;
}
};
});
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
string id = "Bearer";
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My API",
Version = "v1",
});
c.AddSecurityDefinition(id, new OpenApiSecurityScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\". You may use /jwt endpoint to get a jwt token.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
});
//this is a dictionary....
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = id
}
},
new List<string>()
}
});
});
builder.Services.AddCors(options =>
{
options.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy(Policy.USER_NAME, policy =>
policy.RequireClaim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Name));
ODataConventionModelBuilder modelBuilder = new();
modelBuilder.EntityType<OrderDTO>();
modelBuilder.EntitySet<CustomerDTO>("Customers");
//builder.Services.AddControllers().AddOData(
//options =>
//{
// options.Select().Filter().OrderBy().Expand().Count().SetMaxTop(null)
// .AddRouteComponents("odata", modelBuilder.GetEdmModel());
//});
builder.Services.AddControllers();
WebApplication app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
options.RoutePrefix = string.Empty;
});
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/jwt", (IOptions<JWTOptions> options) =>
{
Claim[] claims = new Claim[]
{
new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Name, "user@example.com"),
};
string secretKey = options.Value.Secret;
// Create a symmetric security key using the secret key
SymmetricSecurityKey securityKey = CreateSymmetricKey(secretKey);
// Create the JWT security token
JwtSecurityToken token = new JwtSecurityToken(
issuer: options.Value.Issuer,
audience: options.Value.Audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature)
);
JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler();
string jwtToken = jwtHandler.WriteToken(token);
return Results.Ok(jwtToken);
}).Produces<string>(StatusCodes.Status200OK)
.WithDescription("Get JWT Token for authorization")
.WithTags("Token");
app.MapPost("/api/pos", ([FromBody] PartOfSpeechTaggerDTO pos) =>
{
java.io.StringReader reader = new java.io.StringReader(pos.Input);
object[] sentences = MaxentTagger.tokenizeText(reader).toArray();
string[] taggedSentences = new string[sentences.Length];
int i = 0;
foreach (List sentence in sentences.Cast<List>())
{
var taggedSentence = StanfordNLP.MaxentTagger.Value.tagSentence(sentence);
taggedSentences[i] = SentenceUtils.listToString(taggedSentence, false);
i++;
}
reader.close();
return Results.Ok(new PartOfSpeechTaggerDTO
{
Input = pos.Input,
Output = taggedSentences
});
}).Produces<PartOfSpeechTaggerDTO>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status401Unauthorized)
.RequireAuthorization(Policy.USER_NAME)
.WithDescription("Part-Of-Speech Tagger")
.WithTags("Part-Of-Speech Tagger");
app.MapPost("/api/parser", ([FromBody] ParserDTO parser) =>
{
//The PTB (Penn Treebank) Tokenizer is a tool for dividing a block of text into individual tokens,
//or "words," that are appropriate for use in natural language processing tasks
TokenizerFactory tokenizerFactory = PTBTokenizer.factory(new CoreLabelTokenFactory(), "");
java.io.StringReader sentenceReader = new java.io.StringReader(parser.Input);
List rawWords = tokenizerFactory.getTokenizer(sentenceReader).tokenize();
sentenceReader.close();
Tree tree2 = StanfordNLP.Parser.Value.apply(rawWords);
////prints out a representation of a tree in Penn Treebank format.
////The Penn Treebank is a set of annotated corpora for natural language processing tasks,
////including part-of-speech tagging and parsing.
//tree2.pennPrint();
// Extract dependencies from lexical tree
PennTreebankLanguagePack tlp = new PennTreebankLanguagePack();
GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
GrammaticalStructure gs = gsf.newGrammaticalStructure(tree2);
List tdl = gs.typedDependenciesCCprocessed();
//var tp = new TreePrint("penn,typedDependenciesCollapsed");
//tp.printTree(tree2);
string output = SentenceUtils.listToString(tdl, false);
return Results.Ok(new ParserDTO()
{
Input = parser.Input,
Output = output
});
}).Produces<ParserDTO>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status401Unauthorized)
.WithTags("Parser").RequireAuthorization(Policy.USER_NAME);
app.MapPost("/api/ner", (string input) =>
{
string outpt = StanfordNLP.NamedEntityRecognizer.Value.classifyToString(input);
return Results.Ok(outpt);
}).Produces<string>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status401Unauthorized)
.WithTags("Named Entity Recognizer").RequireAuthorization(Policy.USER_NAME);
app.MapPost("/api/sutime", (string input) =>
{
//SUTime (Standford University Time) is a natural language processing tool that is used to identify and normalize time expressions in text.
AnnotationPipeline pipeline = new AnnotationPipeline();
pipeline.addAnnotator(new TokenizerAnnotator(false));
pipeline.addAnnotator(new WordsToSentencesAnnotator(false));
pipeline.addAnnotator(new POSTaggerAnnotator(StanfordNLP.MaxentTagger.Value));
Properties props = new Properties();
props.setProperty("sutime.rules", StanfordNLPModelPath.SUTIME_RULES);
props.setProperty("sutime.binders", "0");
pipeline.addAnnotator(new TimeAnnotator("sutime", props));
Annotation annotation = new Annotation(input);
annotation.set(new CoreAnnotations.DocDateAnnotation().getClass(), "2013-07-14");
pipeline.annotate(annotation);
ArrayList? timexAnnsAll = annotation.get(new TimeAnnotations.TimexAnnotations().getClass()) as ArrayList;
if (timexAnnsAll is not null)
{
List<string> timeStrings = new List<string>();
foreach (CoreMap cm in timexAnnsAll)
{
if (cm.get(new CoreAnnotations.TokensAnnotation().getClass()) is not List tokens)
{
continue;
}
object first = tokens.get(0);
object last = tokens.get(tokens.size() - 1);
if (cm.get(new TimeExpression.Annotation().getClass()) is not TimeExpression time)
{
continue;
}
string timeString = string.Format("{0} [from char offset {1} to {2}] --> {3}", cm, first, last, time.getTemporal());
timeStrings.Add(timeString);
}
return Results.Ok(timeStrings.ToArray());
}
else
{
return Results.Ok(new[] { "No Time Expression Found" });
}
}).Produces<string[]>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status401Unauthorized)
.WithTags("Stanford University Time").RequireAuthorization(Policy.USER_NAME);
app.MapGet("/api/oneOf", () => {
if (DateTime.Now.Second % 2 == 0)
{
return Results.Ok("This is a string result.");
}
else
{
return Results.Ok(DateTime.Now.Second);
}
})
.Produces<OneOf<string, int>>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status401Unauthorized)
.RequireAuthorization(Policy.USER_NAME)
.WithDescription("oneOf<string>")
.WithTags("OneOf");
app.Map("/api/exposed", () =>
{
return "Hola! This is an exposed endpoint.";
})
.Produces<bool>(StatusCodes.Status200OK)
.WithTags("Exposed");
app.MapPatch("/api/Patch", ([FromBody] JsonPatchDocument patchDoc) =>
{
//patchDoc.ApplyTo(new object(), adapter);
// Handle the patch document
patchDoc.Operations.ForEach(op =>
{
Console.WriteLine($"Operation: {op.op}, Path: {op.path}, Value: {op.value}");
});
return Results.Accepted();
})
.Produces(StatusCodes.Status202Accepted)
.WithTags("JsonPatch");
app.MapControllers().RequireCors("MyPolicy");
app.Run();
SymmetricSecurityKey CreateSymmetricKey(string base64SecretKey)
{
byte[] keyBytes = System.Convert.FromBase64String(base64SecretKey);
return new SymmetricSecurityKey(keyBytes);
}
public class StanfordNLPModelPath
{
public const string POS = "english-left3words-distsim.tagger";
public const string PARSER = "englishPCFG.ser.gz"; //English Probabilistic Context-Free Grammar
public const string NAMED_ENTITY_RECOGNIZER = "english.all.3class.distsim.crf.ser.gz";
public const string SUTIME_RULES = "defs.sutime.txt,english.holidays.sutime.txt,english.sutime.txt";
}
public static class StanfordNLP
{
public readonly static Lazy<MaxentTagger> MaxentTagger = new Lazy<MaxentTagger>(() => new MaxentTagger(StanfordNLPModelPath.POS));
public readonly static Lazy<LexicalizedParser> Parser = new Lazy<LexicalizedParser>(() => LexicalizedParser.loadModel(StanfordNLPModelPath.PARSER));
public readonly static Lazy<CRFClassifier> NamedEntityRecognizer = new Lazy<CRFClassifier>(() => CRFClassifier.getClassifierNoExceptions(StanfordNLPModelPath.NAMED_ENTITY_RECOGNIZER));
}
public class Policy
{
public const string USER_NAME = "UserName";
}