Ejemplo n.º 1
0
 internal static async Task<SvcStatus> CreateJob(ParticipantResult participantResult, ParticipantActivity activity)
 {
     CFJobRequest job = new CFJobRequest()
         {
             Title = (participantResult.User.App == Crowd.Model.Data.User.AppType.Speeching) ? "Speeching " : "Fluent" + participantResult.Id,
             Instructions = "Please listen to the audio clip(s) and complete the following tasks, making sure that your computer's volume is loud enough to hear the voice samples clearly",
             PaymentCents = 5,
             UnitsPerAssignment = 2,
             Css = "div.grp { border: solid thin gray; margin: 10px 0; }",
             WebhookUri = ConfidentialData.ApiUrl + "/api/CFWebhook/",
             SupportEmail = ConfidentialData.SupportEmail,
             ResourceUrl = participantResult.ResourceUrl
         };
     return await job.CreateAudioJob(participantResult, activity);
 }
Ejemplo n.º 2
0
        // POST api/Activity
        public HttpResponseMessage Post(ParticipantActivity activity)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            using (CrowdContext db = new CrowdContext())
            {
                db.ParticipantActivities.Add(activity);
                db.SaveChanges();
                var response = Request.CreateResponse(HttpStatusCode.Created, activity);
                return response;
            }
        }
Ejemplo n.º 3
0
        internal async Task<SvcStatus> CreateAudioJob(ParticipantResult result, ParticipantActivity activity)
        {
            SvcStatus status = new SvcStatus();
            try
            {
                string userKey = result.User.Email;

                using (HttpClient client = new HttpClient())
                {
                    FormUrlEncodedContent reqContent = CreateRequestCUrlData(result.User.App);
                    Uri baseAddress = new Uri(CrowdflowerBaseUri + "jobs.json?key=" + CrowdflowerKey);
                    HttpResponseMessage response = client.PostAsync(baseAddress, reqContent).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        CFJobResponse jobRes = await response.Content.ReadAsAsync<CFJobResponse>();
                        List<string> audioFiles = await SvcUtil.DownloadAndExtractZip(ResourceUrl, jobRes.id.ToString(), userKey, activity.Id.ToString());

                        if (!audioFiles.Any()) return status;

                        CFUnitRequest unitsReq = new CFUnitRequest();
                        int count = 0;
                        string uploadUnitsJson = AudioUnit.CreateCFData(audioFiles, activity, result, out count);

                        Rows = await unitsReq.SendCfUnits(jobRes.id, uploadUnitsJson);

                        foreach (CrowdRowResponse unit in Rows)
                        {
                            unit.ParticipantResultId = result.Id;
                        }

                        status = new SvcStatus()
                        {
                            Level = 0,
                            Count = count,
                            Description = "Job created",
                            Response = response,
                            CreatedRows = Rows
                        };
                    }
                    else
                    {
                        status = new SvcStatus() { Level = 2, Description = "Failed to create the job", Response = response };
                    }
                }
            }
            catch (Exception e)
            {
                status = new SvcStatus() { Level = 2, Description = e.Message, Response = new HttpResponseMessage(HttpStatusCode.InternalServerError) };
            }
            
            return status;
        }
Ejemplo n.º 4
0
        public static string CreateCFData(IEnumerable<string> audioPaths, ParticipantActivity activity, ParticipantResult result, out int count)
        {
            count = 0;
            string json = "";
            if (!audioPaths.Any())
                return json;

            using (CrowdContext db = new CrowdContext())
            {
                result = db.ParticipantResults.Find(result.Id);
                CrowdRowResponse[] lastAssessResponses = null;
                CrowdRowResponse[] lastNormResponses = null;
                int lastAssessTaskId = -1;
                int lastNormTaskId = -1;
                string extraData = "";
                if (result.User.App == User.AppType.Speeching)
                {
                    foreach (var path in audioPaths)
                    {
                        string[] options = null;
                        string taskType = "Other";
                        CrowdRowResponse comparionResponse = null;

                        ParticipantResultData thisData = (from data in result.Data
                                                          where data.FilePath == Path.GetFileName(path)
                                                          select data).FirstOrDefault();

                        if (thisData == null)
                        {
                            continue;
                        }

                        int assTaskId = -1;
                        int normTaskId = -1;

                        if (thisData.ParticipantAssessmentTask != null) // Is assessment
                        {
                            ParticipantAssessmentTask task = thisData.ParticipantAssessmentTask;
                            assTaskId = task.Id;

                            List<string> quickFireOptions = new List<string>();
                            foreach (var prompt in task.PromptCol.Prompts)
                            {
                                quickFireOptions.Add(prompt.Value);
                            }
                            options = quickFireOptions.ToArray();

                            switch (task.TaskType)
                            {
                                case ParticipantAssessmentTask.AssessmentTaskType.QuickFire:
                                    taskType = "MP";
                                    break;
                                case ParticipantAssessmentTask.AssessmentTaskType.ImageDesc:
                                    taskType = "Image";
                                    break;
                            }

                            string filename = Path.GetFileNameWithoutExtension(path);
                            string promptId = "";
                            bool started = false;

                            // Get the prompt index from the filename
                            foreach (char c in filename)
                            {
                                if (c == '-')
                                {
                                    started = true;
                                    continue;
                                }
                                if (started && char.IsDigit(c))
                                {
                                    promptId += c;
                                }
                            }

                            if (!string.IsNullOrWhiteSpace(promptId))
                            {
                                extraData = promptId;
                            }

                            if (lastAssessTaskId != task.Id)
                            {
                                lastAssessResponses = (from rowResp in db.CrowdRowResponses
                                                       where rowResp.ParticipantAssessmentTaskId == task.Id &&
                                                             rowResp.ParticipantResult.User.Key == result.User.Key
                                                       orderby rowResp.CreatedAt
                                                       select rowResp).ToArray();
                                lastAssessTaskId = assTaskId;
                            }

                            if (lastAssessResponses != null)
                            {
                                foreach (CrowdRowResponse resp in lastAssessResponses)
                                {
                                    // Can't use GetFileName in LINQ expressions so have to do in memory
                                    bool matches = Path.GetFileName(resp.RecordingUrl) == Path.GetFileName(path);
                                    if (!matches) continue;

                                    comparionResponse = resp;
                                    break;
                                }
                            }

                        }
                        else if (thisData.ParticipantTask != null) // Not assessment
                        {
                            normTaskId = thisData.ParticipantTask.Id;
                            if (lastNormTaskId != normTaskId)
                            {
                                lastNormResponses = (from rowResp in db.CrowdRowResponses
                                                     where rowResp.ParticipantTaskId == normTaskId &&
                                                           rowResp.ParticipantResult.User.Key == result.User.Key
                                                     orderby rowResp.CreatedAt
                                                     select rowResp).ToArray();
                                lastNormTaskId = normTaskId;
                            }
                            if (lastNormResponses != null)
                            {
                                foreach (CrowdRowResponse resp in lastNormResponses)
                                {
                                    // Can't use GetFileName in LINQ expressions so have to do in memory
                                    bool matches = Path.GetFileName(resp.RecordingUrl) == Path.GetFileName(path);
                                    if (!matches) continue;

                                    comparionResponse = resp;
                                    break;
                                }
                            }
                        }

                        string choices = "";
                        string comparisonPath = "";
                        int prevLoud = -1;
                        int prevPace = -1;
                        int prevPitch = -1;

                        if (options != null)
                        {
                            // Shuffle the words
                            Random rnd = new Random();
                            options = options.OrderBy(x => rnd.Next()).ToArray();

                            for (int i = 0; i < options.Length; i++)
                            {
                                choices += options[i];
                                if (i < options.Length - 1) choices += ", ";
                            }
                        }

                        if (comparionResponse != null)
                        {
                            comparisonPath = comparionResponse.RecordingUrl;
                            prevLoud = GetAverageRes(comparionResponse, "rlstvolume");
                            prevPace = GetAverageRes(comparionResponse, "rlstpace");
                            prevPitch = GetAverageRes(comparionResponse, "rlstpitch");
                        }

                        json += createUnit(path, taskType, assTaskId, normTaskId, choices, prevLoud, prevPace, prevPitch, comparisonPath, extraData);

                        count += 1;
                    }
                }
                else //Fluent
                {
                    json += string.Format("{{\"AudioUrls\":\"{0}\", " +
                                              "\"FeedbackQuery\":\"{1}\"}}\r\n"
                            , String.Join(",", audioPaths), result.FeedbackQuery);
                    count += 1;
                }

            }
            json += TestQuestions();
            json = json.TrimEnd();

            return json;
        }
Ejemplo n.º 5
0
        // PUT api/Activity/5
        public HttpResponseMessage Put(int id, ParticipantActivity activity)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (id != activity.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            using (CrowdContext db = new CrowdContext())
            {
                db.ParticipantActivities.Attach(activity);
                db.Entry(activity).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
        }