コード例 #1
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(MecanexUserRequest $request)
 {
     //		$thematic_area=$request->interest;
     //		dd($thematic_area);
     $mecanexuser = MecanexUser::create($request->all());
     $username = $request->username;
     $user = User::where('username', $username)->get()->first();
     // create records in table users_terms-scores once a mecanex user has been created
     $terms = Term::all();
     $total_terms = $terms->count();
     foreach ($terms as $term) {
         $mecanexuser->term()->sync([$term->id => ['user_score' => 0]], false);
         $mecanexuser->profilescore()->sync([$term->id => ['profile_score' => 0]], false);
     }
     //create record in table mecanex_user_term_home_term_neighbor once a mecanex user has been created
     for ($i = 1; $i <= $total_terms; $i++) {
         for ($j = $i + 1; $j <= $total_terms; $j++) {
             $mec_matrix = new MecanexUserTermHomeTermNeighbour();
             $mec_matrix->mecanex_user_id = $mecanexuser->id;
             $mec_matrix->term_home_id = $i;
             $mec_matrix->term_neighbor_id = $j;
             $mec_matrix->link_score = 0.1;
             $mec_matrix->save();
         }
     }
     //the following is only needed for linking an existing authorized user (users_table) with a new mecanex user provided they have the same username
     if (empty($user)) {
         $response = array('message' => 'Store successful');
     } else {
         $mecanexuser->user_id = $user->id;
         $mecanexuser->save();
         $response = array('message' => 'Store successful');
     }
     return response($response, 201)->header('Content-Type', 'application/json');
 }
コード例 #2
0
ファイル: ImportController.php プロジェクト: skafetzo/SPtool
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function scores()
 {
     //indexing of video terms
     set_time_limit(0);
     DB::table('videos_terms_scores')->delete();
     //$counts=DB::select('select count(video_id) from videos');  //take number of videos
     //dd($counts);
     $terms = Term::all();
     //take all Profile terms
     $videos = Video::all();
     foreach ($videos as $video) {
         $id = $video->id;
         foreach ($terms as $term) {
             $results = DB::select(DB::raw('select MATCH (genre, topic, geographical_coverage, thesaurus_terms, title) AGAINST (? WITH QUERY EXPANSION)  as rev from videos where id = (?)'), [$term->term, $id]);
             echo 'video_id=' . $id . '  term = ' . $term->term . '   score = ' . $results[0]->rev . '<br>';
             DB::table('videos_terms_scores')->insert(['video_id' => $id, 'term_id' => $term->id, 'video_score' => $results[0]->rev]);
             echo 'record inserted!' . '<br>';
         }
     }
     ///////////////////normalization///////////////////////////////////////////////////
     //this takes for ever....raw db instead
     //				foreach ($videos as $video) {
     //				$id = $video->id;
     //				$max_score = DB::table('videos_terms_scores')->where('video_id',$id)->max('video_score');
     //					foreach ($terms as $term) {
     //						$temp_video = $video->term->find($term);
     //						$video_term_score = $temp_video->pivot->video_score;  //get score of video
     //						$new_score=$video_term_score/$max_score;
     //						$video->term()->sync([$term->id=> ['video_score' => $new_score]], false);
     //
     //					}
     //				}
     $query = DB::select(DB::raw('UPDATE videos_terms_scores as t join (select video_id,MAX(video_score) as maximum FROM videos_terms_scores GROUP BY video_id)as max_scores  on  t.video_id=max_scores.video_id  SET t.video_score=t.video_score/max_scores.maximum'));
     //return view ('video.parser');
 }
コード例 #3
0
 public function remove_duplicates_on_score()
 {
     $terms = Term::all();
     //take all Profile terms
     $videos = Video::all();
     foreach ($videos as $video) {
         $id = $video->id;
         foreach ($terms as $term) {
             $results = DB::select(DB::raw('select * from videos_terms_scores where video_id=? and term_id=?'), [$id, $term->id]);
             if (count($results) > 1) {
                 DB::table('videos_terms_scores')->where('video_id', $id)->where('term_id', $term->id)->delete();
                 DB::table('videos_terms_scores')->insert(['video_id' => $results[0]->video_id, 'term_id' => $results[0]->term_id, 'video_score' => $results[0]->video_score]);
             }
         }
     }
     return "removed duplicates";
 }
コード例 #4
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function checkprofile()
 {
     $mecanex_user = Auth::user()->mecanex_user;
     $terms = Term::all();
     $interests = Interest::all();
     $listterms = [];
     $listscores = [];
     foreach ($interests as $interest) {
         array_push($listterms, $interest->interest);
     }
     foreach ($terms as $term) {
         $temp_user = $mecanex_user->profilescore->find($term->id);
         $user_term_score = $temp_user->pivot->profile_score;
         array_push($listscores, $user_term_score);
     }
     $userprofile = array_combine($listterms, $listscores);
     return view('user.checkprofile', compact('userprofile'));
 }
コード例 #5
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(CreateProfileRequest $request)
 {
     //validation first
     $request->all();
     $username = Auth::user()->username;
     $email = Auth::user()->email;
     $name = Input::get('name');
     $surname = Input::get('surname');
     $gender_id = Input::get('gender_id');
     $age_id = Input::get('age_id');
     $country_id = Input::get('country_id');
     $occupation_id = Input::get('occupation_id');
     $education_id = Input::get('education_id');
     //$facebook=Input::get('facebook');
     //$twitter=Input::get('twitter');
     $mecanex_user = new MecanexUser(['username' => $username, 'name' => $name, 'surname' => $surname, 'gender_id' => $gender_id, 'age_id' => $age_id, 'education_id' => $education_id, 'occupation_id' => $occupation_id, 'country_id' => $country_id, 'email' => $email]);
     $user = User::find(Auth::user()->id);
     $mecanex_user = $user->profile()->save($mecanex_user);
     //$mecanex_user->save();
     // create records in table users_terms-scores once a mecanex user has been created
     $terms = Term::all();
     $total_terms = $terms->count();
     foreach ($terms as $term) {
         $mecanex_user->term()->sync([$term->id => ['user_score' => 0]], false);
         $mecanex_user->profilescore()->sync([$term->id => ['profile_score' => 0]], false);
     }
     //create record in table mecanex_user_term_home_term_neighbor once a mecanex user has been created
     for ($i = 1; $i <= $total_terms; $i++) {
         for ($j = $i + 1; $j <= $total_terms; $j++) {
             $mec_matrix = new MecanexUserTermHomeTermNeighbour();
             $mec_matrix->mecanex_user_id = $mecanex_user->id;
             $mec_matrix->term_home_id = $i;
             $mec_matrix->term_neighbor_id = $j;
             $mec_matrix->link_score = 0.05;
             $mec_matrix->save();
         }
     }
     return view('user.profile')->with('message', 'You can now state your interests');
     //
 }
コード例 #6
0
 /**
  * Update the specified resource in storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function update(Request $request)
 {
     //
     //get the input
     $arts = $request->arts;
     $disasters = $request->disasters;
     $education = $request->education;
     $environment = $request->environment;
     $health = $request->health;
     $lifestyle = $request->lifestyle;
     $media = $request->media;
     $holidays = $request->holidays;
     $politics = $request->politics;
     $religion = $request->religion;
     $society = $request->society;
     $transportation = $request->transportation;
     $wars = $request->wars;
     $work = $request->work;
     //delete all records of that user in pivot table
     $mecanex_user = Auth::user()->mecanex_user;
     $mecanex_user->interest()->detach();
     //store input in pivot table
     $mecanex_user->interest()->sync([1 => ['interest_score' => $arts], 2 => ['interest_score' => $disasters], 3 => ['interest_score' => $education], 4 => ['interest_score' => $environment], 5 => ['interest_score' => $health], 6 => ['interest_score' => $lifestyle], 7 => ['interest_score' => $media], 8 => ['interest_score' => $holidays], 9 => ['interest_score' => $politics], 10 => ['interest_score' => $religion], 11 => ['interest_score' => $society], 12 => ['interest_score' => $transportation], 13 => ['interest_score' => $wars], 14 => ['interest_score' => $work]]);
     //$interests=Interest::all(array('short_name'));
     $user_interests = $mecanex_user->interest;
     $term_ids = [];
     foreach ($user_interests as $user_interest) {
         $short_name = $user_interest->short_name;
         array_push($term_ids, $user_interest->id);
         $term = Term::where('term', $short_name)->firstOrFail();
         $mecanex_user->term()->sync([$term->id => ['user_score' => $user_interest->pivot->interest_score / 5]], false);
         //normalization
     }
     $terms = Term::all()->count();
     for ($i = 0; $i <= $terms - 1; $i++) {
         for ($j = $i + 1; $j <= $terms - 1; $j++) {
             $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $mecanex_user->id)->where('term_home_id', $term_ids[$i])->where('term_neighbor_id', $term_ids[$j])->get()->first();
             $temp_user = $mecanex_user->term->find($term_ids[$i]);
             $user_term_score_a = $temp_user->pivot->user_score;
             $temp_user = $mecanex_user->term->find($term_ids[$j]);
             $user_term_score_b = $temp_user->pivot->user_score;
             $new_score = $user_term_score_a * $user_term_score_b;
             $temp_user_matrix->link_score = $new_score;
             $temp_user_matrix->save();
         }
     }
     for ($j = 1; $j <= $terms; $j++) {
         $profile_score = 0;
         for ($i = 1; $i <= $terms; $i++) {
             $temp_user = $mecanex_user->term->find($i);
             $user_term_score = $temp_user->pivot->user_score;
             //get score of user
             if ($i == $j) {
                 $link_score = 0;
             } elseif ($i > $j) {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $mecanex_user->id)->where('term_home_id', $j)->where('term_neighbor_id', $i)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             } else {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $mecanex_user->id)->where('term_home_id', $i)->where('term_neighbor_id', $j)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             }
             $profile_score = $profile_score + $user_term_score * $link_score;
         }
         $mecanex_user->profilescore()->sync([$j => ['profile_score' => $profile_score]], false);
     }
     return Redirect::route('home')->with('message', 'Your interests were updated');
 }
コード例 #7
0
 public function scoreEnrichments()
 {
     set_time_limit(0);
     DB::table('enrichments_terms_scores')->delete();
     $terms = Term::all();
     //take all Profile terms
     $enrichments = Enrichment::all();
     foreach ($enrichments as $enrichment) {
         $id = $enrichment->id;
         foreach ($terms as $term) {
             $results = DB::select(DB::raw('select MATCH (class, longName, description) AGAINST (? WITH QUERY EXPANSION)  as rev from enrichments where id = (?)'), [$term->term, $id]);
             DB::table('enrichments_terms_scores')->insert(['enrichment_id' => $id, 'term_id' => $term->id, 'enrichment_score' => $results[0]->rev]);
         }
     }
     $query = DB::select(DB::raw('UPDATE enrichments_terms_scores as t join (select enrichment_id,MAX(enrichment_score) as maximum FROM enrichments_terms_scores GROUP BY enrichment_id)as max_scores  on  t.enrichment_id=max_scores.enrichment_id  SET t.enrichment_score=t.enrichment_score/max_scores.maximum'));
     $terms = Term::all();
     //take all Profile terms
     $enrichments = Enrichment::all();
     foreach ($enrichments as $enrichment) {
         $id = $enrichment->id;
         foreach ($terms as $term) {
             $results = DB::select(DB::raw('select COUNT(*) as rev from enrichments where id=' . $id . ' and class LIKE "%' . $term->term . '%"'));
             DB::table('enrichments_terms_scores')->where('enrichment_id', $id)->where('term_id', $term->id)->update(['enrichment_score' => DB::raw('enrichment_score*0.5+' . $results[0]->rev * 0.5 . '')]);
         }
     }
     $response = ['message' => 'Successful scoring of enrichments'];
     $statusCode = 200;
     return Response::json($response, $statusCode);
 }
コード例 #8
0
 public function get_send_customer_quote($qr_id)
 {
     $message = Session::get('message');
     $error = Session::get('error');
     $quote_request = QuoteRequest::Find($qr_id);
     $qris = count($quote_request->get_quote) > 0 ? $quote_request->get_quote->qris : [];
     $terms = Term::all();
     return view('quotes.send_customer_quote', compact('quote_request', 'qris', 'message', 'error', 'terms'));
 }
コード例 #9
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function target(Request $request)
 {
     try {
         $mecanexusers = MecanexUser::all();
         // filter by demographics
         if ($request->gender_id != 0) {
             $mecanexusers = $mecanexusers->where("gender_id", (int) $request->gender_id);
         }
         if ($request->age_id != 0) {
             $mecanexusers = $mecanexusers->where("age_id", (int) $request->age_id);
         }
         if ($request->education_id != 0) {
             $mecanexusers = $mecanexusers->where("education_id", (int) $request->education_id);
         }
         if ($request->occupation_id != 0) {
             $mecanexusers = $mecanexusers->where("occupation_id", (int) $request->occupation_id);
         }
         if ($request->country_id != 0) {
             $mecanexusers = $mecanexusers->where("country_id", (int) $request->country_id);
         }
         // filter by preference on terms
         // keep mecanex users whose term profile score is more than 0.7 when normalized by the max term value of the user
         $statusCode = 200;
         if ($request->terms != []) {
             $all_terms = Term::all();
             foreach ($all_terms as $term) {
                 if (strpos($request->terms, $term->term) !== false) {
                     $mecanexusers = $mecanexusers->filter(function ($user) use($term) {
                         $myquery = DB::select(DB::raw(' SELECT MAX(profile_score) as mymax
                                                        FROM users_terms_profilescores
                                                        WHERE mecanex_user_id=' . $user->id . ''));
                         if ($myquery[0]->mymax == 0) {
                             // don't take into account users that have not provided any information
                             return false;
                         }
                         return $user->profilescore[$term->id - 1]['pivot']['profile_score'] / $myquery[0]->mymax > 0.7;
                         // minus one because terms start from 0 where id starts from 1
                     });
                     //                        $response[] = $mecanexusers[1]->profilescore[$term->id-1]['pivot']['profile_score'];
                     //                        $myquery = DB::select(DB::raw(' SELECT MAX(profile_score) as mymax
                     //                                                           FROM users_terms_profilescores
                     //                                                           WHERE mecanex_user_id='. $mecanexusers[2]->id .''));
                 }
             }
         }
         $array_of_users = array();
         // If no mecanexusers exist from the filters selected, we return a random list of videos
         if ($mecanexusers->isEmpty()) {
             $response = [];
             $response['message'][] = "No information for the target group";
             $statusCode = 200;
             return $response;
         }
         foreach ($mecanexusers as $mecanexuser) {
             $array = array();
             $terms = $mecanexuser->profilescore;
             foreach ($terms as $term) {
                 $temp = (double) $term['pivot']['profile_score'];
                 array_push($array, $temp);
             }
             // normalize with maximum because that way the clustering seems more accurate
             $maximum = max($array);
             if ($maximum != 0) {
                 for ($i = 0; $i < count($array); $i++) {
                     $array[$i] = $array[$i] / $maximum;
                 }
             }
             array_push($array_of_users, $array);
         }
         /** return the array of users so that we can see whether the profiles have normalized
          * values so that they can be clustered properly
          */
         $space = new Space(14);
         $num_of_clusters = 5;
         foreach ($array_of_users as $point) {
             $space->addPoint($point);
         }
         $clusters = $space->solve($num_of_clusters);
         $all_users = [];
         //            foreach ($clusters as $i => $cluster)
         //                printf("Cluster %d [%d,%d]: %d points\n", $i, $cluster[0], $cluster[1], count($cluster));
         foreach ($clusters as $i => $cluster) {
             $terms = [];
             for ($j = 0; $j < 14; $j++) {
                 array_push($terms, $cluster[$j]);
             }
             $all_users[] = ['cluster_id' => $i, 'cluster_terms' => $terms, 'num_of_users' => count($cluster)];
         }
         $statusCode = 200;
         $response = $all_users;
         return $response;
     } catch (Exception $e) {
         $statusCode = 400;
     } finally {
         return Response::json($response, $statusCode);
     }
 }
コード例 #10
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(InterestRequest $request)
 {
     $interests = $request->except('username');
     $username = $request->username;
     $user = MecanexUser::where('username', $username)->get()->first();
     if (empty($user)) {
         $response = ["error" => "User doesn`t exist"];
         $statusCode = 404;
     } else {
         $key_values = array();
         foreach ($interests as $key => $value) {
             $interest = Interest::where('short_name', $key)->get(array('id'))->first();
             $user->interest()->sync([$interest->id => ['interest_score' => $value]], false);
             $key_values[$interest->id] = $value;
             $term = Term::where('term', $key)->firstOrFail();
             $value = $value / 5;
             //for normalization
             $user->term()->sync([$term->id => ['user_score' => $value]], false);
         }
         ksort($key_values);
         $term_ids = array_keys($key_values);
         $term_ids_length = count($term_ids);
         //update adjacency matrix
         for ($i = 0; $i <= $term_ids_length - 1; $i++) {
             for ($j = $i + 1; $j < $term_ids_length; $j++) {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $term_ids[$i])->where('term_neighbor_id', $term_ids[$j])->get()->first();
                 $temp_user = $user->term->find($term_ids[$i]);
                 $user_term_score_a = $temp_user->pivot->user_score;
                 $temp_user = $user->term->find($term_ids[$j]);
                 $user_term_score_b = $temp_user->pivot->user_score;
                 $new_score = $user_term_score_a * $user_term_score_b;
                 $temp_user_matrix->link_score = $new_score;
                 $temp_user_matrix->save();
             }
         }
         //update profile
         $terms = Term::all()->count();
         for ($j = 1; $j <= $terms; $j++) {
             $profile_score = 0;
             for ($i = 1; $i <= $terms; $i++) {
                 $temp_user = $user->term->find($i);
                 $user_term_score = $temp_user->pivot->user_score;
                 //get score of user
                 if ($i == $j) {
                     $link_score = 0;
                 } elseif ($i > $j) {
                     $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $j)->where('term_neighbor_id', $i)->get()->first();
                     $link_score = $temp_user_matrix->link_score;
                 } else {
                     $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $i)->where('term_neighbor_id', $j)->get()->first();
                     $link_score = $temp_user_matrix->link_score;
                 }
                 $profile_score = $profile_score + $user_term_score * $link_score;
             }
             $user->profilescore()->sync([$j => ['profile_score' => $profile_score]], false);
         }
         $response = ["message" => "User Interests were saved"];
         $statusCode = 201;
     }
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #11
0
 public function get_seek_announcements(Request $request)
 {
     $field_search = input::get('field');
     $term_search = input::get('term');
     $region_search = input::get('region');
     $municipalities_search = input::get('municipalities');
     if ($field_search == '0' || empty($field_search)) {
         $fields_all = Field::all(['id']);
         foreach ($fields_all as $field) {
             $fields[] = $field->id;
         }
     } else {
         $fields[] = $field_search;
     }
     if ($term_search == '0' || empty($term_search)) {
         $terms_all = Term::all(['id']);
         foreach ($terms_all as $term) {
             $terms[] = $term->id;
         }
     } else {
         $terms[] = $term_search;
     }
     if ($municipalities_search[0] == '0' || empty($municipalities_search)) {
         if ($region_search != '0' && !empty($region_search)) {
             $any_municipality = Region::find($region_search)->get_municipalities()->get();
         } else {
             $any_municipality = Municipality::all(['id']);
         }
         foreach ($any_municipality as $instance) {
             $municipality_id[] = $instance->id;
         }
     } else {
         $municipality_id = $municipalities_search;
     }
     $select = DB::select(' SELECT seek_trainings.id, field_seek_training.field_id, municipality_seek_training.municipality_id
                             FROM seek_trainings
                             JOIN field_seek_training ON seek_trainings.id = field_seek_training.seek_training_id
                             JOIN municipality_seek_training ON seek_trainings.id = municipality_seek_training.seek_training_id
                             WHERE field_seek_training.field_id in(' . implode(',', $fields) . ')
                             AND municipality_seek_training.municipality_id in (' . implode(',', $municipality_id) . ')
                             group by seek_trainings.id
                         ');
     foreach ($select as $instance) {
         $seek_training_filtered = new \stdClass();
         $seek_training_instance = SeekTraining::find($instance->id);
         $seek_training_field = Field::find($instance->field_id);
         $seek_training_municipality = Municipality::find($instance->municipality_id);
         $training_terms = DB::select('SELECT terms.name FROM seek_training_term JOIN terms ON terms.id = seek_training_term.term_id WHERE seek_training_id = ' . $instance->id);
         $seek_training_terms_array = [];
         foreach ($training_terms as $term) {
             $seek_training_terms_array[] = $term->name;
         }
         $seek_training_filtered->id = $seek_training_instance->id;
         $seek_training_filtered->header = $seek_training_instance->name;
         $seek_training_filtered->description = $seek_training_instance->description;
         $seek_training_filtered->file = $seek_training_instance->file;
         $seek_training_filtered->link = $seek_training_instance->link;
         $seek_training_filtered->per = $seek_training_instance->per;
         $seek_training_filtered->terms = implode(',', $seek_training_terms_array);
         $seek_training_filtered->contact = $seek_training_instance->contact;
         $seek_training_filtered->quantity = $seek_training_instance->quantity;
         $seek_training_filtered->field = $seek_training_field->name;
         $seek_training_filtered->municipality = $seek_training_municipality->name;
         $seek_training_filtered->isAdmin = !(!Auth::user() || Auth::user()->role == 100);
         $seek_training_filtered_array[] = $seek_training_filtered;
         unset($seek_training_filtered);
         unset($seek_training_months_array);
         unset($seek_training_terms_array);
     }
     return response(json_encode($seek_training_filtered_array), 200)->header('Content-Type', 'application/json');
 }
コード例 #12
0
 public function callback(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
 {
     //		$token = $fb->getAccessTokenFromRedirect();
     //		dd($token);
     // Obtain an access token.
     try {
         $token = $fb->getAccessTokenFromRedirect();
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     // Access token will be null if the user denied the request
     // or if someone just hit this URL outside of the OAuth flow.
     if (!$token) {
         // Get the redirect helper
         $helper = $fb->getRedirectLoginHelper();
         if (!$helper->getError()) {
             abort(403, 'Unauthorized action.');
         }
         // User denied the request
         //				echo '<p>Error: ' . $helper->getError();
         //				echo '<p>Code: ' . $helper->getErrorCode();
         //				echo '<p>Reason: ' . $helper->getErrorReason();
         //				echo '<p>Description: ' . $helper->getErrorDescription();
         //				exit ;
         dd($helper->getError(), $helper->getErrorCode(), $helper->getErrorReason(), $helper->getErrorDescription());
     }
     $fb->setDefaultAccessToken($token);
     if (!$token->isLongLived()) {
         // OAuth 2.0 client handler
         $oauth_client = $fb->getOAuth2Client();
         // Extend the access token.
         try {
             $token = $oauth_client->getLongLivedAccessToken($token);
         } catch (Facebook\Exceptions\FacebookSDKException $e) {
             dd($e->getMessage());
         }
     }
     //this is for not include $token in the get calls
     $fb->setDefaultAccessToken($token);
     // Get basic info on the user from Facebook.
     try {
         $response = $fb->get('/me?fields=id,email');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     try {
         $profileresponse = $fb->get('/me?fields=id,name,gender');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     // Convert the response to a `Facebook/GraphNodes/GraphUser` collection
     $facebook_user = $response->getGraphUser();
     $mecanex_user = $profileresponse->getGraphUser();
     $existing_mecanex_user = MecanexUser::where('facebook_user_id', '=', $facebook_user["id"])->get()->first();
     $existing_user = User::where('facebook_user_id', '=', $facebook_user["id"])->get()->first();
     // Create the user if it does not exist or update the existing entry.
     // This will only work if you've added the SyncableGraphNodeTrait to your User model.
     if ($existing_user == null) {
         $facebook_user["username"] = "******" . $facebook_user["id"];
     } else {
         $facebook_user["username"] = $existing_user->username;
     }
     $user = User::createOrUpdateGraphNode($facebook_user);
     //store profile data in mecanex_users table
     $id = $user->id;
     $facebook_id = $user->facebook_user_id;
     if ($existing_mecanex_user == null) {
         $username = "******" . $user->facebook_user_id;
     } else {
         $username = $existing_mecanex_user->username;
     }
     $email = $user->email;
     $fullname = $mecanex_user->getName();
     $fullname = explode(" ", $fullname);
     $name = $fullname[0];
     $surname = $fullname[1];
     $gender = $mecanex_user->getGender();
     if ($gender == 'female') {
         $gender_id = 2;
     } else {
         $gender_id = 1;
     }
     $fbuser = MecanexUser::firstOrNew(array('facebook_user_id' => $facebook_id));
     $fbuser->username = $username;
     $fbuser->user_id = $id;
     $fbuser->facebook_user_id = $facebook_id;
     $fbuser->gender_id = $gender_id;
     $fbuser->name = $name;
     $fbuser->surname = $surname;
     $fbuser->email = $email;
     $fbuser->save();
     // Log the user into Laravel
     Auth::login($user);
     if ($existing_mecanex_user == null) {
         // create records in table users_terms-scores once a mecanex user has been created
         $terms = Term::all();
         $total_terms = count($terms);
         foreach ($terms as $term) {
             $fbuser->term()->sync([$term->id => ['user_score' => 0]], false);
             $fbuser->profilescore()->sync([$term->id => ['profile_score' => 0]], false);
         }
         for ($i = 1; $i <= $total_terms; $i++) {
             for ($j = $i + 1; $j <= $total_terms; $j++) {
                 $mec_matrix = new MecanexUserTermHomeTermNeighbour();
                 $mec_matrix->mecanex_user_id = $fbuser->id;
                 $mec_matrix->term_home_id = $i;
                 $mec_matrix->term_neighbor_id = $j;
                 $mec_matrix->link_score = 0.05;
                 $mec_matrix->save();
             }
         }
     }
     return redirect('/home')->with('message', 'Successfully logged in with Facebook');
 }
コード例 #13
0
 private function content_similarity($user_id, $video_ids)
 {
     $temp_profile_scores = [];
     // if there is no video list, search all videos, else only those on the list
     if (count($video_ids) == 0) {
         $videos = Video::all();
     } else {
         //            $videos = Video::whereRaw('video_id  IN (' . $video_ids . ')')->get();
         $tmpArray = explode(',', $video_ids);
         $func = function ($string) {
             return substr($string, 1, -1);
         };
         $myArray = array_map($func, $tmpArray);
         $videos = DB::table('videos')->whereIn('video_id', $myArray)->get();
     }
     //keep all terms of the user in a list
     $terms = Term::all();
     $user = MecanexUser::where('id', $user_id)->get()->first();
     $user_terms_scores = $user->profilescore;
     foreach ($user_terms_scores as $user_term_score) {
         $temp_profile_scores[] = $user_term_score->pivot->profile_score;
     }
     foreach ($videos as $video) {
         $arithmitis = 0;
         $sumA = 0;
         $sumB = 0;
         $temp_video_scores = [];
         //keep all terms of video in a list
         $video_terms_scores = DB::select(DB::raw('SELECT * FROM videos_terms_scores WHERE video_id=? ORDER BY term_id'), [$video->id]);
         foreach ($video_terms_scores as $video_term_score) {
             $temp_video_scores[] = $video_term_score->video_score;
         }
         // calculate the similarity
         for ($i = 0; $i < count($terms); $i++) {
             $arithmitis = $arithmitis + $temp_video_scores[$i] * $temp_profile_scores[$i];
             $sumA = $sumA + pow($temp_video_scores[$i], 2);
             $sumB = $sumB + pow($temp_profile_scores[$i], 2);
         }
         $videoScores[$video->id] = $arithmitis / (sqrt($sumA) + sqrt($sumB));
     }
     return $videoScores;
 }
コード例 #14
0
 private function content_similarity($user_id, $limit)
 {
     $result = [];
     $videos = Video::all();
     $terms = Term::all();
     $user = MecanexUser::where('id', $user_id)->get()->first();
     $user_terms_scores = $user->profilescore;
     foreach ($user_terms_scores as $user_term_score) {
         $temp_profile_scores[] = $user_term_score->pivot->profile_score;
     }
     foreach ($videos as $video) {
         $arithmitis = 0;
         $sumA = 0;
         $sumB = 0;
         $temp_video_scores = [];
         $video_terms_scores = DB::select(DB::raw('SELECT * FROM videos_terms_scores WHERE video_id=? ORDER BY term_id'), [$video->id]);
         foreach ($video_terms_scores as $video_term_score) {
             $temp_video_scores[] = $video_term_score->video_score;
         }
         for ($i = 0; $i < count($terms); $i++) {
             $arithmitis = $arithmitis + $temp_video_scores[$i] * $temp_profile_scores[$i];
             $sumA = $sumA + pow($temp_video_scores[$i], 2);
             $sumB = $sumB + pow($temp_profile_scores[$i], 2);
         }
         $videoScores[$video->id] = $arithmitis / (sqrt($sumA) + sqrt($sumB));
     }
     arsort($videoScores);
     $videoScores = array_slice($videoScores, 0, $limit, true);
     foreach ($videoScores as $key => $score) {
         $video = $videos->find($key);
         $result[] = array('video_id' => $video->id, 'title' => $video->title, 'similarity' => $score, 'euscreen_id' => $video->video_id);
     }
     return $result;
 }
コード例 #15
0
 /**
  * Return clusterheads and corresponding videos for filtered users.
  *
  * @return Clusterheads and videos
  */
 public function professional(Request $request)
 {
     try {
         $mecanexusers = MecanexUser::all();
         // filter by demographics
         if ($request->gender_id != 0) {
             $mecanexusers = $mecanexusers->where("gender_id", (int) $request->gender_id);
         }
         if ($request->age_id != 0) {
             $mecanexusers = $mecanexusers->where("age_id", (int) $request->age_id);
         }
         if ($request->education_id != 0) {
             $mecanexusers = $mecanexusers->where("education_id", (int) $request->education_id);
         }
         if ($request->occupation_id != 0) {
             $mecanexusers = $mecanexusers->where("occupation_id", (int) $request->occupation_id);
         }
         if ($request->country_id != 0) {
             $mecanexusers = $mecanexusers->where("country_id", (int) $request->country_id);
         }
         if ($request->num != 0) {
             $num = $request->num;
         } else {
             $num = 50;
         }
         // filter by preference on terms
         // keep mecanex users whose term profile score is more than 0.7 when normalized by the max term value of the user
         if ($request->terms != []) {
             $all_terms = Term::all();
             foreach ($all_terms as $term) {
                 if (strpos($request->terms, $term->term) !== false) {
                     $mecanexusers = $mecanexusers->filter(function ($user) use($term) {
                         $myquery = DB::select(DB::raw(' SELECT MAX(profile_score) as mymax
                                                        FROM users_terms_profilescores
                                                        WHERE mecanex_user_id=' . $user->id . ''));
                         if ($myquery[0]->mymax == 0) {
                             // don't take into account users that have not provided any information
                             return false;
                         }
                         return $user->profilescore[$term->id - 1]['pivot']['profile_score'] / $myquery[0]->mymax > 0.7;
                         // minus one because terms start from 0 where id starts from 1
                     });
                     //                        $response[] = $mecanexusers[1]->profilescore[$term->id-1]['pivot']['profile_score'];
                     //                        $myquery = DB::select(DB::raw(' SELECT MAX(profile_score) as mymax
                     //                                                           FROM users_terms_profilescores
                     //                                                           WHERE mecanex_user_id='. $mecanexusers[2]->id .''));
                 }
             }
         }
         $array_of_users = array();
         // If no mecanexusers exist from the filters selected, we return a random list of videos
         if ($mecanexusers->isEmpty()) {
             if ($request->videos == null) {
                 $videos = Video::orderByRaw('RAND()')->take($num)->get();
             } else {
                 $reqvideos = "'" . str_replace(",", "','", $request->videos) . "'";
                 //                    $videos = Video::where('video_id','in',['EUS_025A722EA4B240D8B6F6330A8783143C'])->orderByRaw('RAND()')->take($num)->get();
                 $videos = DB::select(DB::raw(' SELECT *
                                         FROM videos
                                         WHERE video_id IN (' . $reqvideos . ') ORDER BY RAND()  LIMIT ' . $num . ''));
             }
             $response = [];
             foreach ($videos as $video) {
                 $response['videos'][] = $video->video_id;
             }
             $statusCode = 200;
             return $response;
         }
         foreach ($mecanexusers as $mecanexuser) {
             $array = array();
             $terms = $mecanexuser->profilescore;
             foreach ($terms as $term) {
                 $temp = (double) $term['pivot']['profile_score'];
                 array_push($array, $temp);
             }
             array_push($array_of_users, $array);
         }
         /** return the array of users so that we can see whether the profiles have normalized
          * values so that they can be clustered properly
          */
         //            return $array_of_users;
         $space = new Space(14);
         $num_of_clusters = 5;
         foreach ($array_of_users as $point) {
             $space->addPoint($point);
         }
         $clusters = $space->solve($num_of_clusters);
         $statusCode = 200;
         $all_users = [];
         //            foreach ($clusters as $i => $cluster)
         //                printf("Cluster %d [%d,%d]: %d points\n", $i, $cluster[0], $cluster[1], count($cluster));
         foreach ($clusters as $i => $cluster) {
             $terms = [];
             for ($j = 0; $j < 14; $j++) {
                 array_push($terms, $cluster[$j]);
             }
             $all_users[] = ['cluster_id' => $i, 'cluster_terms' => $terms, 'num_of_users' => count($cluster)];
         }
         $cluster_list = [];
         foreach ($all_users as $user) {
             $cluster_list[] = ['cluster_id' => $user['cluster_id'], 'video_ids' => $this->recommend_video($user['cluster_terms'], $request), 'cluster_terms' => $user['cluster_terms'], 'num_of_users' => $user['num_of_users']];
         }
         //            $response = $cluster_list[0]['video_ids'][0]->id;
         $video_list = [];
         $response = [];
         $num_of_videos = 0;
         $total_num_of_videos = count($cluster_list[0]['video_ids']);
         for ($i = 0; $i < $total_num_of_videos; $i++) {
             for ($j = 0; $j < $num_of_clusters; $j++) {
                 $video = $cluster_list[$j]['video_ids'][$i];
                 if (!in_array($video->video_id, $video_list, true)) {
                     $video_list[] = $video->video_id;
                     $response['videos'][] = $video->euscreen_id;
                     $num_of_videos += 1;
                 }
                 if ($num_of_videos == $total_num_of_videos) {
                     break;
                 }
             }
             if ($num_of_videos == $total_num_of_videos) {
                 break;
             }
         }
         return $response;
     } catch (Exception $e) {
         $statusCode = 400;
     } finally {
         return Response::json($response, $statusCode);
     }
 }
コード例 #16
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function login(Request $request, SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
 {
     //test if token for FB login is enough
     $token = $request->token;
     //	return $token;
     // does not work since $token is string but should be token
     //		if (! $token->isLongLived()) {
     //			// OAuth 2.0 client handler
     //			$oauth_client = $fb->getOAuth2Client();
     //
     //			// Extend the access token.
     //			try {
     //				$token = $oauth_client->getLongLivedAccessToken($token);
     //			} catch (Facebook\Exceptions\FacebookSDKException $e) {
     //				dd($e->getMessage());
     //			}
     //		}
     //this is for not include $token in the get calls
     $fb->setDefaultAccessToken($token);
     // Get basic info on the user from Facebook.
     try {
         $response = $fb->get('/me?fields=id,email');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     try {
         $profileresponse = $fb->get('/me?fields=id,name,gender');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     // Convert the response to a `Facebook/GraphNodes/GraphUser` collection
     $facebook_user = $response->getGraphUser();
     $mecanex_user = $profileresponse->getGraphUser();
     // Create the user if it does not exist or update the existing entry.
     // This will only work if you've added the SyncableGraphNodeTrait to your User model.
     $user = User::createOrUpdateGraphNode($facebook_user);
     //store profile data in mecanex_users table
     $id = $user->id;
     $facebook_id = $user->facebook_user_id;
     $fullname = $mecanex_user->getName();
     $fullname = explode(" ", $fullname);
     $name = $fullname[0];
     $surname = $fullname[1];
     $gender = $mecanex_user->getGender();
     if ($gender == 'female') {
         $gender_id = 2;
     } else {
         $gender_id = 1;
     }
     $fbuser = MecanexUser::firstOrNew(array('facebook_user_id' => $facebook_id));
     $fbuser->user_id = $id;
     $fbuser->facebook_user_id = $facebook_id;
     $fbuser->gender_id = $gender_id;
     $fbuser->name = $name;
     $fbuser->surname = $surname;
     $fbuser->save();
     // Log the user into Laravel
     Auth::login($user);
     // create records in table users_terms-scores once a mecanex user has been created
     $terms = Term::all();
     foreach ($terms as $term) {
         $fbuser->term()->sync([$term->id => ['user_score' => 0]], false);
     }
     $response = 'User was saved';
     $statusCode = 201;
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #17
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function login(Request $request, SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
 {
     //test if token for FB login is enough
     $token = $request->token;
     //			return $token;
     // does not work since $token is string but should be token
     //		if (! $token->isLongLived()) {
     //			// OAuth 2.0 client handler
     //			$oauth_client = $fb->getOAuth2Client();
     //
     //			// Extend the access token.
     //			try {
     //				$token = $oauth_client->getLongLivedAccessToken($token);
     //			} catch (Facebook\Exceptions\FacebookSDKException $e) {
     //				dd($e->getMessage());
     //			}
     //		}
     //this is for not include $token in the get calls
     $fb->setDefaultAccessToken($token);
     // Get basic info on the user from Facebook.
     try {
         $response = $fb->get('/me?fields=id,email');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     try {
         $profileresponse = $fb->get('/me?fields=id,name,gender');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     // Convert the response to a `Facebook/GraphNodes/GraphUser` collection
     $facebook_user = $response->getGraphUser();
     $mecanex_user = $profileresponse->getGraphUser();
     $existing_mecanex_user = MecanexUser::where('email', '=', $facebook_user["email"])->get()->first();
     $existing_user = User::where('email', '=', $facebook_user["email"])->get()->first();
     // Create the user if it does not exist or update the existing entry.
     // This will only work if you've added the SyncableGraphNodeTrait to your User model.
     if ($existing_user == null) {
         $facebook_user["username"] = "******" . $facebook_user["id"];
         $user = User::createOrUpdateGraphNode($facebook_user);
     } else {
         $facebook_user["username"] = $existing_user->username;
         $user = $existing_user;
         $user->facebook_user_id = $facebook_user["id"];
         $user->save();
     }
     //store profile data in mecanex_users table
     $id = $user->id;
     $facebook_id = $user->facebook_user_id;
     if ($existing_mecanex_user == null) {
         $username = "******" . $user->facebook_user_id;
     } else {
         $username = $existing_mecanex_user->username;
     }
     $email = $user->email;
     $fullname = $mecanex_user->getName();
     $fullname = explode(" ", $fullname);
     $name = $fullname[0];
     $surname = $fullname[1];
     $gender = $mecanex_user->getGender();
     if ($gender == 'female') {
         $gender_id = 2;
     } else {
         $gender_id = 1;
     }
     $fbuser = MecanexUser::firstOrNew(array('email' => $email));
     $fbuser->username = $username;
     $fbuser->user_id = $id;
     $fbuser->facebook_user_id = $facebook_id;
     $fbuser->gender_id = $gender_id;
     $fbuser->name = $name;
     $fbuser->surname = $surname;
     $fbuser->email = $email;
     $fbuser->save();
     // Log the user into Laravel
     Auth::login($user);
     // create records in table users_terms-scores once a mecanex user has been created
     if ($existing_mecanex_user == null) {
         $terms = Term::all();
         $total_terms = count($terms);
         foreach ($terms as $term) {
             $fbuser->term()->sync([$term->id => ['user_score' => 0]], false);
             $fbuser->profilescore()->sync([$term->id => ['profile_score' => 0]], false);
         }
         for ($i = 1; $i <= $total_terms; $i++) {
             for ($j = $i + 1; $j <= $total_terms; $j++) {
                 $mec_matrix = new MecanexUserTermHomeTermNeighbour();
                 $mec_matrix->mecanex_user_id = $fbuser->id;
                 $mec_matrix->term_home_id = $i;
                 $mec_matrix->term_neighbor_id = $j;
                 $mec_matrix->link_score = 0.05;
                 $mec_matrix->save();
             }
         }
     }
     $response = ['username' => $username, 'message' => 'User was successfully logged in'];
     $statusCode = 201;
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #18
0
 public function explicitrf_function(SignalsRequest $request)
 {
     $username = $request->username;
     $device = $request->device_id;
     $video_id = $request->video_id;
     $action_type = $request->action;
     $explicit_rf = $request->value;
     //check if $request->score==-1 or 0 or 1
     $record_exists = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_type)->first();
     if (empty($record_exists)) {
         $user_action = new UserAction(['username' => $username, 'device_id' => $device, 'video_id' => $video_id, 'explicit_rf' => $explicit_rf, 'action' => $action_type]);
         $user_action->save();
         $get_importance = Action::where('id', $request->action)->first();
         $importance = $get_importance->importance;
         $user_action->update(array('weight' => $explicit_rf, 'importance' => $importance));
     } else {
         $record_exists->update(array('explicit_rf' => $explicit_rf, 'weight' => $explicit_rf));
     }
     //store in the dcgs table - only used for the online experiments
     $mecanex_user = MecanexUser::where('username', $username)->first();
     $dcg_record = Dcg::where('mecanex_user_id', $mecanex_user->id)->where('video_id', $video_id);
     $dcg_record->update(array('explicit_rf' => $explicit_rf));
     //////////////calculate ku///////////////////////
     // number of all enrichments
     $video = Video::where('video_id', $video_id)->first();
     $num_all_enrichments = DB::select(DB::raw('SELECT COUNT(*) as num FROM enrichments_videos_time WHERE video_id=?'), [$video->id]);
     $num_all_enrichments = $num_all_enrichments[0]->num;
     // create list with clicked enrichments
     $get_action_id = Action::where('action', 'click enrichment')->first();
     $action_id = $get_action_id->id;
     $enrichment_click_ids = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->get(array('content_id'));
     $num_clicked_enrichments = count($enrichment_click_ids);
     // replace all database entries with one with the appropriate weight (so that the calculation can be easily done).
     // The information for what enrichments where clicked is now in the $enrichment_click_ids variable
     if ($num_clicked_enrichments != 0) {
         DB::table('user_actions')->where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->delete();
         $user_action = new UserAction(['username' => $username, 'device_id' => $device, 'video_id' => $video_id, 'action' => $action_id, 'content_id' => '1']);
         $user_action->save();
         $get_importance = Action::where('id', $action_id)->first();
         $importance = $get_importance->importance;
         $user_action->update(array('weight' => $num_clicked_enrichments / $num_all_enrichments, 'importance' => $importance));
     }
     // create list with shared enrichments
     $get_action_id = Action::where('action', 'share')->first();
     $action_id = $get_action_id->id;
     $enrichment_share_ids = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->get(array('content_id'));
     $num_shared_enrichments = count($enrichment_share_ids);
     // replace all database entries with one with the appropriate weight (so that the calculation can be easily done).
     // The information for what enrichments where clicked is now in the $enrichment_shared_ids variable
     if ($num_shared_enrichments != 0) {
         DB::table('user_actions')->where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->delete();
         $user_action = new UserAction(['username' => $username, 'device_id' => $device, 'video_id' => $video_id, 'action' => $action_id, 'content_id' => '1']);
         $user_action->save();
         $get_importance = Action::where('id', $action_id)->first();
         $importance = $get_importance->importance;
         $user_action->update(array('weight' => $num_shared_enrichments / $num_all_enrichments, 'importance' => $importance));
     }
     $k_nominator = UserAction::where('username', $username)->where('video_id', $video_id)->groupBy('username')->get(['username', DB::raw('SUM(importance*weight) as total_score')])->first();
     $query = "SELECT SUM(t1.importance ) AS total FROM (SELECT DISTINCT action, importance FROM user_actions WHERE username=:username AND video_id=:videoid) AS t1 ";
     $k_denominator = DB::select(DB::raw($query), array('username' => $username, 'videoid' => $video_id));
     //returns array
     $k = $k_nominator->total_score / $k_denominator[0]->total;
     //to [0] gia na prospelasei to 1o stoixeio tou array pou einai to object
     /////////////////////////////update weights and update profile//////////////////////////////////////////////////////////
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     /////////////Retrieve Terms/////////////////////////////
     //////////////retrieve terms for given video//////////////
     $video = Video::where('video_id', $request->video_id)->first();
     $threshold = 0;
     //need to appropriate set
     $results = $video->term()->where('video_score', '>', $threshold)->get(array('term_id'));
     $video_term_list = [];
     foreach ($results as $result) {
         //retrieve the terms that will be updated
         array_push($video_term_list, $result->term_id);
     }
     sort($video_term_list);
     ///////////retrieve terms for the clicked enrichments//////////////
     //		$get_actionid = Action::where('action', 'click enrichment')->first();
     //		$action_id = $get_actionid->id;
     //		$enrichment_ids = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->get(array('content_id'));
     $enrichment_term_list = [];
     //		foreach ($enrichment_ids as $enrichment_id)
     //		{
     //
     //			//call the api and get some terms
     //			//or emulate enrichment_terms
     //			//$results=Enrichment::where('id',$enrichment_id)->get(array('term_id'))
     //			foreach($results as $result)
     //			{
     //				array_push($enrichment_term_list,$result->term_id);
     //			}
     //
     //		}
     //$enrichment_terms=array_unique($enrichment_term_list);
     $enrichment_terms = [3, 4, 7];
     //retrieve terms for the clicked ads
     $ads_terms = [4, 8, 10];
     ///Final term_list -  no need since I will update in three steps
     //		$term_list=array_merge($video_term_list,$enrichment_terms,$ads_terms);
     //		$terms=array_unique($term_list);
     ////////////////update weights of profile//////////////////////////
     $term_scores = [];
     //save all scores to get the max
     $user = MecanexUser::where('username', $username)->get()->first();
     $video = Video::where('video_id', $video_id)->get()->first();
     $link_user = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->get()->first();
     //return $video;
     //return $link_user;
     //update based on video_terms
     //return $video_term_list;
     foreach ($video_term_list as $video_term_id) {
         $temp_user = $user->term->find($video_term_id);
         $user_term_score = $temp_user->pivot->user_score;
         //get score of user
         $temp_video = $video->term->find($video_term_id);
         $video_term_score = $temp_video->pivot->video_score;
         //get score of video
         $final_score = $k * (0.8 * $video_term_score);
         foreach ($enrichment_click_ids as $enrichment_click_id) {
             $id = $enrichment_click_id->content_id;
             $enrichment = Enrichment::where('enrichment_id', $id)->get()->first();
             $temp_enrichment = $enrichment->term->find($video_term_id);
             $enrichment_term_score = $temp_enrichment->pivot->enrichment_score;
             $final_score = $final_score + $k * (0.1 / $num_clicked_enrichments * $enrichment_term_score);
         }
         foreach ($enrichment_share_ids as $enrichment_share_id) {
             $id = $enrichment_share_id->content_id;
             $enrichment = Enrichment::where('enrichment_id', $id)->get()->first();
             $temp_enrichment = $enrichment->term->find($video_term_id);
             $enrichment_term_score = $temp_enrichment->pivot->enrichment_score;
             $final_score = $final_score + $k * (0.1 / $num_shared_enrichments * $enrichment_term_score);
         }
         //update score
         $new_score = $user_term_score + $final_score;
         //ok
         $new_score = max($new_score, 0);
         // don't let negative values
         array_push($term_scores, $new_score);
         //				//store score
         $user->term()->sync([$video_term_id => ['user_score' => $new_score]], false);
     }
     //return $term_scores;
     // update matrix
     $number_video_terms = count($video_term_list);
     $link_term_scores = [];
     //save all scores to get the max
     for ($i = 0; $i <= $number_video_terms - 1; $i++) {
         for ($j = $i + 1; $j < $number_video_terms; $j++) {
             $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $video_term_list[$i])->where('term_neighbor_id', $video_term_list[$j])->get()->first();
             //return $temp_user_matrix;
             $temp_video = $video->term->find($video_term_list[$i]);
             $video_term_score1 = $temp_video->pivot->video_score;
             $temp_video = $video->term->find($video_term_list[$j]);
             $video_term_score2 = $temp_video->pivot->video_score;
             $final_score = $k * (0.8 * $video_term_score1 * $video_term_score2);
             foreach ($enrichment_click_ids as $enrichment_click_id) {
                 $id = $enrichment_click_id->content_id;
                 $enrichment = Enrichment::where('enrichment_id', $id)->get()->first();
                 $temp_enrichment = $enrichment->term->find($video_term_list[$i]);
                 $enrichment_term_score1 = $temp_enrichment->pivot->enrichment_score;
                 $temp_enrichment = $enrichment->term->find($video_term_list[$j]);
                 $enrichment_term_score2 = $temp_enrichment->pivot->enrichment_score;
                 $final_score = $final_score + $k * (0.1 / $num_clicked_enrichments * $enrichment_term_score1 * $enrichment_term_score2);
             }
             foreach ($enrichment_share_ids as $enrichment_share_id) {
                 $id = $enrichment_share_id->content_id;
                 $enrichment = Enrichment::where('enrichment_id', $id)->get()->first();
                 $temp_enrichment = $enrichment->term->find($video_term_list[$i]);
                 $enrichment_term_score1 = $temp_enrichment->pivot->enrichment_score;
                 $temp_enrichment = $enrichment->term->find($video_term_list[$j]);
                 $enrichment_term_score2 = $temp_enrichment->pivot->enrichment_score;
                 $final_score = $final_score + $k * (0.1 / $num_shared_enrichments * $enrichment_term_score1 * $enrichment_term_score2);
             }
             $new_score = $temp_user_matrix->link_score + $final_score;
             $new_score = max($new_score, 0);
             // don't let negative values
             array_push($link_term_scores, $new_score);
             $temp_user_matrix->link_score = $new_score;
             $temp_user_matrix->save();
         }
     }
     //same should be done for enrichments and ads
     //find max value and divide term values
     $max_term_value = max(max($term_scores), 1);
     if ($link_term_scores != []) {
         $max_link_term_value = max(max($link_term_scores), 1);
     }
     foreach ($video_term_list as $video_term_id) {
         $temp_user = $user->term->find($video_term_id);
         $user_term_score = $temp_user->pivot->user_score;
         //get score of user
         $temp_video = $video->term->find($video_term_id);
         $video_term_score = $temp_video->pivot->video_score;
         //get score of video
         //update score
         $new_score = $user_term_score / $max_term_value;
         //ok
         //store score
         $user->term()->sync([$video_term_id => ['user_score' => $new_score]], false);
     }
     for ($i = 0; $i <= $number_video_terms - 1; $i++) {
         for ($j = $i + 1; $j < $number_video_terms; $j++) {
             $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $video_term_list[$i])->where('term_neighbor_id', $video_term_list[$j])->get()->first();
             $old_score = $temp_user_matrix->link_score;
             $new_score = $old_score / $max_link_term_value;
             $temp_user_matrix->link_score = $new_score;
             $temp_user_matrix->save();
         }
     }
     //calculate profile
     $terms = Term::all()->count();
     for ($j = 1; $j <= $terms; $j++) {
         $profile_score = 0;
         for ($i = 1; $i <= $terms; $i++) {
             $temp_user = $user->term->find($i);
             $user_term_score = $temp_user->pivot->user_score;
             //get score of user
             if ($i == $j) {
                 $link_score = 0;
             } elseif ($i > $j) {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $j)->where('term_neighbor_id', $i)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             } else {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $i)->where('term_neighbor_id', $j)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             }
             $profile_score = $profile_score + $user_term_score * $link_score;
         }
         $user->profilescore()->sync([$j => ['profile_score' => $profile_score]], false);
     }
     DB::table('user_actions')->where('username', $username)->where('video_id', $video_id)->delete();
     $response = ["message" => 'RF Saved'];
     $statusCode = 200;
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #19
0
 private function recommend_enr($list, $user_id)
 {
     $terms = Term::all();
     $user = MecanexUser::where('id', $user_id)->get()->first();
     $user_terms_scores = $user->profilescore;
     foreach ($user_terms_scores as $user_term_score) {
         $temp_profile_scores[] = $user_term_score->pivot->profile_score;
     }
     foreach ($list as $enrichment) {
         $arithmitis = 0;
         $sumA = 0;
         $sumB = 0;
         $temp_enrichment_scores = [];
         $enrichment_terms_scores = DB::select(DB::raw('SELECT * FROM enrichments_terms_scores WHERE enrichment_id=? ORDER BY term_id'), [$enrichment["enrichment_id"]]);
         foreach ($enrichment_terms_scores as $enrichment_term_score) {
             $temp_enrichment_scores[] = $enrichment_term_score->enrichment_score;
         }
         for ($i = 0; $i < count($terms); $i++) {
             $arithmitis = $arithmitis + $temp_enrichment_scores[$i] * $temp_profile_scores[$i];
             $sumA = $sumA + pow($temp_enrichment_scores[$i], 2);
             $sumB = $sumB + pow($temp_profile_scores[$i], 2);
         }
         $enrichment["score"] = $arithmitis / (sqrt($sumA) + sqrt($sumB));
         $enrichmentScores[$enrichment["enrichment_id"]] = $arithmitis / (sqrt($sumA) + sqrt($sumB));
     }
     arsort($enrichmentScores);
     return $enrichmentScores;
     //		// first key of enrichmentScores list - the most recommended enrichment
     //		$recommended_enrichment = key($enrichmentScores);
     //
     //		return Enrichment::find($recommended_enrichment)->enrichment_id;
 }
コード例 #20
0
ファイル: VideoController.php プロジェクト: skafetzo/SPtool
 public function rf(Request $request)
 {
     $user = Auth::user();
     $username = $user->username;
     $device = "1";
     $video_id = $request->video_id;
     $action_type = 6;
     $explicit_rf = $request->score;
     //check if $request->score==-1 or 0 or 1
     $record_exists = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_type)->first();
     if (empty($record_exists)) {
         $user_action = new UserAction(['username' => $username, 'device_id' => '1', 'video_id' => $video_id, 'explicit_rf' => $explicit_rf, 'action' => $action_type]);
         $user_action->save();
         $get_importance = Action::where('id', $action_type)->first();
         $importance = $get_importance->importance;
         $user_action->update(array('weight' => 1, 'importance' => $importance));
         return $record_exists;
     } else {
         $record_exists->update(array('explicit_rf' => $explicit_rf));
     }
     //store in the dcgs table - only used for the online experiments
     $mecanex_user = MecanexUser::where('username', $username)->first();
     $dcg_record = Dcg::where('mecanex_user_id', $mecanex_user->id)->where('video_id', $video_id);
     $dcg_record->update(array('explicit_rf' => $explicit_rf));
     //////////////calculate ku///////////////////////
     $k_nominator = UserAction::where('username', $username)->where('video_id', $video_id)->groupBy('username')->get(['username', DB::raw('SUM(importance*weight) as total_score')])->first();
     //prepei edw na to diairw k me to plithos twn sunolikwn enrichments k ads
     $query = "SELECT SUM(t1.importance ) AS total FROM (SELECT DISTINCT action, importance FROM user_actions WHERE username=:username AND video_id=:videoid) AS t1 ";
     $k_denominator = DB::select(DB::raw($query), array('username' => $username, 'videoid' => $video_id));
     //returns array
     $k = $k_nominator->total_score / $k_denominator[0]->total;
     //to [0] gia na prospelasei to 1o stoixeio tou array pou einai to object
     /////////////////////////////update weights and update profile//////////////////////////////////////////////////////////
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     /////////////Retrieve Terms/////////////////////////////
     //////////////retrieve terms for given video//////////////
     $video = Video::where('video_id', $video_id)->first();
     $threshold = 0.1;
     //need to appropriate set
     $results = $video->term()->where('video_score', '>', $threshold)->distinct()->get(array('term_id'));
     //$results = $results->unique();
     //return $results;
     $video_term_list = [];
     foreach ($results as $result) {
         //retrieve the terms that will be updated
         array_push($video_term_list, $result->term_id);
     }
     sort($video_term_list);
     //return $video_term_list;
     ///////////retrieve terms for the clicked enrichments//////////////
     $get_actionid = Action::where('action', 'click enrichment')->first();
     $action_id = $get_actionid->id;
     $enrichment_ids = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->get(array('content_id'));
     $enrichment_term_list = [];
     //		foreach ($enrichment_ids as $enrichment_id)
     //		{
     //
     //			//call the api and get some terms
     //			//or emulate enrichment_terms
     //			//$results=Enrichment::where('id',$enrichment_id)->get(array('term_id'))
     //			foreach($results as $result)
     //			{
     //				array_push($enrichment_term_list,$result->term_id);
     //			}
     //
     //		}
     //$enrichment_terms=array_unique($enrichment_term_list);
     //		$enrichment_terms = [3, 4, 7];
     //retrieve terms for the clicked ads
     //		$ads_terms = [4, 8, 10];
     ///Final term_list -  no need since I will update in three steps
     //		$term_list=array_merge($video_term_list,$enrichment_terms,$ads_terms);
     //		$terms=array_unique($term_list);
     ////////////////update weights of profile//////////////////////////
     $term_scores = [];
     //save all scores to get the max
     $user = MecanexUser::where('username', $username)->get()->first();
     $video = Video::where('video_id', $video_id)->get()->first();
     $link_user = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->get()->first();
     //return $link_user;
     //update based on video_terms
     foreach ($video_term_list as $video_term_id) {
         $temp_user = $user->term->find($video_term_id);
         $user_term_score = $temp_user->pivot->user_score;
         //get score of user
         $temp_video = $video->term->find($video_term_id);
         $video_term_score = $temp_video->pivot->video_score;
         //get score of video
         //update score
         $new_score = $user_term_score + $k * (0.8 * $video_term_score);
         //ok
         array_push($term_scores, $new_score);
         //				//store score
         $user->term()->sync([$video_term_id => ['user_score' => $new_score]], false);
     }
     // update matrix
     $number_video_terms = count($video_term_list);
     $link_term_scores = [];
     //save all scores to get the max
     for ($i = 0; $i <= $number_video_terms - 1; $i++) {
         for ($j = $i + 1; $j < $number_video_terms; $j++) {
             $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $video_term_list[$i])->where('term_neighbor_id', $video_term_list[$j])->get()->first();
             //return $temp_user_matrix;
             $temp_video = $video->term->find($video_term_list[$i]);
             $video_term_score1 = $temp_video->pivot->video_score;
             $temp_video = $video->term->find($video_term_list[$j]);
             $video_term_score2 = $temp_video->pivot->video_score;
             //return $temp_user_matrix;
             $new_score = $temp_user_matrix->link_score + $k * (0.8 * ($video_term_score1 * $video_term_score2));
             array_push($link_term_scores, $new_score);
             $temp_user_matrix->link_score = $new_score;
             $temp_user_matrix->save();
         }
     }
     //same should be done for enrichments and ads
     //find max value and divide term values
     $max_term_value = max($term_scores);
     $max_link_term_value = max($link_term_scores);
     foreach ($video_term_list as $video_term_id) {
         $temp_user = $user->term->find($video_term_id);
         $user_term_score = $temp_user->pivot->user_score;
         //get score of user
         $temp_video = $video->term->find($video_term_id);
         $video_term_score = $temp_video->pivot->video_score;
         //get score of video
         //update score
         $new_score = $user_term_score / $max_term_value;
         //ok
         //				//store score
         $user->term()->sync([$video_term_id => ['user_score' => $new_score]], false);
     }
     for ($i = 0; $i <= $number_video_terms - 1; $i++) {
         for ($j = $i + 1; $j < $number_video_terms; $j++) {
             $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $video_term_list[$i])->where('term_neighbor_id', $video_term_list[$j])->get()->first();
             $old_score = $temp_user_matrix->link_score;
             $new_score = $old_score / $max_link_term_value;
             $temp_user_matrix->link_score = $new_score;
             $temp_user_matrix->save();
         }
     }
     //calculate profile
     $terms = Term::all()->count();
     for ($j = 1; $j <= $terms; $j++) {
         $profile_score = 0;
         for ($i = 1; $i <= $terms; $i++) {
             $temp_user = $user->term->find($i);
             $user_term_score = $temp_user->pivot->user_score;
             //get score of user
             if ($i == $j) {
                 $link_score = 0;
             } elseif ($i > $j) {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $j)->where('term_neighbor_id', $i)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             } else {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $i)->where('term_neighbor_id', $j)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             }
             $profile_score = $profile_score + $user_term_score * $link_score;
         }
         $user->profilescore()->sync([$j => ['profile_score' => $profile_score]], false);
     }
     //	DB::table('user_actions')->where('username',$username)->where('video_id', $video_id)->delete();
     return Redirect::route('home')->with('message', 'Thank you for watching the video');
 }