Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.38 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net.Http;
  7. using System.Net.Http.Headers;
  8. using System.Web;
  9. using System.IO;
  10. using System.Collections;
  11. using System.Runtime.InteropServices;
  12. using Newtonsoft.Json.Linq;
  13. using Newtonsoft.Json;
  14. using System.Web.Script.Serialization;
  15.  
  16. namespace ACT_SKUSKA
  17. {
  18.     class Program
  19.     {
  20.  
  21.         // Replace <Subscription Key> with your valid subscription key.
  22.         const string subscriptionKey = "1ef2a67d893a4e93a8f186e3ef0c7b59";
  23.         static List<string> list = new List<string>();
  24.         static string helper = "";
  25.  
  26.         // replace <myresourcename> with the string found in your endpoint URL
  27.         const string uriBase =
  28.             "https://faceappcloudy.cognitiveservices.azure.com/face/v1.0/detect";
  29.  
  30.         const string imageFilePath = @"D:\Skola\ACT\Skuska\famiily-inner-pic.jpg";
  31.         static int count = 0;
  32.  
  33.         static void Main(string[] args)
  34.         {
  35.  
  36.             // Get the path and filename to process from the user.
  37.             Console.WriteLine("Detect faces:");
  38.             //Console.Write(
  39.             //"Enter the path to an image with faces that you wish to analyze: ");
  40.  
  41.             if (File.Exists(imageFilePath))
  42.             {
  43.                 try
  44.                 {
  45.                     MakeAnalysisRequest(imageFilePath);
  46.                     Console.WriteLine("\nWait a moment for the results to appear.\n");
  47.                 }
  48.                 catch (Exception e)
  49.                 {
  50.                     Console.WriteLine("\n" + e.Message + "\nPress Enter to exit...\n");
  51.                 }
  52.             }
  53.             else
  54.             {
  55.                 Console.WriteLine("\nInvalid file path.\nPress Enter to exit...\n");
  56.             }
  57.  
  58.             Console.ReadLine();
  59.         }
  60.         // Gets the analysis of the specified image by using the Face REST API.
  61.         static async void MakeAnalysisRequest(string imageFilePath)
  62.         {
  63.             HttpClient client = new HttpClient();
  64.  
  65.             // Request headers.
  66.             client.DefaultRequestHeaders.Add(
  67.                 "Ocp-Apim-Subscription-Key", subscriptionKey);
  68.  
  69.             // Request parameters. A third optional parameter is "details".
  70.             string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" +
  71.                 "&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +
  72.                 "emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
  73.  
  74.             // Assemble the URI for the REST API Call.
  75.             string uri = uriBase + "?" + requestParameters;
  76.  
  77.             HttpResponseMessage response;
  78.  
  79.             // Request body. Posts a locally stored JPEG image.
  80.             byte[] byteData = GetImageAsByteArray(imageFilePath);
  81.  
  82.             using (ByteArrayContent content = new ByteArrayContent(byteData))
  83.             {
  84.                 // This example uses content type "application/octet-stream".
  85.                 // The other content types you can use are "application/json"
  86.                 // and "multipart/form-data".
  87.                 content.Headers.ContentType =
  88.                     new MediaTypeHeaderValue("application/octet-stream");
  89.  
  90.                 // Execute the REST API call.
  91.                 response = await client.PostAsync(uri, content);
  92.  
  93.                 // Get the JSON response.
  94.                 string contentString = await response.Content.ReadAsStringAsync();
  95.  
  96.                 // Display the JSON response.
  97.                 Console.WriteLine("\nResponse:\n");
  98.                 //Console.WriteLine(JsonPrettyPrint(contentString));
  99.                 //var address = new JavaScriptSerializer().Deserialize<dynamic>(contentString);
  100.                 JsonPrettyPrint(contentString);
  101.                 //Console.WriteLine(list.Count);
  102.                 foreach (string str in list)
  103.                 {
  104.                     Console.WriteLine(str);
  105.                    
  106.                 }
  107.                 Console.WriteLine(count);
  108.                 //Console.WriteLine(address[1]);
  109.  
  110.                 Console.WriteLine("\nPress Enter to exit...");
  111.             }
  112.         }
  113.         // Returns the contents of the specified file as a byte array.
  114.         static byte[] GetImageAsByteArray(string imageFilePath)
  115.         {
  116.             using (FileStream fileStream =
  117.                 new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
  118.             {
  119.                 BinaryReader binaryReader = new BinaryReader(fileStream);
  120.                 return binaryReader.ReadBytes((int)fileStream.Length);
  121.             }
  122.         }
  123.  
  124.         // Formats the given JSON string by adding line breaks and indents.
  125.         static public void JsonPrettyPrint(string json)
  126.         {
  127.             //if (string.IsNullOrEmpty(json))
  128.               //  return string.Empty;
  129.  
  130.             json = json.Replace(Environment.NewLine, "").Replace("\t", "");
  131.  
  132.            
  133.  
  134.             StringBuilder sb = new StringBuilder();
  135.             bool quote = false;
  136.             bool ignore = false;
  137.             int offset = 0;
  138.             int indentLength = 3;
  139.  
  140.             foreach (char ch in json)
  141.             {
  142.                 switch (ch)
  143.                 {
  144.                     case '"':
  145.                         if (!ignore) quote = !quote;
  146.                         break;
  147.                     case '\'':
  148.                         if (quote) ignore = !ignore;
  149.                         break;
  150.                 }
  151.  
  152.                 if (quote)
  153.                     sb.Append(ch);
  154.                 else
  155.                 {
  156.                     switch (ch)
  157.                     {
  158.                         case '{':
  159.                         case '[':
  160.                             sb.Append(ch);
  161.                             sb.Append(Environment.NewLine);
  162.                             sb.Append(new string(' ', ++offset * indentLength));
  163.                             break;
  164.                         case '}':
  165.                         case ']':
  166.                             sb.Append(Environment.NewLine);
  167.                             sb.Append(new string(' ', --offset * indentLength));
  168.                             sb.Append(ch);
  169.                             break;
  170.                         case ',':
  171.                             sb.Append(ch);
  172.                             sb.Append(Environment.NewLine);
  173.                             sb.Append(new string(' ', offset * indentLength));
  174.                             break;
  175.                         case ':':
  176.                             sb.Append(ch);
  177.                             sb.Append(' ');
  178.                             break;
  179.                         default:
  180.                             if (ch != ' ') sb.Append(ch);
  181.                             break;
  182.                     }
  183.                 }
  184.             }
  185.             string[] lines = sb.ToString().Split('\n');
  186.            
  187.             foreach (string line in lines)
  188.             {
  189.                 //Console.WriteLine(line);
  190.                 if (line.Contains("age"))
  191.                     {
  192.                     string _line = line.Replace("age", "");
  193.                     _line = _line.Replace('"', ' ');
  194.                     _line = _line.Replace(',', ' ');
  195.                     _line = _line.Replace(':', ' ');
  196.                     list.Add(_line);
  197.                     count++;
  198.                         }
  199.  
  200.             }
  201.  
  202.            
  203.  
  204.         }
  205.     }
  206. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement