Example #1
0
def test_scrape_ynet():
    items_expected = [
        # note: the file holds date in winter timezone, so here it is described as summer timezone - +1 hour
        NewsFlash(
            date=datetime.datetime(
                2020, 5, 22, 19, 27, 32, tzinfo=timezones.ISREAL_SUMMER_TIMEZONE
            ),
            title="קפריסין הודיעה: ישראלים יוכלו להיכנס למדינה החל מה-9 ביוני",
            link="http://www.ynet.co.il/articles/0,7340,L-5735229,00.html",
            source="ynet",
            author="איתמר אייכנר",
            description=": \"שר התחבורה של קפריסין הודיע על תוכנית לפתיחת שדות התעופה וחידוש הטיסות החל מה-9 ביוני. התוכנית שאושרה בידי הממשלה חולקה לשני שלבים לפי תאריכים ומדינות שיורשו להיכנס בשעריה. עד ה-19 ביוני נוסעים מכל המקומות יצטרכו להיבדק לקורונה 72 שעות לפני מועד הטיסה. מה-20 ביוני יידרשו לכך רק נוסעים משוויץ, פולין רומניה, קרואטיה, אסטוניה וצ'כיה. בתי המלון ייפתחו ב-1 ביוני, וחובת הבידוד תבוטל ב-20 ביוני.   ",
        ),
        NewsFlash(
            date=datetime.datetime(2020, 5, 22, 16, 8, 48, tzinfo=timezones.ISREAL_SUMMER_TIMEZONE),
            link="http://www.ynet.co.il/articles/0,7340,L-5735178,00.html",
            source="ynet",
            author="אלישע בן קימון",
            title="צוותי כיבוי פועלים בשריפת קוצים שמתפשטת סמוך ליצהר שבשומרון",
            description=': "צוותי כיבוי פועלים בשריפת קוצים שמתפשטת לעבר ההתנחלות יצהר שבשומרון. לוחמי האש פועלים למניעת התקדמות השריפה ליצהר על ידי חתירה למגע עם האש ובסיוע מטוסי כיבוי. נמסר כי קיימת סכנה למוצב צבאי במקום.   ',
        ),
    ]

    items_actual = list(
        rss_sites.scrape("ynet", fetch_rss=fetch_rss_ynet, fetch_html=fetch_html_ynet)
    )
    assert_all_equal(items_actual, items_expected)
    verify_cache(items_actual)
Example #2
0
def test_extract_location():
    if not secrets.exists("GOOGLE_MAPS_KEY"):
        pytest.skip("Could not find GOOGLE_MAPS_KEY")

    parsed = dict(
        link="https://twitter.com/mda_israel/status/1253010741080326148",
        title='בשעה 19:39 התקבל דיווח במוקד 101 של מד"א במרחב דן על הולכת רגל שככל הנראה נפגעה מאופנוע ברחוב ביאליק ברמת גן. צוותי מד"א מעניקים טיפול ומפנים לבי"ח איכילוב 2 פצועים: אישה כבת 30 במצב קשה, עם חבלה רב מערכתית ורוכב האופנוע, צעיר בן 18 במצב בינוני, עם חבלות בראש ובגפיים.',
        description='בשעה 19:39 התקבל דיווח במוקד 101 של מד"א במרחב דן על הולכת רגל שככל הנראה נפגעה מאופנוע ברחוב ביאליק ברמת גן. צוותי מד"א מעניקים טיפול ומפנים לבי"ח איכילוב 2 פצועים: אישה כבת 30 במצב קשה, עם חבלה רב מערכתית ורוכב האופנוע, צעיר בן 18 במצב בינוני, עם חבלות בראש ובגפיים.',
        source="twitter",
        tweet_id=1253010741080326144,
        author="מגן דוד אדום",
        date=datetime.datetime(2020, 4, 22, 19, 39, 51),
        accident=True,
    )
    expected = NewsFlash(
        **parsed,
        lat=32.0861791,
        lon=34.8098462,
        resolution="רחוב",
        location="רחוב ביאליק ברמת גן",
        road_segment_name=None,
        district_hebrew=None,
        non_urban_intersection_hebrew=None,
        region_hebrew=None,
        road1=None,
        road2=None,
        street1_hebrew="ביאליק",
        street2_hebrew=None,
        yishuv_name="רמת גן",
    )

    actual = NewsFlash(**parsed)
    location_extraction.extract_geo_features(init_db(), actual)
    for k in to_dict(expected):
        assert getattr(actual, k) == getattr(expected, k)
Example #3
0
def test_scrape_walla():
    items_expected = [
        NewsFlash(
            date=datetime.datetime(2020, 5, 23, 19, 55, tzinfo=timezones.ISREAL_SUMMER_TIMEZONE),
            title='פרקליטי רה"מ יתלוננו נגד רביב דרוקר על שיבוש הליכי משפט',
            link="https://news.walla.co.il/break/3362504",
            source="walla",
            author="דניאל דולב",
            description='פרקליטיו של ראש הממשלה בנימין נתניהו מתכוונים להגיש הערב (שבת) תלונה ליועץ המשפטי לממשלה, אביחי מנדלבליט, נגד העיתונאי רביב דרוקר בטענה ששיבש הליכי משפט והדיח עד בתוכניתו "המקור". התלונה מתייחסת לראיונות שנתנו לתוכנית עדי תביעה במשפטו של נתניהו, בהם שאול אלוביץ\' ומומו פילבר.]]>',
        ),
        NewsFlash(
            date=datetime.datetime(2020, 5, 22, 16, 14, tzinfo=timezones.ISREAL_SUMMER_TIMEZONE),
            title="פקיסטן: לפחות נוסע אחד שרד את התרסקות המטוס",
            link="https://news.walla.co.il/break/3362389",
            source="walla",
            author="רויטרס",
            description="לפחות נוסע אחד שרד מהתרסקות המטוס הפקיסטני היום (שישי) באזור מגורים בקראצ'י - כך אמר גורם בממשל המקומי. בהודעתו אמר דובר ממשלת המחוז כי בנקאי שהיה על המטוס אותר לאחר ששרד את ההתרסקות. מרשות התעופה האזרחית של פקיסטן נמסר כי היו 91 נוסעים ושמונה אנשי צוות על מטוס איירבוס A320.]]>",
        ),
    ]

    items_actual = list(
        rss_sites.scrape("walla", fetch_rss=fetch_rss_walla, fetch_html=fetch_html_walla)
    )
    assert_all_equal(items_actual, items_expected)
    verify_cache(items_actual)
def add_news_flash_to_cache(news_flash: NewsFlash):
    try:
        if not (news_flash.accident and anyway.infographics_utils.
                is_news_flash_resolution_supported(news_flash)):
            logging.debug(
                f"add_news_flash_to_cache: news flash does not qualify:{news_flash.serialize()}"
            )
            return True
        db.get_engine().execute(
            InfographicsDataCache.__table__.insert(),  # pylint: disable=no-member
            [{
                "news_flash_id":
                news_flash.get_id(),
                "years_ago":
                y,
                "data":
                anyway.infographics_utils.create_infographics_data(
                    news_flash.get_id(), y, "he"),
            } for y in CONST.INFOGRAPHICS_CACHE_YEARS_AGO],
        )
        logging.info(f"{news_flash.get_id()} added to cache")
        return True
    except Exception as e:
        logging.exception(
            f"Exception while inserting to cache. flash_id:{news_flash}), cause:{e.__cause__}"
        )
        return False
Example #5
0
def extract_geo_features(db, newsflash: NewsFlash) -> None:
    newsflash.location = extract_location_text(
        newsflash.description) or extract_location_text(newsflash.title)
    geo_location = geocode_extract(newsflash.location)
    if geo_location is not None:
        newsflash.lat = geo_location["geom"]["lat"]
        newsflash.lon = geo_location["geom"]["lng"]
        newsflash.resolution = set_accident_resolution(geo_location)
        location_from_db = get_db_matching_location(db, newsflash.lat,
                                                    newsflash.lon,
                                                    newsflash.resolution,
                                                    geo_location["road_no"])
        for k, v in location_from_db.items():
            setattr(newsflash, k, v)
Example #6
0
def test_scrape_ynet():
    items_expected = [
        # note: the file holds date in winter timezone, so here it is described as summer timezone - +1 hour
        NewsFlash(
            date=datetime.datetime(2021,
                                   6,
                                   23,
                                   13,
                                   58,
                                   51,
                                   tzinfo=timezones.ISREAL_SUMMER_TIMEZONE),
            title=
            'עבודות לתועלת הציבור לסייעת "גן מתוק" בגבעתיים שבו הותקפו ילדים',
            link='https://www.ynet.co.il/news/article/HkhoCYxnO',
            source="ynet",
            author="גלעד מורג",
            description=
            'בית משפט השלום בתל אביב קבע שלא להרשיע את סייעת "גן מתוק" בגבעתיים, אורנה אקבלי. הוא קבע שביצעה עבירת סיוע לתקיפה אך בגלל נסיבות החריגות של המקרה ובגלל שהייתה מעורבת בדיווח על האלימות בגן לא תורשע. עם זאת על אקבלי הוטלו 180 שעות עבודות לתועלת הציבור, צו מבחן, ו-3,000 שקל פיצויים.',
        ),
    ]

    items_actual = list(
        rss_sites.scrape("ynet",
                         rss_source="tests/ynet.xml",
                         fetch_html=fetch_html_ynet))
    assert_all_equal(items_actual, items_expected)
    verify_cache(items_actual)
Example #7
0
 def test_add_unqualified_news_flash(self, utils):
     nf = NewsFlash(accident=False,
                    resolution=["xxx"],
                    road_segment_name="name")
     res = add_news_flash_to_cache(nf)
     utils.assert_not_called()
     assert res, "Should return True when no error occurred"
Example #8
0
def scrape(site_name, *, fetch_rss=_fetch, fetch_html=_fetch):
    config = sites_config[site_name]
    rss_text = fetch_rss(config["rss"])

    # Patch RSS issue in walla. This might create duplicate `guid` field
    rss_text = rss_text.replace("link", "guid")

    rss_soup = BeautifulSoup(rss_text, features="lxml")
    rss_soup_items = rss_soup.find_all("item")

    assert rss_soup_items

    for item_rss_soup in rss_soup_items:
        link = item_rss_soup.guid.get_text()
        date = timezones.parse_creation_datetime(
            item_rss_soup.pubdate.get_text())

        html_text = fetch_html(link)
        item_html_soup = BeautifulSoup(html_text, "lxml")

        author, title, description = config["parser"](item_rss_soup,
                                                      item_html_soup)
        yield NewsFlash(
            link=link,
            date=date,
            source=site_name,
            author=author,
            title=title,
            description=description,
            accident=False,
        )
Example #9
0
 def test_add_news_flash_throws_exception(self, utils, get_engine):
     nf = NewsFlash(id=17,
                    accident=True,
                    resolution="כביש בינעירוני",
                    road_segment_name="name")
     get_engine.side_effect = RuntimeError
     res = add_news_flash_to_cache(nf)
     assert not res, "Should return False when error occurred"
Example #10
0
def parse_tweet(tweet, screen_name):
    return NewsFlash(
        link="https://twitter.com/{}/status/{}".format(screen_name, tweet["id_str"]),
        date=timezones.parse_creation_datetime(tweet["created_at"]),
        source="twitter",
        author=to_hebrew[screen_name],
        title=tweet["full_text"],
        description=tweet["full_text"],
        tweet_id=int(tweet["id_str"]),
        accident=False,
    )
Example #11
0
 def test_add_qualified_news_flash(self, utils, get_engine):
     nf = NewsFlash(id=17, accident=True, resolution="כביש בינעירוני", road_segment_name="name")
     get_engine.execute.return_value = {}
     res = add_news_flash_to_cache(nf)
     invocations = utils.call_args_list
     utils.assert_has_calls(
         [unittest.mock.call(17, y, "he") for y in CONST.INFOGRAPHICS_CACHE_YEARS_AGO]
     )
     for i in range(len(invocations)):
         self.assertEqual(invocations[i][0][0], 17, "incorrect news flash id")
         self.assertEqual(invocations[i][0][1], CONST.INFOGRAPHICS_CACHE_YEARS_AGO[i])
     assert res, "Should return True when no error occurred"
Example #12
0
 def test_is_news_flash_resolution_supported(self, mock_extract):
     expected = \
         {'name': 'location',
          'data': {'resolution': 'רחוב',
                   'yishuv_name': 'נצרת',
                   'street1_hebrew': 'רח 6021',
                   'road1': 17
                   },
          'gps': {'lat': 32.6994161, 'lon': 35.2960886}
          }
     mock_extract.return_value = expected
     actual = is_news_flash_resolution_supported(NewsFlash())
     self.assertTrue(actual, f"{expected}")
     mock_extract.return_value = \
         {'name': 'location',
          'data': {'resolution': 'רחוב',
                   'street1_hebrew': 'רח 6021'
                   },
          'gps': {'lat': 32.6994161, 'lon': 35.2960886}
          }
     actual = is_news_flash_resolution_supported(NewsFlash())
     self.assertFalse(actual, "yishuv_name missing")
Example #13
0
def test_scrape_walla():
    # Reuters is marked differently than Walla's authors
    items_expected = [
        NewsFlash(
            date=datetime.datetime(2021,
                                   6,
                                   23,
                                   16,
                                   49,
                                   tzinfo=timezones.ISREAL_SUMMER_TIMEZONE),
            title='חובת המסכות תוחזר אם יהיה ממוצע שבועי של 100 חולים ביום',
            link="https://news.walla.co.il/break/3443829",
            source="walla",
            author="מירב כהן",
            description=
            'חובת המסכות תוחזר בחללים סגורים אם יהיה ממוצע שבועי של 100 חולים ביום - כך הוחלט היום (רביעי) בדיון השרים.',
        ),
        NewsFlash(
            date=datetime.datetime(2021,
                                   7,
                                   14,
                                   9,
                                   10,
                                   tzinfo=timezones.ISREAL_SUMMER_TIMEZONE),
            title="פקיסטן: שמונה הרוגים בפיצוץ באוטובוס",
            link="https://news.walla.co.il/break/3448092",
            source="walla",
            author="רויטרס",
            description=
            "שמונה בני אדם נהרגו הבוקר (רביעי) בפיצוץ אוטובוס בצפון פקיסטן. בין ההרוגים, שישה מהנדסים תושבי סין. טרם ידוע מקור הפיצוץ.",
        ),
    ]

    items_actual = list(
        rss_sites.scrape("walla",
                         rss_source="tests/walla.xml",
                         fetch_html=fetch_html_walla))
    assert_all_equal(items_actual, items_expected)
    verify_cache(items_actual)
Example #14
0
 def setUp(self) -> None:
     self.connection = db.get_engine().connect()
     # begin a non-ORM transaction
     self.trans = self.connection.begin()
     # bind an individual Session to the connection
     self.session = Session(bind=self.connection)
     # add data
     self.region_description = 'test_region_description'
     nf_region = NewsFlash(road1=12345678,
                           description=self.region_description,
                           accident=True,
                           resolution="מחוז",
                           lat=32.0192988,
                           lon=34.7971384)
     self.session.add(nf_region)
     self.district_description = 'test_district_description'
     nf_district = NewsFlash(road1=12345678,
                             description=self.district_description,
                             accident=True,
                             resolution="נפה",
                             lat=32.0192988,
                             lon=34.7971384)
     self.session.add(nf_district)
     self.session.commit()
Example #15
0

@pytest.mark.slow
def test_scrape_sanity_online_twitter():
    if not secrets.exists("TWITTER_CONSUMER_SECRET"):
        pytest.skip("Could not find TWITTER_CONSUMER_SECRET")

    assert twitter.scrape("mda_israel", count=1)


twitter_expected_list = [
    NewsFlash(
        link="https://twitter.com/mda_israel/status/1267054794587418630",
        date=datetime.datetime(2020, 5, 31, 14, 26, 18, tzinfo=timezones.ISREAL_SUMMER_TIMEZONE),
        source="twitter",
        author="מגן דוד אדום",
        title='בשעה 13:19 התקבל דיווח במוקד 101 של מד"א במרחב ירושלים על פועל שנפצע במהלך עבודתו במפעל באזור התעשיה עטרות בירושלים. חובשים ופראמדיקים של מד"א מעניקים טיפול רפואי ומפנים לבי"ח שערי צדק גבר בן 31 במצב קשה, עם חבלת ראש.',
        description='בשעה 13:19 התקבל דיווח במוקד 101 של מד"א במרחב ירושלים על פועל שנפצע במהלך עבודתו במפעל באזור התעשיה עטרות בירושלים. חובשים ופראמדיקים של מד"א מעניקים טיפול רפואי ומפנים לבי"ח שערי צדק גבר בן 31 במצב קשה, עם חבלת ראש.',
        tweet_id=1267054794587418630,
        accident=False,
    ),
    NewsFlash(
        link="https://twitter.com/mda_israel/status/1267037315869880321",
        date=datetime.datetime(2020, 5, 31, 13, 16, 51, tzinfo=timezones.ISREAL_SUMMER_TIMEZONE),
        source="twitter",
        author="מגן דוד אדום",
        title='בשעה 12:38 התקבל דיווח במוקד 101 של מד"א במרחב ירדן על ת.ד סמוך למסעדה. חובשים ופראמדיקים של מד"א מעניקים טיפול רפואי ל4 פצועים, בהם 1 מחוסר הכרה.',
        description='בשעה 12:38 התקבל דיווח במוקד 101 של מד"א במרחב ירדן על ת.ד סמוך למסעדה. חובשים ופראמדיקים של מד"א מעניקים טיפול רפואי ל4 פצועים, בהם 1 מחוסר הכרה.',
        tweet_id=1267037315869880321,
        accident=True,
        location='בשעה 12:38 התקבל דיווח במוקד 101 של מד"א במרחב ירדן על ת',  # Note: erroneous expected
        lat=32.052603,
Example #16
0
def scrape(*args, **kwargs):
    # lazily load dependencies, so this module will behave like an independent library
    from anyway.models import NewsFlash

    for dict_item in scrape_raw(*args, **kwargs):
        yield NewsFlash(**dict_item)