news_fr / extract_news /3_extract_news_txt.php
eckendoerffer's picture
Upload 10 files
eaee53a
raw
history blame
15.4 kB
<?php
/**
* News Article Text Extractor
*
* This script extracts the text from locally-stored news articles. The main goal is
* to retrieve clean text with minimal external elements, such as user menus, article lists,
* and advertisements.
*
* To use this script, you must have electrolinux/phpquery installed. Install it using Composer with
* the command: composer require electrolinux/phpquery.
*
* After completing this step, you can use the Python script located at /dataset/2_cleaning_txt.py
* to standardize the text for your dataset.
*
* Debugging:
* - Enable debugging by setting the `$debug` variable to 1. This will display the hexadecimal
* code for each character in the final version before being saved in /txt_news/. Additionally,
* it will show the full HTML version or the complete HTML source if there's no output.
* - GET variables:
* - `?id=`: Use this integer value to display a specific news article. This corresponds
* to the ID in the `base_news` table.
* - `?media=`: Use this integer value to display a specific media. This corresponds
* to the ID in the `base_media` table.
*
* Note:
* RSS feed links for media sources, as well as the HTML structure of media pages, tend to change
* and evolve regularly. It's crucial to regularly check the output per media source and adjust
* the parsing process to ensure high-quality text extraction and to address potential changes
* in RSS feed URLs.
*
* @author Guillaume Eckendoerffer
* @date 08-09-2023
*/
$debug = 0;
$redirect_enabled = 1;
$time_start = microtime(true);
// composer require electrolinux/phpquery
require 'vendor/autoload.php';
// Include the database functions
include( "functions_mysqli.php" );
// Initialize global variables
$last = date( "U" );
$path = $_SERVER ['DOCUMENT_ROOT'];
/**
* Cleans the input text by replacing specific characters and filtering out unwanted Unicode categories.
*
* @param string $text The original text to be cleaned.
* @return string The cleaned text with specific replacements and filtered characters.
*
* @example
* clean_text("Hello`World!"); // Returns "Hello'World!"
*/
function clean_text( $text ) {
$text = str_replace( chr( 8217 ), "'", $text );
$text = str_replace( "`", "'", $text );
$text = str_replace( "’", "'", $text );
$dict_char = str_split( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/*-+.$*ù^£–—“”—" .
"µ%¨!:;,?./§&é\"'(è_çàâ)=°ç[{#}]¤~²ôûîïäëêíáã•©®€¢¥ƒÁÂÀÅÃäÄæÇÉÊÈËÍîÎñÑÓÔóÒøØõÕö" .
"ÖœŒšŠßðÐþÞÚúûÛùÙüÜýÝÿŸαβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ×÷" .
"±∓≠<>≤≥≈∝∞∫∑∈∉⊆⊇⊂⊃∪∩∧∨¬∀∃π×⨯⊗→←↑↓↔ ϒϖϑℵ⟩⟨⋅⊗⊄≅∗∉∅⇓⇑⇐↵ℜℑ℘⊕⊥∼∴∪∨∧∠∝" .
"∋∈∇∃∀⇔⇒∩¬∞√∑∏∂″′ªº³²¹¾½¼‰¶‡†¿§«»@" );
for ( $i = 0; $i < strlen( $text ); $i++ ) {
$char = $text[$i];
if ( !in_array( $char, $dict_char ) ) {
$text = str_replace( $char, ' ', $text );
}
}
return $text;
}
// Search for the source code of the next record to process
if( isset( $_GET["id"] ) AND is_numeric( $_GET["id"] ) ) $req="`id`='" . $_GET["id"] . "'"; else $req="`step`='1' ORDER By `id` ";
if( isset( $_GET["media"] ) AND is_numeric( $_GET["media"] ) ) $req="`media`='" . $_GET["media"] . "' ORDER By Rand() ";
$result = mysqli_query( $mysqli, "SELECT `id`, `url`, `title`, `txt_clean` FROM `base_news` WHERE $req LIMIT 1" );
while ( $row = mysqli_fetch_assoc( $result ) ) {
$id_source = $row["id"];
$next = $id_source + 1;
$url = trim( $row["url"] );
$title = trim( html_entity_decode( $row["title"] ) );
$txt_clean = trim( $row["txt_clean"] );
}
if( !isset( $id_source ) ) exit;
mysqli_query( $mysqli, "UPDATE `base_news` SET `step`='2' WHERE `id`='$id_source' LIMIT 1" );
$htmlContent = '';
$file_path = "$path/sources/html_news/$id_source.txt";
if ( file_exists( $file_path ) ) $htmlContent = implode ( '', file ( $file_path ) );
if( substr_count( $url, '/replay' ) ) $htmlContent ='';
// utf8
$current_encoding = mb_detect_encoding( $htmlContent, 'auto' );
try {
$htmlContent = ($current_encoding == 'UTF-8') ? $htmlContent : mb_convert_encoding($htmlContent, 'UTF-8', $current_encoding);
} catch (ValueError $e) {
if( $redirect_enabled )
echo "<script type=\"text/javascript\">location.href='" . str_replace( strstr( $_SERVER ['REQUEST_URI'], '?' ), "", $_SERVER ['REQUEST_URI'] ) . "?id=$next';</script>";
else
echo "Error: mb_convert_encoding()";
exit;
}
$doc = \phpQuery::newDocument( $htmlContent );
// Extracting the title
if( trim( $title )=='' ){
$title = html_entity_decode( trim( pq('h1')->text() ) );
mysqli_query( $mysqli, "UPDATE `base_news` SET `title`='" . addslashes( $title ) . "' WHERE `id`='$id_source' LIMIT 1" );
}
// Extracting the description
if( trim( $txt_clean )=='' ){
$description = pq('meta[name="description"]')->attr('content');
if( trim( $description )=='' ){
$description = pq('meta[name="og:description"]')->attr('content');
}
if( trim( $description )!='' ){
$txt_clean = html_entity_decode( trim( $description ) );
$txt_clean = preg_replace( '/\s{2,}/', ' ', $txt_clean );
}
}
// Extracting the text from source code
$content ='';
$html ='';
// Extracting the text from <article> tag
$color ='#008000';
if( !substr_count( $url, ".rtbf.be" ) ) {
foreach ( pq( 'article p' ) as $p ) {
$html .= " " . trim( pq( $p )->html() ) . " ";
if( substr_count( $url, ".futura-sciences.com" ) ) pq($p)->find('a')->remove();
$content .= " " . trim( html_entity_decode( pq( $p )->text() ) ) . " ";
}
}
// Extracting from <p> tags after <h1>
if( trim( $content )=='' ){
$start = pq('h1:first');
$nextElements = pq($start)->nextAll();
foreach ($nextElements as $element) {
if (pq($element)->is('p')) {
$start = trim(html_entity_decode(pq($element)->text()));
}
}
foreach ( pq( 'p' ) as $p ) {
$content .= " " . trim( html_entity_decode( pq( $p )->text() ) ) . " ";
}
if( trim( $start )!='' ) $content = strstr( $content, $start );
$color ='#000080';
}
// Extracting from <p> tags
if( trim( $content )=='' ){
foreach ( pq( 'p' ) as $p ) {
$content .= " " . trim( html_entity_decode( pq( $p )->text() ) ) ;
}
$color ='#888';
}
// Adding a space after punctuation and various deletions
$content = str_replace(array("\r", "\n"), ' ', $content);
$remove = [
'?',
'!',
";",
"!",
"»",
"]",];
foreach ( $remove as $phrase ) {
$content = str_replace( $phrase, $phrase . ' ', $content );
}
$content = str_replace( html_entity_decode('&nbsp;'), " ", $content ); // Standardizing spaces
$content = preg_replace( '/\s{2,}/', ' ', $content ); // one space, no more
$pattern = '/À lire aussi.{1,200}?»/';
$content = preg_replace($pattern, ' ', $content);
$pattern = '/Temps de Lecture.{1,20}? Fiche/';
$content = preg_replace($pattern, ' ', $content);
$pattern = '/Temps de Lecture.{1,20}? min./';
$content = preg_replace($pattern, ' ', $content);
// Media-specific cutting rules
if( substr_count( $url, ".elle.fr" ) ){
$pattern = '/Note :.{13,45}? sur 5/';
$content = preg_replace($pattern, ' ', $content);
$content = str_replace( strstr( $content, " sur 5 " ), '', $content );
}
if( substr_count( $url, ".latribune.fr" ) ){
$content = str_replace( "Partager :", ' ', $content );
}
if( substr_count( $url, ".techno-science.net" ) ){
$content = strip_tags( strstr( $htmlContent, "suivez-nous sur" ) );
$content = strstr( $content, ');' );
$content = html_entity_decode( str_replace( strstr( $content, "Référence" ), "", $content ) );
}
if( substr_count( $url, ".lexpress.fr" ) ){
$content = strstr( $htmlContent, "article__text" ) ;
$content = strstr( $content, ">" );
$content = substr( $content,1,99999 );
$content = html_entity_decode( strip_tags( str_replace( strstr( $content, "<div id=\"taboola" ), "", $content ) ) );
}
$content_or = $content; // Store the original content
// List of starting phrases to find and use as the new starting point
$startPhrases = [
"Partager l'article sur Twitter",
" au sommaire ",
"TF1 INFO",
"Licence Creative Commons",
" / AFP ",
"ne rien louper de vos programmes favoris.",
"© Belga"
];
foreach ( $startPhrases as $phrase ) {
if ( strpos( $content, $phrase ) !== false ) {
$content = strstr( $content, $phrase );
$content = str_replace( $phrase, ' ', $content );
break;
}
}
// List of phrases to remove from the end of content
$removePhrasesEnd = [
'Sur le même sujet',
'Sur lemême thème',
'Nos articles à lire aussi',
'Suivez toute l’actualité de vos villes',
'En direct',
"J'ai déjà un compte",
'> Ecoutez',
'Courrier international',
'Vous avez trouvé une erreur?',
'Il vous reste',
'Partager',
"Suivez-nous",
'Newsletter',
'Abonnez-vous',
'1€ le premier mois',
'Votre France Bleu',
'Soyez le premier à commenter cet article',
'Pour rester informé(e)',
'Un site du groupe',
"Cet article est réservé aux abonnés",
"Recevez chaque vendredi l'essentiel",
"Suivez toute l'actualité de ZDNet",
"Suivez-nous sur les résaux sociaux",
". par ",
"Le résumé de la semaine",
"ACTUELLEMENT EN KIOSQUE",
" L’actualité par la rédaction de",
"Gratis onbeperkt",
"Débloquez immédiatement cet article",
"À voir également",
"null null null ",
'Du lundi au vendredi, à 19h',
"La rédaction de La Tribune",
"Restez toujours informé: suivez-nous sur Google Actualités",
"Du lundi au vendredi, votre rendez-vous",
"Enregistrer mon nom, mon e-mail",
"Mot de passe oublié",
'(function',
];
foreach ( $removePhrasesEnd as $phrase ) {
$content = str_replace( strstr( $content, $phrase ), "", $content);
}
// List of phrases to remove
$removePhrases = [
"Inscrivez-vous pour recevoir les newsletters de la Rép' dans votre boîte mail",
"TF1 INFO",
"Sujet TF1 Info",
"Sujet JT LCI",
"TF1 Info ",
"JT 20h WE ",
"JT 20h Semaine ",
"Source :",
"Inscrivez-vous aux newsletters de la RTBF Tous les sujets de l'article",
"Pour voir ce contenu, connectez-vous gratuitement",
">> LIRE AUSSI",
"À LIRE AUSSI",
"A lire aussi >> ",
" → À LIRE.",
"À voir également",
"Image d'illustration -",
"Le média de la vie locale ",
"Les plus lus.",
"Ce live est à présent terminé.",
" . -",
"[…]",
"[.]",
"(…)",
"(.)",
"©"
];
foreach ( $removePhrases as $phrase ) {
$content = str_replace( $phrase, ".", $content );
}
$content = preg_replace( '/\.{2,}/', '.', $content );
$content = preg_replace( '/\s{2,}/', ' ', $content );
$content = preg_replace( '/-{2,}/', '-', $content );
$content = preg_replace( '/__{2,}/', '_', $content );
// Display
echo "<span style='font-family: verdana;font-size: .9em;'>($id_source) [$current_encoding] $url <br /><br />" .
"<b>Title: $title</b> <br /><br />" .
"<span style='color:$color;'>Content: $content</span>";
if( strlen( $content ) != strlen( $content_or ) ){
echo "<hr> <span style='color:#ff0000;'>$content_or</span>"; // original content
}
// Formatting the output content for the txt file in the $add variable
$content = strip_tags($content);
$add = html_entity_decode( $title ) . '. ';
if( trim( $txt_clean ) != '' ) $add .= str_replace( "..", ".", html_entity_decode( $txt_clean ) . '. ' );
if( strlen( $content ) > 160 ) $add .= $content . '.';
$add = trim( clean_text( $add ) );
$remove = [ '. .', '..', "?.", "!.", ";.", "??", "? ?",];
foreach ( $remove as $phrase ) {
$add = str_replace( $phrase, substr( $phrase,0,1 ). ' ', $add );
}
$add = strip_tags( $add );
$add = str_replace( html_entity_decode( '&nbsp;' ), " ", $add );
$add = preg_replace( '/&#(x[0-9a-fA-F]+|\d+);/', ' ', $add );
$add = preg_replace( '/&#\d+;/', ' ', $add );
$add = preg_replace( '/[\x{1F534}\x{26A0}\x{1F3C9}\x{1F6A8}\x{1F6D2}\x{1FA82}\x{25B6}\x{2139}\x{2600}-\x{26FF}\x{1F300}-\x{1F5FF}\x{1F600}-\x{1F64F}\x{1F680}-\x{1F6FF}\x{1F700}-\x{1F77F}\x{1F780}-\x{1F7FF}\x{1F800}-\x{1F8FF}\x{1F900}-\x{1F9FF}\x{1FA00}-\x{1FA6F}\x{1FA70}-\x{1FAFF}]/u', ' ', $add );
$add = preg_replace( '/\s{2,}/', ' ', $add );
$replacements = array( "À" => "À", "Â" => "Â", "Ã" => "Ã", "Ä" => "Ä", "Â" => "Â", "Ã…" => "Å", "á" => "á", "â" => "â", "ã" => "ã", "ä" => "ä", "Ã¥" => "å", "Ã’" => "Ò", "Ó" => "Ó", "Ô" => "Ô", "Õ" => "Õ", "Ö" => "Ö", "Ø" => "Ø", "ò" => "ò", "ó" => "ó", "ô" => "ô", "õ" => "õ", "ö" => "ö", "ø" => "ø", "È" => "È", "É" => "É", "Ê" => "Ê", "Ë" => "Ë", "è" => "è", "é" => "é", "ê" => "ê", "ë" => "ë", "Ç" => "Ç", "ç" => "ç", "ÃŒ" => "Ì", "ÃŽ" => "Î", "ì" => "ì", "í" => "í", "î" => "î", "ï" => "ï", "Ù" => "Ù", "Ú" => "Ú", "Û" => "Û", "Ãœ" => "Ü", "ù" => "ù", "ú" => "ú", "û" => "û", "ü" => "ü", "ÿ" => "ÿ", "Ñ" => "Ñ", "ñ" => "ñ", "Á" => "Á", "Í" => "Í", "à " => "à", '’'=>'\'', "«" => "«", '»'=>'»');
$add = str_replace( array_keys( $replacements ), array_values( $replacements ), $add );
// Additional display for debugging and testing
if( $debug ){
if( trim( $content )=='' ) {
echo "<hr /> html:<br /> $html " . htmlentities( $html ) . "<hr />" .
htmlentities( $doc->text() ) .'<br />' .
'Source lenght: ' . strlen( $htmlContent );
}
$test_char ="";
foreach ( str_split( $add ) as $char) {
$test_char .= $char . "(" . bin2hex($char). ") ";
}
echo '<hr /> hexadecimal code for each character from $add var: <br />' . $test_char;
} else {
if( $id_source%10000 === 0 ) mysqli_query( $mysqli, "OPTIMIZE TABLE `base_news`;" );
}
// Saving the title + description + text in a text file
$key_title = md5( $title );
$nb_base = mysqli_return_number( $mysqli, "SELECT `id` FROM `base_news` WHERE `key_title`='$key_title' LIMIT 1" );
if( isset( $_GET["id"] ) OR isset( $_GET["media"] ) OR ( strlen( $content ) > 200 AND !$nb_base ) ){
mysqli_query( $mysqli, "UPDATE `base_news` SET `key_title` = '$key_title' WHERE `id`='$id_source' LIMIT 1" );
$bom = "\xEF\xBB\xBF";
file_put_contents( "$path/sources/txt_news/$id_source.txt", $bom . $add );
}
$execution_time = microtime(true) - $time_start;
echo"<hr /> execution time: $execution_time";
if( $id_source%100 === 0 ) sleep(1); // throttling navigation to prevent the browser from hanging.
if( $redirect_enabled ) echo "<script type=\"text/javascript\">location.href='" . str_replace( strstr( $_SERVER ['REQUEST_URI'], '?' ), "", $_SERVER ['REQUEST_URI'] ) . "?id=$next';</script>";
?>