/** * @return array */ public function getKeywordsFor($text) { $keywords = $this->alchemy->keywords('text', $text); $words = array(); if (isset($keywords['keywords'])) { $total = 0; foreach ($keywords['keywords'] as $keyword) { if ($total++ < $this->maxKeywords) { $words[] = (string) $keyword['text']; } } } return $words; }
echo 'type: ', $response['docSentiment']['type'], PHP_EOL; echo 'score: ', $response['docSentiment']['score'], PHP_EOL; } else { echo 'Error in the sentiment analysis call: ', $response['statusInfo']; } echo PHP_EOL; echo PHP_EOL; echo PHP_EOL; echo '############################################', PHP_EOL; echo '# Keyword Extraction Example #', PHP_EOL; echo '############################################', PHP_EOL; echo PHP_EOL; echo PHP_EOL; echo 'Processing text: ', $demo_text, PHP_EOL; echo PHP_EOL; $response = $alchemyapi->keywords('text', $demo_text, array('sentiment' => 1)); if ($response['status'] == 'OK') { echo '## Response Object ##', PHP_EOL; echo print_r($response); echo PHP_EOL; echo '## Keywords ##', PHP_EOL; foreach ($response['keywords'] as $keyword) { echo 'text: ', $keyword['text'], PHP_EOL; echo 'relevance: ', $keyword['relevance'], PHP_EOL; echo 'sentiment: ', $keyword['sentiment']['type'], ' (' . $keyword['sentiment']['score'] . ')', PHP_EOL; echo PHP_EOL; } } else { echo 'Error in the keyword extraction call: ', $response['statusInfo']; } echo PHP_EOL;
<?php $file = file_get_contents('../all.txt', true); require_once '../alchemyapi/alchemyapi.php'; $alchemyapi = new AlchemyAPI(); ?> <?php $rows = array(); //flag is not needed $flag = true; $table = array(); $table['cols'] = array(array('label' => 'text', 'type' => 'string'), array('label' => 'sentiment', 'type' => 'string'), array('label' => 'relevance', 'type' => 'number')); $rows = array(); $response = $alchemyapi->keywords('text', $file, array('sentiment' => 1)); foreach ($response['keywords'] as $keyword) { $temp = array(); // the following line will be used to slice the Pie chart $temp[] = array('v' => (string) $keyword['text']); $temp[] = array('v' => (string) $keyword['sentiment']['type']); // Values of each slice $temp[] = array('v' => (double) $keyword['relevance']); $rows[] = array('c' => $temp); } $table['rows'] = $rows; $jsonTable = json_encode($table); //echo $jsonTable; ?> <html>
<span id="sl_i4" class="sl_command sl_i"> </span> <h2 class="sread">The slideshow</h2> <div class="lyrics" style=" color:#FFF; font-family:Verdana, Geneva, sans-serif;margin-top:30px;margin-bottom:20px;"><hr /> <?php $id = $_GET["trackid"]; // To get lyrics $url = "http://api.musixmatch.com/ws/1.1/track.lyrics.get?apikey=76bda465128468ccea51f3ad58f3fcdd&track_id=" . $id . "&format=xml"; $xml = simplexml_load_file($url); $value = (string) $xml->body->lyrics->lyrics_body; print_r($value); //to get meaning require_once 'alchemyapi_php-master/alchemyapi.php'; $alchemyapi = new AlchemyAPI(); $response = $alchemyapi->keywords('text', "{$value}", array('sentiment' => 1)); ?> <!-- Start WOWSlider.com BODY section --> <!-- add to the <body> of your page --> <div id="wowslider-container0"> <div class="ws_images"><ul> <?php $i = 0; foreach ($response['keywords'] as $keyword) { //displaying images $url_image = 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=77ba63794367be8f4b47e1b9fb7b9a3d&text=' . $keyword['text'] . '&per_page=10';
function render() { $sounds = array("A", "As", "B", "C", "Cs", "D", "Ds", "E", "F", "Fs", "G", "Gs"); $paragraphs = array(); // build indexed array of dream values $dreams_by_value = array(); foreach ($this->dreams as $dream) { if ($dream->node_type == self::TYPE_DREAM) { $index = array_search($dream, $this->dreams); $dreams_by_value[$index] = $dream->value; } if ($dream->value) { $sound_id = $sounds[floor(count($sounds) / 0xffffff * hexdec($dream->color2))]; $sound_id .= min($dream->value, 3); $dream->soundeffect_path = $sound_id; } } // sort array of values by value arsort($dreams_by_value); // textualization $paragraphs[0] = array(); $total_weight = 0; foreach ($dreams_by_value as $index => $value) { $total_weight += max(1, $this->dreams[$index]->value); } $cursor_position = 0; $i = 0; foreach ($dreams_by_value as $index => $value) { $dream = $this->dreams[$index]; $sentences = preg_split("/(\\.+\\s*)/", $dream->description); $influence = max(1, $dream->value) / $total_weight; $excerpt_count = ceil($influence * count($sentences)); $start = round(count($sentences) * $cursor_position); $length = min(count($sentences) - $start - 1, $excerpt_count); $excerpt = array_slice($sentences, $start, $length); $explanation = count($excerpt) . " sentences taken from the " . $this->cardinalize($i + 1) . " most influential dream"; for ($j = 0; $j < count($excerpt); $j++) { $paragraphs[0][] = array("index" => $dream->index, "sentence" => $sentences[$j], "explanation" => $explanation); } $cursor_position = ($start + $length) / count($sentences); $i++; } // get alchemy tags for synthesized root node dynamically if (self::SHOW_TAGS) { // flatten node content into a string $text = ""; $sentences = array(); foreach ($paragraphs as $p) { foreach ($p as $sentence) { $sentences[] = $sentence['sentence']; } } $text = implode(". ", $sentences); // alchemy $alchemy = new AlchemyAPI($this->alchemyApiKey); $params = array(); $params['maxRetrieve'] = $this->maxKeywords; $params['keywordExtractMode'] = 'strict'; $params['sentiment'] = 0; $params['showSourceText'] = 0; try { // parse response $result = $alchemy->keywords('text', $text, $params); } catch (Exception $e) { } if (isset($result) && $result['status'] == "OK") { $root_node = $this->nodes[0]; foreach ($result['keywords'] as $keyword) { $tag = stripslashes($keyword['text']); $tag = preg_replace("/\\./", "", $tag); if (isset($this->indexes['tags'][$tag])) { $tag_node = $this->indexes['tags'][$tag]; } else { $this->indexes['tags'][$tag] = $this->tags[] = $tag_node = (object) array('color' => '#000000', 'id' => -1, 'index' => count($this->nodes), 'node_type' => 'tag', 'tags' => array(), 'title' => $tag, 'value' => 0); } if ($tag_node->value >= $this->minTagValue) { if (!array_search($tag_node, $this->nodes)) { $this->nodes[] = $tag_node; } $this->addTag($tag_node, $root_node); } } } } $this->nodes[0]->description = $paragraphs; foreach ($this->nodes as $node) { if ($node->node_type == self::TYPE_TAG || $node->node_type == self::TYPE_DREAM && (isset($node->ip) && $node->ip == $_SERVER['REMOTE_ADDR'])) { $node->stroke = true; } else { $node->stroke = $node->strokeContrast = isset($node->color2) ? hexdec(preg_replace("/#/", "0x", $node->color2)) < 0x666666 ? true : false : false; } } $data = (object) array('nodes' => $this->nodes, 'links' => $this->links, 'dream_total' => count($this->dreams), 'art_total' => 0); return $data; }
// Keyword extraction extract($_GET); $res_arr = array(); $more_res = array(); $keywords = array(); $text = rawurldecode($demo_text); $file_searched = fopen("search_terms.txt", "a+"); $size = filesize("search_terms.txt"); if ($size == 0) { $searched = array(); } else { $searched = fread($file_searched, filesize("search_terms.txt")); $searched = explode(";", $searched); } // $text = "Machine learning is a subfield of computer science that evolved from the study of pattern recognition and computational learning theory in artificial intelligence. Machine learning explores the study and construction of algorithms that can learn from and make predictions on data."; $response = $alchemyapi->keywords('text', $text, array('maxRetrieve' => 2)); if ($response['status'] == 'OK') { $words = ''; foreach ($response['keywords'] as $keyword) { //$words = $words . ';' . $keyword['text'] . ':' . $keyword['relevance']; $words = $words . ';' . $keyword['text'] . ':' . $keyword['relevance']; $keywords[$keyword['text']] = $keyword['relevance']; } } else { echo 'Error in the keyword extraction call: ', $response['statusInfo']; } // $keywords = array('computational learning theory'=> '0.971245', // 'pattern recognition'=> '0.854866', // 'artificial intelligence'=> '0.793011', // 'Machine learning' => '0.714784', // 'subfield'=> '0.638192');
public function save($validate = true) { $this->logger->clear(); // validation $valid = !$validate || $this->validate(); // get a user_id, either by adding new user or fetching id of existing if ($valid) { $user = new User(null, $this->db); $user->email = $this->email; $user->name = $this->username; if (!is_null($user->email) && !empty($user->email)) { $user->loadFromEmail(); } else { if (!is_null($user->name) && !empty($user->name)) { $user->loadFromName(); } } if ($this->isImport) { $user->implied = 1; } if ($user->id) { $this->logger->log("user found..."); } else { $user->ip = $_SERVER['REMOTE_ADDR']; } $success = $user->save(); $this->user_id = $user->id; if (is_null($this->user_id)) { $valid = false; } } if ($valid && isset($this->imageUpload) && !empty($this->imageUpload["name"]) && $this->imageUpload["error"] == 0) { $this->logger->log("saving image..."); $image = new Media(null, $this->db); $image->name = time(); $image->mime_type = $this->imageUpload['type']; $image->tempFile = $this->imageUpload; if ($image->validate()) { if ($image->save()) { $this->logger->log("image saved..."); } else { $this->status = $image->errorMessage; $valid = false; $this->logger->log("error saving image..."); } } else { $this->status = $image->errorMessage; $valid = false; } } if ($valid && isset($this->audioUpload) && !empty($this->audioUpload["name"]) && $this->audioUpload["error"] == 0) { $this->logger->log("saving audio..."); $audio = new Media(null, $this->db); $audio->name = time(); $audio->mime_type = $this->audioUpload['type']; $audio->tempFile = $this->audioUpload; if ($audio->validate()) { if ($audio->save()) { $this->logger->log("audio saved..."); } else { $this->status = $audio->errorMessage; $valid = false; $this->logger->log("error saving audio..."); } } else { $this->status = $audio->errorMessage; $valid = false; $this->logger->log("error validating audio..."); } } $get_location = curl_init(); curl_setopt($get_location, CURLOPT_URL, "http://freegeoip.net/json/" . $_SERVER['REMOTE_ADDR']); curl_setopt($get_location, CURLOPT_RETURNTRANSFER, 1); $location = curl_exec($get_location); $location = json_decode($location); // import dream if ($valid) { $date = DateTime::createFromFormat($this->dateFormat, $this->date, new DateTimeZone($this->timezone)); $this->occur_date = $date->format('Y-m-d'); if ($location) { $this->city = $location->city; $this->country = $location->country_name; $this->latitude = $location->latitude; $this->longitude = $location->longitude; } else { $this->latitude = "0"; $this->longitude = "0"; } $success = parent::save(); if ($success) { $this->status = "Dream added!"; } else { if (isset($this->errorMessage)) { $this->status = $this->errorMessage; } else { $this->status = "Error updating dream"; } $valid = false; } } if (isset($image)) { if (!is_null($this->id) && !empty($this->id)) { $image->dream_id = $this->id; $image->save(); } else { $image->delete(); } $this->logger->log($image->logger->log); } if (isset($audio)) { if (!is_null($this->id) && !empty($this->id)) { $audio->dream_id = $this->id; $audio->save(); } else { $audio->delete(); } $this->logger->log($audio->logger->log); } $tags = array(); // add dream tags if ($valid && $this->useAlchemy) { $kb = strlen($this->description) / 1024; if ($kb <= 150) { $alchemy = new AlchemyAPI($this->alchemyApiKey); $params = array(); $params['maxRetrieve'] = 20; $params['keywordExtractMode'] = 'strict'; $params['sentiment'] = 1; $params['showSourceText'] = 0; try { $result = $alchemy->keywords('text', $this->description, $params); $this->logger->log("alchemy " . $result['status'] . ", " . (isset($result['keywords']) ? count($result['keywords']) : 0) . " keywords, " . $this->description); } catch (Exception $e) { $this->logger->log("alchemy, " . $result['status'] . ", " . $result['statusInfo']); } if (isset($result) && $result['status'] == "OK") { foreach ($result['keywords'] as $keyword) { $tag = stripslashes($keyword['text']); $tag = preg_replace("/^\\W|\\W\$|\\./", "", $tag); $tag = strtolower(trim($tag)); $tag = $this->db->real_escape_string($tag); // get tag_id $sql = "SELECT id FROM `tags` WHERE tag='" . $tag . "'"; $result2 = $this->db->query($sql); if ($this->db->affected_rows > 0) { $tag_row = $result2->fetch_assoc(); $tag_id = $tag_row['id']; } else { $sql = "INSERT INTO `tags` (tag,alchemy) VALUES ('" . $tag . "','1')"; $this->db->query($sql); $tag_id = $this->db->insert_id; } if ($tag_id) { $sentiment = $keyword['sentiment']; $sql = "INSERT INTO `dream_tags` (dream_id,tag_id,sentiment_type,sentiment_score) VALUES ('" . $this->id . "','" . $tag_id . "','" . $sentiment['type'] . "','" . (isset($sentiment['score']) ? $sentiment['score'] : 0) . "')"; $this->db->query($sql); } $tags[] = $tag; } } } else { $this->logger->log("Dream " . $this->id . " to big to process" . $kb); } } if ($valid && $this->postToTumblr && $this->tumblrPostEmail != null) { $to = $this->tumblrPostEmail; $subject = isset($this->title) ? $this->title : "untitled"; $body = $this->description; $body .= "\n\nDreamt on " . $this->date . " by a " . $this->age . " year old " . ($this->gender == "male" ? "man" : "woman") . " in " . $location->city; $body .= "\n\nhttp://artefactsofthecollectiveunconscious.net/browse.php?did=" . $this->id; $tagline = ''; foreach ($tags as $tag) { $tagline .= "#" . $tag . " "; } $body .= "\n\n" . $tagline; mail($to, $subject, $body); } if ($valid) { foreach ($this->feelings as $feeling_id) { if ($feeling_id) { $sql = "INSERT INTO `dream_feelings` (dream_id,feeling_id) VALUES ('" . $this->id . "','" . $feeling_id . "')"; $result = $this->db->query($sql); } } } if ($valid) { $this->init(); } return $valid; }
<?php require_once 'alchemyapi.php'; $alchemyapi = new AlchemyAPI('YOUR_API_KEY'); $DATA = 'Any news'; //the news goes in here $FLAVOR = 'text'; $response = $alchemyapi->keywords($FLAVOR, $DATA, array('sentiment' => 0)); // $response = $alchemyapi->keywords('text', 'Bunnies are nice but sometimes robots are evil', array('sentiment'=>1)); foreach ($response['keywords'] as $keyword) { echo $keyword['text'], PHP_EOL; }
echo 'Combined tests complete!', PHP_EOL, PHP_EOL; //Entities echo 'Checking entities . . . ', PHP_EOL; $response = $alchemyapi->entities('text', $test_text, null); assert($response['status'] == 'OK'); $response = $alchemyapi->entities('html', $test_html, null); assert($response['status'] == 'OK'); $response = $alchemyapi->entities('url', $test_url, null); assert($response['status'] == 'OK'); $response = $alchemyapi->entities('random', $test_url, null); assert($response['status'] == 'ERROR'); //invalid flavor echo 'Entity tests complete!', PHP_EOL, PHP_EOL; //Keywords echo 'Checking keywords . . . ', PHP_EOL; $response = $alchemyapi->keywords('text', $test_text, null); assert($response['status'] == 'OK'); $response = $alchemyapi->keywords('html', $test_html, null); assert($response['status'] == 'OK'); $response = $alchemyapi->keywords('url', $test_url, null); assert($response['status'] == 'OK'); $response = $alchemyapi->keywords('random', $test_url, null); assert($response['status'] == 'ERROR'); //invalid flavor echo 'Keyword tests complete!', PHP_EOL, PHP_EOL; //Concepts echo 'Checking concepts . . . ', PHP_EOL; $response = $alchemyapi->concepts('text', $test_text, null); assert($response['status'] == 'OK'); $response = $alchemyapi->concepts('html', $test_html, null); assert($response['status'] == 'OK');
<?php require_once 'alchemyapi.php'; $alchemyapi = new AlchemyAPI(); $response = $alchemyapi->keywords('text', "Oh, love of mine\nWith a song and a whine\nYou're harsh and divine\nLike truths and a lie\n\nBut the tale ends not here\nI have nothing to fear\nFor my love is yell of giving and hold on\n\nAnd the bright emptiness\nIn a room full of it\nIs a cruel mistress\nWhoa oh!", array('sentiment' => 1)); foreach ($response['keywords'] as $keyword) { echo $keyword['text'], PHP_EOL; echo "<br />"; }