-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
82 lines (66 loc) · 2.52 KB
/
Program.cs
File metadata and controls
82 lines (66 loc) · 2.52 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
using System;
using System.Net.Http;
using System.Text.Json.Nodes;
using MimeTypes;
using RestSharp;
#pragma warning disable CS0162
/*
* Use "demo" mode just to try api4ai for free. ⚠️ Free demo is rate limited and must not be used in real projects.
*
* Use 'normal' mode if you have an API Key from the API4AI Developer Portal. This is the method that users should normally prefer.
*
* Use 'rapidapi' if you want to try api4ai via RapidAPI marketplace.
* For more details visit:
* https://rapidapi.com/api4ai-api4ai-default/api/general-classification1/details
*/
const String MODE = "demo";
/*
* Your RapidAPI key. Fill this variable with the proper value if you have one.
*/
const String API4AI_KEY = "";
/*
* Your RapidAPI key. Fill this variable with the proper value if you want
* to try api4ai via RapidAPI marketplace.
*/
const String RAPIDAPI_KEY = "";
String url;
Dictionary<String, String> headers = new Dictionary<String, String>();
switch (MODE) {
case "demo":
url = "https://demo.api4ai.cloud/general-cls/v1/results";
break;
case "normal":
url = "https://api4ai.cloud/general-cls/v1/results";
headers.Add("X-API-KEY", API4AI_KEY);
break;
case "rapidapi":
url = "https://general-classification1.p.rapidapi.com/v1/results";
headers.Add("X-RapidAPI-Key", RAPIDAPI_KEY);
break;
default:
Console.WriteLine($"[e] Unsupported mode: {MODE}");
return 1;
}
// Prepare request.
String image = args.Length > 0 ? args[0] : "https://static.api4.ai/samples/general-cls-2.jpg";
var client = new RestClient(new RestClientOptions(url) { ThrowOnAnyError = true });
var request = new RestRequest();
if (image.Contains("://")) {
request.AddParameter("url", image);
} else {
request.AddFile("image", image, MimeTypeMap.GetMimeType(Path.GetExtension(image)));
}
request.AddHeaders(headers);
// Perform request.
var jsonResponse = (await client.ExecutePostAsync(request)).Content!;
// Print raw response.
Console.WriteLine($"[i] Raw response:\n{jsonResponse}\n");
// Parse response and print top 5 classes.
JsonNode docRoot = JsonNode.Parse(jsonResponse)!.Root;
JsonObject classes = docRoot["results"]![0]!["entities"]![0]!["classes"]!.AsObject();
Console.WriteLine("[i] Top 5 classes:");
var top5 = (from c in classes orderby (double)c.Value descending select c).Take(5);
foreach (var item in top5) {
Console.WriteLine($"{item.Key}: {item.Value}");
}
return 0;