You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kibble.apache.org by hu...@apache.org on 2018/01/09 00:29:38 UTC

[kibble-scanners] branch master updated: Initial stab at KPE for Kibble

This is an automated email from the ASF dual-hosted git repository.

humbedooh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/kibble-scanners.git


The following commit(s) were added to refs/heads/master by this push:
     new 23839ca  Initial stab at KPE for Kibble
23839ca is described below

commit 23839ca993ea16c7e0cbc8f39935eb52e6b03aad
Author: Daniel Gruno <hu...@apache.org>
AuthorDate: Tue Jan 9 01:29:09 2018 +0100

    Initial stab at KPE for Kibble
    
    This only supports pony mail so far.
    We'll have to work on support for Pipermail etc
---
 src/plugins/scanners/ponymail-kpe.py | 141 ++++++++++++++++++++++++++++++
 src/plugins/utils/kpe.py             | 160 +++++++++++++++++++++++++++++++++++
 2 files changed, 301 insertions(+)

diff --git a/src/plugins/scanners/ponymail-kpe.py b/src/plugins/scanners/ponymail-kpe.py
new file mode 100644
index 0000000..5137b20
--- /dev/null
+++ b/src/plugins/scanners/ponymail-kpe.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+ #the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+This is a Kibble scanner plugin for Apache Pony Mail sources.
+"""
+import requests
+import json
+import time
+import re
+import hashlib
+import sys
+import datetime
+import plugins.utils.jsonapi
+import plugins.utils.kpe
+
+title = "Key Phrase Extraction plugin for Apache Pony Mail"
+version = "0.1.0"
+ROBITS = r"(git|gerrit|jenkins|hudson|builds|bugzilla)@"
+MAX_COUNT = 100 # Max number of unparsed emails to handle (so we don't max out API credits!)
+
+def accepts(source):
+    """ Test if source matches a Pony Mail archive """
+    # If the source equals the plugin name, assume a yes
+    if source['type'] == 'ponymail':
+        return True
+    
+    # If it's of type 'mail', check the URL
+    if source['type'] == 'mail':
+        if re.match(r"(https?://.+)/list\.html\?(.+)@(.+)", source['sourceURL']):
+            return True
+    
+    # Default to not recognizing the source
+    return False
+
+
+def scan(KibbleBit, source):
+    # Validate URL first
+    url = re.match(r"(https?://.+)/list\.html\?(.+)@(.+)", source['sourceURL'])
+    if not url:
+        KibbleBit.pprint("Malformed or invalid Pony Mail URL passed to scanner: %s" % source['sourceURL'])
+        source['steps']['mail'] = {
+            'time': time.time(),
+            'status': 'Could not parse Pony Mail URL!',
+            'running': False,
+            'good': False
+        }
+        KibbleBit.updateSource(source)
+        return
+    
+    if not 'azure' in KibbleBit.config and not 'picoapi' in KibbleBit.config:
+        KibbleBit.pprint("No Azure/picoAPI creds configured, skipping key phrase extraction")
+        return
+    
+    cookie = None
+    if 'creds' in source and source['creds']:
+        cookie = source['creds'].get('cookie', None)
+        
+    rootURL = re.sub(r"list.html.+", "", source['sourceURL'])
+    query = {
+            'query': {
+                'bool': {
+                    'must': [
+                        {
+                            'term': {
+                                'sourceID': source['sourceID']
+                            }
+                        }
+                    ]
+                }
+            },
+            'sort': [{'ts': 'desc'}]
+        }
+        
+    # Get an initial count of commits
+    res = KibbleBit.broker.DB.search(
+        index=KibbleBit.dbname,
+        doc_type="email",
+        body = query,
+        size = MAX_COUNT * 4
+    )
+    ec = 0
+    hits = []
+    for hit in res['hits']['hits']:
+        eml = hit['_source']
+        if not re.search(ROBITS, eml['sender']):
+            ec += 1
+            if ec > MAX_COUNT:
+                break
+            if 'kpe' not in eml:
+                emlurl = "%s/api/email.lua?id=%s" % (rootURL, eml['id'])
+                KibbleBit.pprint("Fetching %s" % emlurl)
+                rv = None
+                try:
+                    rv = plugins.utils.jsonapi.get(emlurl, cookie = cookie)
+                    if rv and 'body' in rv:
+                        hits.append([hit['_id'],rv['body'], eml])
+                except Exception as err:
+                    KibbleBit.pprint("Server error, skipping this email")
+        
+    bodies = []            
+    for hit in hits:
+        body = hit[1]
+        bid = hit[0]
+        bodies.append(body)
+    if bodies:
+        if 'watson' in KibbleBit.config:
+            pass # Haven't written this yet
+        elif 'azure' in KibbleBit.config:
+            KPEs = plugins.utils.kpe.azureKPE(KibbleBit, bodies)
+        elif 'picoapi' in KibbleBit.config:
+            KPEs = plugins.utils.kpe.picoKPE(KibbleBit, bodies)
+        if KPEs == False:
+            KibbleBit.pprint("Hit rate limit, not trying further emails for now.")
+            
+        a = 0
+        for hit in hits:
+            kpe = KPEs[a]
+            bid = hit[0]
+            eml = hit[2]
+            a += 1
+            eml['kpe'] = kpe
+            print("Key phrases for %s: %s" % (bid, ", ".join(kpe)))
+            KibbleBit.index('email', bid, eml)
+    else:
+        KibbleBit.pprint("No emails to analyze")
+    KibbleBit.pprint("Done with key phrase extraction")
diff --git a/src/plugins/utils/kpe.py b/src/plugins/utils/kpe.py
new file mode 100644
index 0000000..7985d3e
--- /dev/null
+++ b/src/plugins/utils/kpe.py
@@ -0,0 +1,160 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+ #the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+This is an experimental key phrase extraction plugin for using
+Azure/picoAPI for analyzing the key elements of an email on a list. This
+requires an account with a text analysis service provider, and a
+corresponding API section in config.yaml, as such:
+
+# picoAPI example:
+picoapi:
+    key: abcdef1234567890
+    
+# Azure example:
+azure:
+    apikey: abcdef1234567890
+    location: westeurope
+    
+Currently only pony mail is supported. more to come.
+"""
+
+import time
+import datetime
+import re
+import json
+import hashlib
+import requests
+import json
+import uuid
+
+
+def azureKPE(KibbleBit, bodies):
+    """ KPE using Azure Text Analysis API """
+    if 'azure' in KibbleBit.config:
+        headers = {
+            'Content-Type': 'application/json',
+            'Ocp-Apim-Subscription-Key': KibbleBit.config['azure']['apikey']
+        }
+        
+        
+        js = {
+            "documents": []
+          }
+        
+        # For each body...
+        a = 0
+        KPEs = []
+        for body in bodies:
+            # Crop out quotes
+            lines = body.split("\n")
+            body = "\n".join([x for x in lines if not x.startswith(">")])
+            doc = {
+                "language": "en",
+                "id": str(a),
+                "text": body
+              }
+            js['documents'].append(doc)
+            KPEs.append({}) # placeholder for each doc, to be replaced
+            a += 1
+        try:
+            rv = requests.post(
+                "https://%s.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases" % KibbleBit.config['azure']['location'],
+                headers = headers,
+                data = json.dumps(js)
+            )
+            jsout = rv.json()
+        except:
+            jsout = {} # borked sentiment analysis?
+        
+        if 'documents' in jsout and len(jsout['documents']) > 0:
+            for doc in jsout['documents']:
+                KPEs[int(doc['id'])] = doc['keyPhrases'][:5] # Replace KPEs[X] with the actual phrases, 5 first ones.
+                
+        else:
+            KibbleBit.pprint("Failed to analyze email body.")
+            print(jsout)
+            # Depending on price tier, Azure will return a 429 if you go too fast.
+            # If we see a statusCode return, let's just stop for now.
+            # Later scans can pick up the slack.
+            if 'statusCode' in jsout:
+                KibbleBit.pprint("Possible rate limiting in place, stopping for now.")
+                return False
+        return KPEs
+    
+def picoKPE(KibbleBit, bodies):
+    """ KPE using picoAPI Text Analysis """
+    if 'picoapi' in KibbleBit.config:
+        headers = {
+            'Content-Type': 'application/json',
+            'PicoAPI-Key': KibbleBit.config['picoapi']['key']
+        }
+        
+        
+        js = {
+            "texts": []
+          }
+        
+        # For each body...
+        a = 0
+        KPEs = []
+        for body in bodies:
+            # Crop out quotes
+            lines = body.split("\n")
+            body = "\n".join([x for x in lines if not x.startswith(">")])
+            doc = {
+                "id": str(a),
+                "body": body
+              }
+            js['texts'].append(doc)
+            KPEs.append({}) # placeholder for each doc, to be replaced
+            a += 1
+        try:
+            rv = requests.post(
+                "https://v1.picoapi.com/api/text/keyphrase",
+                headers = headers,
+                data = json.dumps(js)
+            )
+            jsout = rv.json()
+        except:
+            jsout = {} # borked sentiment analysis?
+        
+        if 'results' in jsout and len(jsout['results']) > 0:
+            for doc in jsout['results']:
+                phrases = []
+                # This is a bit different than Azure, in that it has a weighting score
+                # So we need to just extract key phrases above a certain level.
+                # Grab up o 5 key phrases per text
+                MINIMUM_WEIGHT = 0.02
+                for element in doc['keyphrases']:
+                    if element['score'] > MINIMUM_WEIGHT:
+                        phrases.append(element['phrase'])
+                    if len(phrases) == 5:
+                        break
+                KPEs[int(doc['id'])] = phrases # Replace KPEs[X] with the actual phrases
+                
+        else:
+            KibbleBit.pprint("Failed to analyze email body.")
+            print(jsout)
+            # 403 returned on invalid key, 429 on rate exceeded.
+            # If we see a code return, let's just stop for now.
+            # Later scans can pick up the slack.
+            if 'code' in jsout:
+                KibbleBit.pprint("Possible rate limiting in place, stopping for now.")
+                return False
+        return KPEs
+    
\ No newline at end of file

-- 
To stop receiving notification emails like this one, please contact
['"commits@kibble.apache.org" <co...@kibble.apache.org>'].