This repository was archived by the owner on May 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathProgram.cs
More file actions
222 lines (185 loc) · 9.17 KB
/
Copy pathProgram.cs
File metadata and controls
222 lines (185 loc) · 9.17 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
using Azure;
using Azure.AI.TextAnalytics;
using CrawlFeaturizer.ActionFeaturizer;
using CrawlFeaturizer.ActionProvider;
using CrawlFeaturizer.Model;
using CrawlFeaturizer.Util;
using Microsoft.Azure.CognitiveServices.Personalizer;
using Microsoft.Azure.CognitiveServices.Personalizer.Models;
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CrawlFeaturizer
{
internal class Program
{
// The key specific to your personalization service instance; e.g. "0123456789abcdef0123456789ABCDEF"
private const string ApiKey = "";
// The endpoint specific to your personalization service instance; e.g. https://westus2.api.cognitive.microsoft.com/
private const string ServiceEndpoint = "";
// Cognitive Service TextAnalytics Endpoint
private const string CognitiveTextAnalyticsEndpoint = "";
// API Key for the Cognitive Service for Text Analytics. See this Azure CLI Link to get the key: https://docs.microsoft.com/en-us/cli/azure/cognitiveservices/account/keys?view=azure-cli-latest#az-cognitiveservices-account-keys-list-examples
private const string CognitiveTextAnalyticsAPIKey = "";
/// <summary>
/// RSS feeds for different news topics
/// </summary>
private static readonly Dictionary<string, string> newsRSSFeeds = new Dictionary<string, string>()
{
{ "World" , "http://rss.cnn.com/rss/cnn_world.rss" },
{ "Business", "http://rss.cnn.com/rss/money_latest.rss"},
{ "Technology", "http://rss.cnn.com/rss/cnn_tech.rss"},
{ "Health", "http://rss.cnn.com/rss/cnn_health.rss"},
{ "Entertainment", "http://rss.cnn.com/rss/cnn_showbiz.rss"},
{ "Travel", "http://rss.cnn.com/rss/cnn_travel.rss"}
};
private static void Main(string[] args)
{
int iteration = 1;
bool runLoop = true;
// Initialize Personalization client.
PersonalizerClient client = InitializePersonalizationClient(ServiceEndpoint);
// Initialize the RSS Feed actions provider
IActionProvider actionProvider = new RSSFeedActionProvider(new RSSParser
{
// Number of items to fetch while crawling the RSS feed
ItemLimit = 2
});
// Initialize the Cognitive Services TextAnalyticsClient for featurizing the crawled action articles
TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClient(new Uri(CognitiveTextAnalyticsEndpoint), new AzureKeyCredential(CognitiveTextAnalyticsAPIKey));
// Initialize the Cognitive Text Analytics actions featurizer
IActionFeaturizer actionFeaturizer = new CognitiveTextAnalyticsFeaturizer(textAnalyticsClient);
var newsActions = new List<RankableAction>();
foreach (var newsTopic in newsRSSFeeds)
{
Console.WriteLine($"Fetching Actions for: {newsTopic.Key} from {newsTopic.Value}");
IList<CrawlAction> crawlActions = actionProvider.GetActionsAsync(newsTopic.Value).Result.ToList();
Console.WriteLine($"Fetched {crawlActions.Count} actions");
actionFeaturizer.FeaturizeActionsAsync(crawlActions).ConfigureAwait(false);
Console.WriteLine($"Featurized actions for {newsTopic.Key}");
// Generate a rankable action for each crawlAction and add the news topic as additional feature
newsActions.AddRange(crawlActions.Select(a =>
{
a.Features.Add(new { topic = newsTopic.Key });
return (RankableAction)a;
}).ToList());
}
do
{
Console.WriteLine("Iteration: " + iteration++);
// Get context information from the user.
string username = GetUserName();
string timeOfDay = GetUsersTimeOfDay();
string location = GetLocation();
// Create current context from user specified data.
IList<object> currentContext = new List<object>() {
new { username },
new { timeOfDay },
new { location }
};
// Id to associate with the request
string eventId = Guid.NewGuid().ToString();
// Rank the actions
var request = new RankRequest(newsActions, currentContext, null, eventId);
RankResponse response = client.Rank(request);
var recommendedAction = newsActions.Where(a => a.Id.Equals(response.RewardActionId)).FirstOrDefault();
Console.WriteLine("Personalization service thinks you would like to read: ");
Console.WriteLine("Id: " + recommendedAction.Id);
JsonSerializerOptions options = new JsonSerializerOptions
{
WriteIndented = true
};
Console.WriteLine("Features : " + JsonSerializer.Serialize(recommendedAction.Features, options));
Console.WriteLine("Do you like this article ?(y/n)");
float reward = 0.0f;
string answer = GetKey();
if (answer == "Y")
{
reward = 1;
Console.WriteLine("Great!");
}
else if (answer == "N")
{
reward = 0;
Console.WriteLine("You didn't like the recommended news article.");
}
else
{
Console.WriteLine("Entered choice is invalid. Service assumes that you didn't like the recommended news article.");
}
Console.WriteLine("Personalization service ranked the actions with the probabilities as below:");
Console.WriteLine("{0, 10} {1, 0}", "Probability", "Id");
var rankedResponses = response.Ranking.OrderByDescending(r => r.Probability);
foreach (var rankedResponse in rankedResponses)
{
Console.WriteLine("{0, 10} {1, 0}", rankedResponse.Probability, rankedResponse.Id);
}
// Send the reward for the action based on user response.
client.Reward(response.EventId, new RewardRequest(reward));
Console.WriteLine("Press q to break, any other key to continue:");
runLoop = !(GetKey() == "Q");
} while (runLoop);
}
/// <summary>
/// Initializes the personalization client.
/// </summary>
/// <param name="url">Azure endpoint</param>
/// <returns>Personalization client instance</returns>
private static PersonalizerClient InitializePersonalizationClient(string url)
{
PersonalizerClient client = new PersonalizerClient(
new ApiKeyServiceClientCredentials(ApiKey))
{ Endpoint = url };
return client;
}
/// <summary>
/// Get user's name.
/// </summary>
/// <returns>User's name.</returns>
private static string GetUserName()
{
Console.WriteLine("What is your name?");
string name = Console.ReadLine();
Console.WriteLine($"Hi {name}");
return name;
}
/// <summary>
/// Get user's time of the day context.
/// </summary>
/// <returns>Time of day feature selected by the user.</returns>
private static string GetUsersTimeOfDay()
{
string[] timeOfDayFeatures = new string[] { "morning", "afternoon", "evening", "night" };
Console.WriteLine("What time of day is it (enter number)? 1. morning 2. afternoon 3. evening 4. night");
if (!int.TryParse(GetKey(), out int timeIndex) || timeIndex < 1 || timeIndex > timeOfDayFeatures.Length)
{
Console.WriteLine("Entered value is invalid. Setting feature value to " + timeOfDayFeatures[0] + ".");
timeIndex = 1;
}
return timeOfDayFeatures[timeIndex - 1];
}
/// <summary>
/// Get user's reading location.
/// </summary>
/// <returns>Selected location.</returns>
private static string GetLocation()
{
string[] location = new string[] { "At home", "At work", "Travelling", "Other" };
var options = string.Join(" ", location.Select((x, i) => string.Format("{0}. {1}", i + 1, x)));
Console.WriteLine($"Where do you want to read? {options}");
if (!int.TryParse(GetKey(), out int locIndex) || locIndex < 1 || locIndex > location.Count())
{
Console.WriteLine("Entered value is invalid. Setting feature value to " + location[0] + ".");
locIndex = 1;
}
return location[locIndex - 1];
}
private static string GetKey()
{
string key = Console.ReadKey().Key.ToString().Last().ToString().ToUpper();
Console.WriteLine();
return key;
}
}
}