diff --git a/.travis.yml b/.travis.yml
index 20a262c3657ccc77eebbecf2b823eeb9ac845636..b66f387dad4e108004d406da7828cae9ea16a72b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,27 +1,25 @@
-
-# Set the build language to Python
+sudo: required
+os:
+  - linux
+  dist: Xenial
+  - osx
+   osx_image: xcode7.2
 language: python
+python:
+  - "3.6"
+  - "3.5"
+  - "3.7"
 
-# Set the python version 
-python: "3.5"
-services:
-  - docker
-  
-# get data from open science frame work.
-# get a prebuilt docker environment that supports this work.
-before_install:     
-  - docker pull russelljarvis/science_accessibility:slc  
-  - DATA_URL="https://osf.io/xfzy6/download"
-  - mkdir data_dir && cd data_dir && wget -O - ${DATA_URL} 
-  - echo $pwd
-
-# Run the unit test
-script:
-# show that running the docker container at least works.
-  - docker run -v data_dir:/home/jovyan/SComplexity/Examples/results_dir russelljarvis/science_accessibility:slc python -c "gets here"
-  - docker run -v data_dir:/home/jovyan/SComplexity/Examples/results_dir russelljarvis/science_accessibility:slc python Examples/use_analysis.py
-
-
-
+before_install:
+  - if [ "$TRAVIS_OS_NAME" = "osx" ]; then brew update          ; fi
 
-        
+install:
+  - pip install -r requirements.txt
+  - python setup.py install 
+  - bash install/user_install.sh
+  - python install/align_data_sources.py
+  script: 
+  - python3 unit_test/scrape_test.py
+  - streamlit run app.py
+after_success:
+  - coveralls
diff --git a/Procfile b/Procfile
new file mode 100644
index 0000000000000000000000000000000000000000..a4a9b4850793b6af8996504b2151ef5049793194
--- /dev/null
+++ b/Procfile
@@ -0,0 +1 @@
+web: sh install/setup.sh && streamlit run app.py
\ No newline at end of file
diff --git a/install/gecko_install.sh b/install/gecko_install.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c3ee8c07c03bc60114e579870864dee428495ec8
--- /dev/null
+++ b/install/gecko_install.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+# download and install latest geckodriver for linux or mac.
+# required for selenium to drive a firefox browser.
+
+install_dir="/usr/local/bin"
+json=$(curl -s https://api.github.com/repos/mozilla/geckodriver/releases/latest)
+if [[ $(uname) == "Darwin" ]]; then
+    url=$(echo "$json" | jq -r '.assets[].browser_download_url | select(contains("macos"))')
+elif [[ $(uname) == "Linux" ]]; then
+    url=$(echo "$json" | jq -r '.assets[].browser_download_url | select(contains("linux64"))')
+else
+    echo "can't determine OS"
+    exit 1
+fi
+curl -s -L "$url" | tar -xz
+chmod +x geckodriver
+sudo mv geckodriver "$install_dir"
+echo "installed geckodriver binary in $install_dir"
diff --git a/install/heroku_setup.sh b/install/heroku_setup.sh
new file mode 100644
index 0000000000000000000000000000000000000000..052cd2f6ca5d0d3966a35db2dcfadeca475fda2e
--- /dev/null
+++ b/install/heroku_setup.sh
@@ -0,0 +1,58 @@
+#!/bin/bash
+# https://gist.github.com/mikesmullin/2636776
+#
+# download and install latest geckodriver for linux or mac.
+# required for selenium to drive a firefox browser.
+sudo apt-get update
+sudo apt-get install jq wget chromium-chromedriver
+
+# firefox
+
+#json=$(curl -s https://api.github.com/repos/mozilla/geckodriver/releases/latest)
+#url=$(echo "$json" | jq -r '.assets[].browser_download_url | select(contains("linux64"))')
+#curl -s -L "$url" | tar -xz
+#chmod +x geckodriver
+#sudo cp geckodriver .
+#sudo cp geckodriver ./app
+#export PATH=$PATH:$pwd/geckodriver
+#echo PATH
+
+
+sudo python3 -m pip install -r requirements.txt
+sudo python3 -m pip install seaborn 
+sudo python3 -m pip install bs4
+sudo python3 -m pip install natsort dask plotly
+sudo python3 -c "import nltk; nltk.download('punkt')"
+sudo python3 -c "import nltk; nltk.download('stopwords')"
+
+#git clone https://github.com/ckreibich/scholar.py.git
+
+wget https://www.dropbox.com/s/3h12l5y2pn49c80/traingDats.p?dl=0
+wget https://www.dropbox.com/s/crarli3772rf3lj/more_authors_results.p?dl=0
+wget https://www.dropbox.com/s/x66zf52himmp5ox/benchmarks.p?dl=0
+# sudo apt-get install -y firefox
+#wget https://ftp.mozilla.org/pub/firefox/releases/45.0.2/linux-x86_64/en-GB/firefox-45.0.2.tar.bz2
+#tar xvf firefox-45.0.2.tar.bz2
+#
+#sudo mv /usr/bin/firefox /usr/bin/firefox-backup
+#rm /usr/bin/firefox
+#sudo mv firefox/ /usr/lib/firefox
+#sudo ln -s /usr/lib/firefox /usr/bin/firefox
+
+
+
+#which firefox
+
+mkdir -p ~/.streamlit/
+echo "\
+[general]\n\
+email = \"rjjarvis@asu.edu\"\n\
+" > ~/.streamlit/credentials.toml
+echo "\
+[server]\n\
+headless = true\n\
+enableCORS=false\n\
+port = $PORT\n\
+" > ~/.streamlit/config.toml
+
+
diff --git a/install/install_python3.sh b/install/install_python3.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5a1e89b82b023d69f03d85140f78aa5accb31351
--- /dev/null
+++ b/install/install_python3.sh
@@ -0,0 +1,13 @@
+
+
+
+
+wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh;
+bash miniconda.sh -b -p $HOME/miniconda
+export PATH="$HOME/miniconda/bin:$PATH"
+hash -r
+conda config --set always_yes yes --set changeps1 no
+conda update -q conda
+conda info -a
+pip install -U pip
+
diff --git a/install/part2.sh b/install/part2.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b660b8e3638869842ddad5c3b1aed8c87d2398ab
--- /dev/null
+++ b/install/part2.sh
@@ -0,0 +1,7 @@
+#!/bin/bash
+sudo /opt/conda/bin/pip install --upgrade pip
+sudo /opt/conda/bin/python -m pip install -U pip
+
+pip install -U -r ../requirements.txt
+python -c "import nltk; nltk.download('punkt')"
+python -c "import nltk; nltk.download('stopwords')" 
\ No newline at end of file
diff --git a/install/setup.sh b/install/setup.sh
new file mode 100644
index 0000000000000000000000000000000000000000..387ebe3efcf46f276dfdd575fdbc82d7cc09e7d8
--- /dev/null
+++ b/install/setup.sh
@@ -0,0 +1,37 @@
+#!/bin/bash
+# https://gist.github.com/mikesmullin/2636776
+#
+# download and install latest geckodriver for linux or mac.
+# required for selenium to drive a firefox browser.
+sudo apt-get update
+#sudo apt-get install jq wget chromium-chromedriver firefox
+
+
+sudo python3 -m pip install -r requirements.txt
+sudo python3 -c "import nltk; nltk.download('punkt')"
+sudo python3 -c "import nltk; nltk.download('stopwords')"
+#sudo conda install -c plotly plotly=4.8.1
+#git clone https://github.com/ckreibich/scholar.py.git
+
+wget https://www.dropbox.com/s/3h12l5y2pn49c80/traingDats.p?dl=0
+wget https://www.dropbox.com/s/crarli3772rf3lj/more_authors_results.p?dl=0
+wget https://www.dropbox.com/s/x66zf52himmp5ox/benchmarks.p?dl=0
+# sudo apt-get install -y firefox
+#wget https://ftp.mozilla.org/pub/firefox/releases/45.0.2/linux-x86_64/en-GB/firefox-45.0.2.tar.bz2
+
+sudo python3 install/align_data_sources.py
+sudo python3 setup.py install
+
+mkdir -p ~/.streamlit/
+echo "\
+[general]\n\
+email = \"rjjarvis@asu.edu\"\n\
+" > ~/.streamlit/credentials.toml
+echo "\
+[server]\n\
+headless = true\n\
+enableCORS=false\n\
+port = $PORT\n\
+" > ~/.streamlit/config.toml
+
+
diff --git a/install/user_install.sh b/install/user_install.sh
new file mode 100644
index 0000000000000000000000000000000000000000..cc973c3ae80c08d71bc330ca7bb8f569c04b291f
--- /dev/null
+++ b/install/user_install.sh
@@ -0,0 +1,43 @@
+#!/bin/bash
+# https://gist.github.com/mikesmullin/2636776
+if [[ $(uname) == "Darwin" ]]; then
+    which -s brew
+    if [[ $? != 0 ]] ; then
+        # Install Homebrew
+        ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
+    else
+        brew update
+    fi
+    brew install jq 
+    brew install wget 
+    brew cask install firefox
+    brew install python-lxml
+	# brew install chromium-chromedriver 
+    curl -s -L https://www.dropbox.com/s/3h12l5y2pn49c80/traingDats.p
+    curl -s -L https://www.dropbox.com/s/crarli3772rf3lj/more_authors_results.p?dl=0
+    curl -s -L https://www.dropbox.com/s/x66zf52himmp5ox/benchmarks.p?dl=0
+
+elif [[ $(uname) == "Linux" ]]; then
+    sudo apt-get update
+    sudo apt-get install jq wget firefox
+    sudo apt-get install python-lxml
+    sudo apt-get install -y firefox
+    wget https://www.dropbox.com/s/3h12l5y2pn49c80/traingDats.p?dl=0
+    wget https://www.dropbox.com/s/crarli3772rf3lj/more_authors_results.p?dl=0
+    wget https://www.dropbox.com/s/x66zf52himmp5ox/benchmarks.p?dl=0
+
+else
+    echo "can't determine OS"
+    exit 1
+fi
+
+#which -s pip3
+#if [[ $? != 0 ]] ; then
+#    sudo bash install_python3.sh
+#fi
+
+#which -s python3
+#if [[ $? != 0 ]] ; then
+#    sudo bash install_python3.sh
+#fi
+sudo bash install/gecko_install.sh
diff --git a/science_access/__init__.py b/science_access/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd346c35ac0c19e0ef76b5cb4fc18cddff64c69d
--- /dev/null
+++ b/science_access/__init__.py
@@ -0,0 +1,6 @@
+name = "science_access"
+#from .crawl import *
+from .utils import *
+from .t_analysis import *
+from .scrape import *
+from .crawl import *
diff --git a/science_access/analysis.py b/science_access/analysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..b474149b84e3c4bd1f97c6c7d850be4d904222a9
--- /dev/null
+++ b/science_access/analysis.py
@@ -0,0 +1,64 @@
+
+import glob
+import os
+import dask.bag as db
+
+from SComplexity.utils import html_to_txt, convert_pdf_to_txt
+from SComplexity.t_analysis import text_proc
+
+from natsort import natsorted, ns
+import pprint
+import pickle
+import numpy as np
+import os
+
+
+def print_best_text(f):
+    link_tuple = pickle.load(open(f,'rb'))
+    se_b, page_rank, link, category, buff_ = link_tuple
+    return buff_
+
+
+
+class Analysis(object):
+    def __init__(self,files, min_word_length = 200, urlDats=None):
+        self.files = files
+        self.urlDats = urlDats
+        self.mwl = min_word_length
+
+    def convert_and_score(self,f):
+        urlDat = {}
+        b = os.path.getsize(f)
+        link_tuple = pickle.load(open(f,'rb'))
+        se_b, page_rank, link, category, buff_ = link_tuple
+        if buff_ is not None:
+            urlDat = { 'link':link,'page_rank':page_rank,'se':se_b,'query':category,'file':f }
+            urlDat = text_proc(buff_,urlDat, WORD_LIM = self.mwl)
+        return urlDat
+
+    def cas(self):
+        # Do in parallel as it is 2018
+    
+        pgrid = db.from_sequence(self.files,npartitions=8)
+        urlDats = list(db.map(self.convert_and_score,pgrid).compute())
+        # just kidding need to do a serial debug often times, regardless of parallel speed up.
+        #urlDats = list(map(self.convert_and_score,self.files))
+        urlDats = [ url for url in urlDats if type(url) is not type(None) ]
+        #urlDats = list(filter(lambda url: type(url) != None, urlDats))
+        urlDats = list(filter(lambda url: len(list(url))>3, urlDats))
+
+        urlDats = list(filter(lambda url: len(list(url.keys()))>3, urlDats))
+        # urlDats = list(filter(lambda url: str('penalty') in url.keys(), urlDats))
+        if type(self.urlDats) is not type(None):
+            urlDats.extend(self.urlDats)
+        return urlDats
+
+    def get_reference_web(self):
+        from SComplexity.scrape import SW
+        from SComplexity.get_bmark_corpus import get_bmarks
+        return get_bmarks()
+
+    #def get_reference_pickle(self):
+    #    known_corpus = []
+    #    from SComplexity.get_bmark_corpus import get_bmarks
+    #    return get_bmarks()
diff --git a/science_access/app_backup.py b/science_access/app_backup.py
new file mode 100644
index 0000000000000000000000000000000000000000..010aa439f7cd8f177483d3fd88999266b78ca74b
--- /dev/null
+++ b/science_access/app_backup.py
@@ -0,0 +1,272 @@
+
+
+import streamlit as st
+import os
+
+from selenium import webdriver
+import os
+from selenium.webdriver.firefox.options import Options
+from selenium.common.exceptions import NoSuchElementException
+
+options = Options()
+options.headless = True
+
+try:
+    GECKODRIVER_PATH=str(os.getcwd())+str("/geckodriver")
+    driver = webdriver.Firefox(options=options,executable_path=GECKODRIVER_PATH)
+    st.write('got here')
+except:
+    os.system('wget')
+
+import matplotlib.pyplot as plt
+import seaborn as sns
+from wordcloud import WordCloud
+
+
+import pandas as pd
+import pickle
+import numpy as np
+import plotly.figure_factory as ff
+import os
+import plotly.express as px
+from online_app_backend import call_from_front_end
+from online_app_backend import ar_manipulation
+
+#from plotly.subplots import make_subplots
+
+import nltk
+try:
+    from nltk.corpus import stopwords
+    stop_words = stopwords.words('english')
+except:
+    nltk.download('punkt')
+    nltk.download('stopwords')
+
+if not(os.path.exists('traingDats.p?dl=0') or os.path.exists('data/traingDats.p')):
+
+    os.system('wget https://www.dropbox.com/s/3h12l5y2pn49c80/traingDats.p?dl=0')
+    os.system('wget https://www.dropbox.com/s/x66zf52himmp5ox/benchmarks.p?dl=0')
+
+if os.path.exists("traingDats.p?dl=0") and not os.path.exists("data/traingDats.p"):
+    os.system('mv traingDats.p?dl=0 data/traingDats.p')
+    os.system('mv benchmarks.p?dl=0 data/benchmarks.p')
+
+
+trainingDats = pickle.load(open('data/traingDats.p','rb'))
+bio_chem = [ t['standard'] for t in trainingDats ]
+biochem_labels =  [ x['file_name'] for x in trainingDats if 'file_name' in x.keys()]
+biochem_labels = [x.split("/")[-1] for x in biochem_labels ]
+
+lods = []
+for i,j,k in zip(bio_chem,[str('Comparison Data') for i in range(0,len(bio_chem))],biochem_labels):
+     lods.append({'Reading_Level':i,'Origin':j,'Web_Link':k})
+df0 = pd.DataFrame(lods)
+
+theme = px.colors.diverging.Portland
+colors = [theme[0], theme[1]]
+st.title('Search Reading Difficulty of Academic')
+author_name = st.text_input('Enter Author:')
+def make_clickable(link):
+    # target _blank to open new window
+    # extract clickable text to display for your link
+    text = link#.split('=')[1]
+    return f'<a target="_blank" href="{link}">{text}</a>'
+
+    
+if author_name:
+    ar = call_from_front_end(author_name)
+    standard_sci = [ t['standard'] for t in ar ]
+    group_labels = ['Author: '+str(author_name)]#, 'Group 2', 'Group 3']
+    scraped_labels = [ str(x['link']) for x in ar]
+
+
+    lods = []
+    for i,j,k in zip(standard_sci,[str(author_name) for i in range(0,len(ar))],scraped_labels):
+        lods.append({'Reading_Level':i,'Origin':j,'Web_Link':k})
+    df1 = pd.DataFrame(lods)
+    df = pd.concat([df1,df0])
+
+    fig0 = px.histogram(df, x="Reading_Level", y="Web_Link", color="Origin",
+                    marginal="box",
+                    opacity=0.7,# marginal='violin',# or violin, rug
+                    hover_data=df.columns,
+                    hover_name=df["Web_Link"],
+                    color_discrete_sequence=colors)
+
+    fig0.update_layout(title_text='Scholar scraped {0} Versus Art Corpus'.format(author_name),width=900, height=900)#, hovermode='x')
+            
+    st.write(fig0)
+
+
+else:      
+
+    with open('data/_author_specificSayali Phatak.p','rb') as f: 
+        contents = pickle.load(f)   
+    (NAME,ar,df,datay,scholar_link) =  contents     
+    (ar, trainingDats) = ar_manipulation(ar)
+    standard_sci = [ t['standard'] for t in ar ]
+
+    scraped_labels = [ str(x['link']) for x in ar]
+    group_labels = ['Author Scraped']#, 'Group 2', 'Group 3']
+    lods = []
+    for i,j,k in zip(standard_sci,[str('S Phatak') for i in range(0,len(ar))],scraped_labels):
+        lods.append({'Reading_Level':i,'Origin':j,'Web_Link':k})
+    df1 = pd.DataFrame(lods)
+    df = pd.concat([df1,df0])
+
+
+
+    fig0 = px.histogram(df, x="Reading_Level", y="Web_Link", color="Origin",
+                    marginal="box",
+                    opacity=0.7,# marginal='violin',# or violin, rug
+                    hover_data=df.columns,
+                    hover_name=df["Web_Link"],
+                    color_discrete_sequence=colors)
+
+    fig0.update_layout(title_text='Scholar S Phatak Versus Art Corpus',width=900, height=600)#, hovermode='x')
+            
+    st.write(fig0)
+'''
+
+### Total number scraped documents:
+
+'''
+st.text(len(ar))
+
+if np.mean(standard_sci) < np.mean(bio_chem):
+    '''
+
+
+    ### This author was on average easier to read as the average of ARTCORPUS:
+    A varied collection of biochemistry science papers
+    '''
+
+if np.mean(standard_sci) >= np.mean(bio_chem):
+    '''
+
+
+    ### This author was on average harder or just as hard to read as average of ARTCORPUS:
+    A varied collection of biochemistry science papers
+    '''
+
+
+sci_corpus = ''
+
+for t in ar:
+    if 'tokens' in t.keys():
+        for s in t['tokens']:
+            sci_corpus+=str(' ')+s
+
+
+def art_cloud(acorpus):
+
+    # Generate a word cloud image
+
+    wordcloud = WordCloud().generate(acorpus)
+    fig = plt.figure()
+
+    plt.imshow(wordcloud, interpolation='bilinear')
+    plt.axis("off")
+    st.pyplot()
+
+    return fig
+
+
+'''
+
+
+### Here are some word clouds, that show the frequency of scraped texts
+You can eye ball them to see if they fit your intuition about what your searched author writes about
+'''
+fig = art_cloud(sci_corpus)
+
+
+
+
+
+df_links = pd.DataFrame()
+df_links['Web_Link'] = pd.Series(scraped_labels)
+df_links['Reading_Level'] = pd.Series(standard_sci)
+#st.write(df)
+# link is the column with hyperlinks
+df_links['Web_Link'] = df_links['Web_Link'].apply(make_clickable)
+df_links = df_links.to_html(escape=False)
+st.write(df_links, unsafe_allow_html=True)
+
+x1 = df0['Reading_Level']#np.random.randn(200)
+x2 = df1['Reading_Level']#np.random.randn(200) + 2
+if author_name:
+    group_labels = ['Comparison Data ', str(author_name)]
+else:
+    group_labels = ['Comparison Data ', str('S Phatak')]
+
+
+colors = [theme[-1], theme[-2]]
+rt=list(pd.Series(scraped_labels))
+fig = ff.create_distplot([x1, x2], group_labels, bin_size=2,colors=colors,rug_text=rt)
+
+hover_trace = [t for t in fig['data'] if 'text' in t]
+
+fig.update_layout(title_text='Scholar scraped Author Versus Art Corpus')
+fig.update_layout(width=900, height=600)#, hovermode='x')
+
+st.write(fig)
+
+list_df = pickle.load(open("data/benchmarks.p","rb")) 
+bm = pd.DataFrame(list_df)
+
+bm = bm.rename(columns={'link': 'Web_Link', 'standard': 'Reading_Level'})
+bm["Origin"] = pd.Series(["Benchmark" for i in range(0,len(bm))])
+
+bm = bm.drop(4, axis=0)
+bm = bm.drop(5, axis=0)
+
+bm_temp = pd.DataFrame()
+bm_temp["Origin"] = bm["Origin"]
+bm_temp["Web_Link"] = bm["Web_Link"]
+bm_temp["Reading_Level"] = bm["Reading_Level"]
+import copy
+bm = copy.copy(bm_temp)
+
+bm_temp['Web_Link'] = bm_temp['Web_Link'].apply(make_clickable)
+bm_temp = bm_temp.to_html(escape=False)
+
+'''
+In the table below there are benchmarks texts that are 
+used as a comparison to investigate some very easy to read scientific writing.
+and some very cryptic and unreadable texts too.
+'''
+
+st.write(bm_temp, unsafe_allow_html=True)
+
+x1 = bm['Reading_Level']
+x2 = df1['Reading_Level']
+
+x3 = df0['Reading_Level']
+
+
+rt=list(bm['Web_Link'])
+rt.extend(list(df1['Web_Link']))
+rt.extend(list(df0['Web_Link']))
+
+colors = [theme[0], theme[4],theme[2]]
+if author_name:
+    group_labels = ['Ideal Bench Marks ', str(author_name), str('Comparison Data')]
+else:
+    group_labels = ['Ideal Bench Marks  ', str('S Phatak'), str('Comparison Data')]
+
+fig = ff.create_distplot([x1, x2, x3], group_labels, bin_size=1,colors=colors,rug_text=rt)
+
+hover_trace = [t for t in fig['data'] if 'text' in t]
+
+fig.update_layout(title_text='Benchmarks versus scraped Author')
+fig.update_layout(width=900, height=600)#, hovermode='x')
+
+st.write(fig)
+
+#ARTCORPUS = pickle.load(open('traingDats.p','rb'))
+#acorpus = ''
+#for t in ARTCORPUS:
+#    if 'tokens' in t.keys():
+#        for s in t['tokens']:
+#            acorpus+=str(' ')+s
\ No newline at end of file
diff --git a/science_access/authors.py b/science_access/authors.py
new file mode 100644
index 0000000000000000000000000000000000000000..46a2a49b488e6afd4c70af4c0b23990d019734ea
--- /dev/null
+++ b/science_access/authors.py
@@ -0,0 +1,193 @@
+#import scholar
+#from SComplexity.
+#!pip install -e +git https://github.com/ckreibich/scholar.py
+import sys
+from scholar_scrape import scholar
+import pandas as pd
+
+#sys.version_info[0] == 3:
+unicode = str # pylint: disable-msg=W0622
+encode = lambda s: unicode(s) # pylint: disable-msg=C0103                                                                                                                                                                                '''
+
+def csv(querier, header=False, sep='|'):
+    articles = querier.articles
+    results = []
+    for art in articles:
+        result = art.as_csv(header=header, sep=sep)
+        results.append(result)
+        print(encode(result))
+        header = False
+    return results
+from delver import Crawler
+C = Crawler()
+import requests
+
+from SComplexity.crawl import collect_pubs
+from SComplexity.scholar_scrape import scholar
+
+import io
+
+from delver import Crawler
+C = Crawler()
+import requests
+
+
+import io
+
+import selenium
+
+from selenium import webdriver
+from pyvirtualdisplay import Display
+
+display = Display(visible=0, size=(1024, 768))
+display.start()
+
+
+#from StringIO import StringIO
+
+from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
+from pdfminer.converter import TextConverter
+from pdfminer.layout import LAParams
+from pdfminer.pdfpage import PDFPage
+import os
+import sys, getopt
+from io import StringIO
+
+from selenium.webdriver.firefox.options import Options
+
+import re
+from bs4 import BeautifulSoup
+import bs4 as bs
+import urllib.request
+from io import StringIO
+import io
+
+display = Display(visible=0, size=(1024, 768))
+display.start()
+
+
+from selenium.webdriver.firefox.options import Options
+
+import re
+from bs4 import BeautifulSoup
+
+
+import PyPDF2
+from PyPDF2 import PdfFileReader
+import textract
+
+def html_to_author(content,link):
+    soup = BeautifulSoup(content, 'html.parser')
+
+    page = urllib.request.urlopen(url)
+    soup = BeautifulSoup(page, 'lxml')
+    mydivs = soup.findAll("h3", { "class" : "gsc_1usr_name"})
+    outputFile = open('sample.csv', 'w', newline='')
+    outputWriter = csv.writer(outputFile)
+    for each in mydivs:
+        for anchor in each.find_all('a'):
+            print(anchor.text)
+
+
+    #strip HTML
+    '''
+    for script in soup(["script", "style"]):
+        script.extract()    # rip it out
+    text = soup.get_text()
+    wt = copy.copy(text)
+    #organize text
+    lines = (line.strip() for line in text.splitlines())  # break into lines and remove leading and trailing space on each
+    chunks = (phrase.strip() for line in lines for phrase in line.split("  ")) # break multi-headlines into a line each
+    text = '\n'.join(chunk for chunk in chunks if chunk) # drop blank lines
+    str_text = str(text)
+    '''
+    return str_text
+
+def url_to_text(tuple_link):
+    index,link = tuple_link
+    buff = None
+    #se_b, page_rank, link, category, buff = link_tuple
+    if str('pdf') not in link:
+        if C.open(link) is not None:
+            content = C.open(link).content
+            #print(content)
+            content = requests.get(link, stream=True)
+            buff = html_to_author(content,link)
+            print(buff)
+
+        else:
+            print('problem')
+    else:
+        pass
+        #pdf_file = requests.get(link, stream=True)
+        #f = io.BytesIO(pdf_file.content)
+        #reader = PdfFileReader(f)
+        #buff = reader.getPage(0).extractText().split('\n')
+
+    import pdb; pdb.set_trace()
+    return buff
+
+#@jit
+'''
+def buffer_to_pickle(link_tuple):
+    se_b, page_rank, link, category, buff = link_tuple
+    link_tuple = se_b, page_rank, link, category, buff
+    fname = 'results_dir/{0}_{1}_{2}.p'.format(category,se_b,page_rank)
+    if type(buff) is not None:
+        with open(fname,'wb') as f:
+            pickle.dump(link_tuple,f)
+    return
+'''
+def process(item):
+    text = url_to_text(item)
+
+    #buffer_to_pickle(text)
+    return
+
+
+def search_author(author):
+    # from https://github.com/ckreibich/scholar.py/issues/80
+
+    querier = scholar.ScholarQuerier()
+    settings = scholar.ScholarSettings()
+    querier.apply_settings(settings)
+    query = scholar.SearchScholarQuery()
+
+    query.set_words(str('author:')+author)
+    querier.send_query(query)
+    #results0 = csv(querier)
+    #results1 = citation_export(querier)
+    links = [ a.attrs['url'][0] for a in querier.articles if a.attrs['url'][0] is not None ]
+    sp = scholar.ScholarArticleParser()
+    #sp._parse_article(links[0])
+    #[ process((index,l)) for index,l in enumerate(links) ]
+    import pdb
+    pdb.set_trace()
+    return links#, results1, links
+
+links = search_author('R Gerkin')
+
+
+print(links)
+
+
+'''
+NUM_LINKS but can't be bothered refactoring.
+def search_scholar(get_links):
+    # from https://github.com/ckreibich/scholar.py/issues/80
+    se_,index,category,category,buff = get_links
+    querier = scholar.ScholarQuerier()
+    settings = scholar.ScholarSettings()
+    querier.apply_settings(settings)
+    query = scholar.SearchScholarQuery()
+
+    query.set_words(category)
+    querier.send_query(query)
+    links = [ a.attrs['url'][0] for a in querier.articles if a.attrs['url'][0] is not None ]
+    #links = query.get_url()
+    #print(links)
+    #if len(links) > NUM_LINKS: links = links[0:NUM_LINKS]
+
+    [ process((se_,index,l,category,buff)) for index,l in enumerate(links) ]
+
+'''
diff --git a/science_access/crawl.py b/science_access/crawl.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd60c7bd81b4fa8dccd175fbabd4f6c4e25abf7e
--- /dev/null
+++ b/science_access/crawl.py
@@ -0,0 +1,214 @@
+
+## A lot of this code is informed by this multi-threading of web-grabbing example:
+# https://github.com/NikolaiT/GoogleScraper/blob/master/Examples/image_search.py
+# Probably the parallel architecture sucks, probably dask.bag mapping would be more readable and efficient.
+##
+#import threading,requests, os, urllib
+from bs4 import BeautifulSoup
+from natsort import natsorted, ns
+import glob
+import requests
+import os
+
+import selenium
+#from pyvirtualdisplay import Display
+from selenium import webdriver
+
+
+
+import pandas as pd
+import pycld2 as cld2
+
+
+import pdfminer
+from pdfminer.pdfparser import PDFParser
+from pdfminer.pdfdocument import PDFDocument
+from pdfminer.pdfpage import PDFPage
+from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
+from pdfminer.pdfdevice import PDFDevice
+from pdfminer.layout import LAParams
+from pdfminer.converter import  TextConverter
+
+import re
+import numpy as np
+
+
+from bs4 import BeautifulSoup
+import bs4 as bs
+import urllib.request
+
+from delver import Crawler
+C = Crawler()
+CWD = os.getcwd()
+
+from io import StringIO
+import io
+
+
+rsrcmgr = PDFResourceManager()
+retstr = StringIO()
+laparams = LAParams()
+codec = 'utf-8'
+device = TextConverter(rsrcmgr, retstr, laparams = laparams)
+interpreter = PDFPageInterpreter(rsrcmgr, device)
+
+
+
+def convert_pdf_to_txt(content):
+    try:
+        pdf = io.BytesIO(content.content)
+    except:
+        pdf = io.BytesIO(content)
+    parser = PDFParser(pdf)
+    document = PDFDocument(parser, password=None) # this fails
+    write_text = ''
+    for page in PDFPage.create_pages(document):
+        interpreter.process_page(page)
+        write_text +=  retstr.getvalue()
+        #write_text = write_text.join(retstr.getvalue())
+    # Process all pages in the document
+    text = str(write_text)
+    return text
+
+def html_to_txt(content):
+    soup = BeautifulSoup(content, 'html.parser')
+    #strip HTML
+    for script in soup(["script", "style"]):
+        script.extract()    # rip it out
+    text = soup.get_text()
+    #organize text
+    lines = (line.strip() for line in text.splitlines())  # break into lines and remove leading and trailing space on each
+    chunks = (phrase.strip() for line in lines for phrase in line.split("  ")) # break multi-headlines into a line each
+    text = '\n'.join(chunk for chunk in chunks if chunk) # drop blank lines
+    str_text = str(text)
+    return str_text
+
+def print_best_text(fileName):
+    file = open(fileName)
+
+    return text
+
+def denver_to_text(url):
+    fileName = C.download(local_path=CWD, url=url, name='temp_file')
+    file = open(fileName)
+    if str('.html') in fileName:
+        text = html_to_txt(file)
+    else:
+        text = convert_pdf_to_txt(file)
+    file.close()
+    return text
+
+def collect_hosted_files(url):
+    '''
+    Used for scholar
+    '''
+    #print(url)
+    try:
+        crude_html = denver_to_text(url)
+    except:
+        driver.get(url)
+        crude_html = driver.page_source
+    #soup0 = BeautifulSoup(crude_html, 'html.parser')
+    soup = BeautifulSoup(crude_html, 'lxml')
+    links = []
+    print(soup)
+    for link in soup.findAll('a'):check_out = link.get('href');links.append(check_out)
+        #print(link)
+    for link in soup.findAll('a', attrs={'href': re.compile("https://")}):
+        check_out = link.get('href')
+        #if '/citations?' in check_out:
+        links.append(check_out)
+    for link in soup.findAll('a', attrs={'href': re.compile("http://")}):
+        check_out = link.get('href')
+        #if '/citations?' in check_out:
+        links.append(check_out)
+
+    return links
+
+if 'DYNO' in os.environ:
+    heroku = True
+    from selenium.webdriver.support.ui import WebDriverWait
+    from selenium.webdriver.support import expected_conditions as EC
+else:
+    heroku = False
+from selenium.common.exceptions import NoSuchElementException
+import os
+from selenium import webdriver
+
+def get_driver():
+    if 'DYNO' in os.environ:
+        heroku = True
+    else:
+        heroku = False
+    from selenium.webdriver.firefox.options import Options
+
+    options = Options()
+    options.add_argument("--headless")
+    options.add_argument("--disable-dev-shm-usage")
+    options.add_argument("--no-sandbox")
+    try:
+        driver = webdriver.Firefox(options=options)
+    except:
+        try:
+            options.binary_location = "/app/vendor/firefox/firefox"
+            driver = webdriver.Firefox(options=options)
+            GECKODRIVER_PATH=str(os.getcwd())+str("/geckodriver")
+            driver = webdriver.Firefox(options=options,executable_path=GECKODRIVER_PATH)
+        except:
+            try:
+                chrome_options = webdriver.ChromeOptions()
+                chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
+                chrome_options.add_argument("--headless")
+                chrome_options.add_argument("--disable-dev-shm-usage")
+                chrome_options.add_argument("--no-sandbox")
+                driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options)
+            except:
+                try:
+                    GECKODRIVER_PATH=str(os.getcwd())+str("/geckodriver")
+                    options.binary_location = str('./firefox')
+                    driver = webdriver.Firefox(options=options,executable_path=GECKODRIVER_PATH)
+                except:
+                    os.system("wget wget https://ftp.mozilla.org/pub/firefox/releases/45.0.2/linux-x86_64/en-GB/firefox-45.0.2.tar.bz2")
+                    os.system("wget https://github.com/mozilla/geckodriver/releases/download/v0.26.0/geckodriver-v0.26.0-linux64.tar.gz")
+                    os.system("tar -xf geckodriver-v0.26.0-linux64.tar.gz")
+                    os.system("tar xvf firefox-45.0.2.tar.bz2")
+                    GECKODRIVER_PATH=str(os.getcwd())+str("/geckodriver")
+                    options.binary_location = str('./firefox')
+                    driver = webdriver.Firefox(options=options,executable_path=GECKODRIVER_PATH)
+    return driver
+from time import sleep
+import numpy as np
+
+
+def collect_pubs(url):
+    '''
+    Used for scholar which is only html
+    '''
+    # import needs to be inside function  to protect scope.
+
+    driver = get_driver()
+    if heroku:
+        sleep(np.random.uniform(1,3))
+
+        #wait = WebDriverWait(driver, 10)
+        #wait.until(EC.url_changes(url))
+        driver.get(url)
+    else:
+        driver.get(url)
+    crude_html = driver.page_source
+
+    soup = BeautifulSoup(crude_html, 'html.parser')
+    links = []
+    for link in soup.findAll('a', attrs={'href': re.compile("https://")}):
+        check_out = link.get('href')
+        #if '/citations?' in check_out:
+        links.append(check_out)
+    for link in soup.findAll('a', attrs={'href': re.compile("http://")}):
+        check_out = link.get('href')
+        #if '/citations?' in check_out:
+        links.append(check_out)
+    driver.close()
+    driver.quit() 
+    driver = None
+    del driver
+    return links
diff --git a/science_access/enter_author_name.py b/science_access/enter_author_name.py
new file mode 100644
index 0000000000000000000000000000000000000000..26512ecb212da5e503eea70992544c34590d8dd9
--- /dev/null
+++ b/science_access/enter_author_name.py
@@ -0,0 +1,30 @@
+#SComplexity.t_analysis
+from SComplexity import online_app_backend
+import argparse
+'''
+parser = argparse.ArgumentParser(description='Process some authors.')
+
+parser.add_argument("-H", "--Help", help = "Example: Help argument", required = False, default = "")
+
+parser.add_argument('author','--a',metavar='N', type=str, nargs='+',required=True,help='authors first name')
+parser.add_argument('t','--t', metavar='N', type=str, nargs='+',help='boolean to select a tournment between authors')
+
+parser.add_argument('a2', metavar='N', type=str, nargs='+',help='second author',required=False)
+parser.add_argument('v','--verbose', help='Print more data',action='store_true',required=False)
+parser.add_argument('an','--anonymize', help='Anonymize loosing author or both authors in competition plot',action='store_true',default="True",required=False)
+args = parser.parse_args()
+NAME = args.author
+TOUR = args.t
+author2 = args.a2
+verbose = args.v
+anon = args.an
+print(NAME)
+'''
+TOUR = False
+if TOUR:
+    NAME1 = args.author1
+    online_app_backend.call_from_front_end(NAME,NAME1=author2,tour=TOUR,anon=anon,verbose=verbose)
+else:
+    NAME = "S S Phatak"
+    verbose = False
+    online_app_backend.call_from_front_end(NAME,verbose=verbose)
diff --git a/science_access/get_bmark_corpus.py b/science_access/get_bmark_corpus.py
new file mode 100644
index 0000000000000000000000000000000000000000..b02a6b6091ed5d810d515303373d8a51830c4342
--- /dev/null
+++ b/science_access/get_bmark_corpus.py
@@ -0,0 +1,156 @@
+import os
+import os.path
+import pickle
+
+import dask.bag as db
+import numpy as np
+import requests
+from bs4 import BeautifulSoup
+
+from .crawl import collect_pubs, convert_pdf_to_txt#,process
+from .scrape import get_driver
+from .t_analysis import text_proc
+from .utils import black_string
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support.ui import WebDriverWait
+if 'DYNO' in os.environ:
+    heroku = False
+else:
+    heroku = True
+def process(link):
+    urlDat = {}
+
+    if heroku:
+        wait = WebDriverWait(driver, 10)
+        wait.until(lambda driver: driver.current_url != link)
+        link = cddriver.current_url
+    if str('pdf') not in link:
+        driver = get_driver()
+        driver.get(link)
+ 
+        crude_html = driver.page_source
+
+        soup = BeautifulSoup(crude_html, 'html.parser')
+        for script in soup(["script", "style"]):
+            script.extract()    # rip it out
+        text = soup.get_text()
+        #wt = copy.copy(text)
+        #organize text
+        lines = (line.strip() for line in text.splitlines())  # break into lines and remove leading and trailing space on each
+        chunks = (phrase.strip() for line in lines for phrase in line.split("  ")) # break multi-headlines into a line each
+        text = '\n'.join(chunk for chunk in chunks if chunk) # drop blank lines
+        buffered = str(text)
+    else:
+        pdf_file = requests.get(link, stream=True)
+        buffered = convert_pdf_to_txt(pdf_file)
+    urlDat['link'] = link
+    urlDat['page_rank'] = 'benchmark'    
+    urlDat = text_proc(buffered,urlDat)
+    driver.close()
+    driver.quit() 
+    driver = None
+    del driver
+    
+    return urlDat
+
+#try:
+#    assert os.path.isfile('../BenchmarkCorpus/benchmarks.p')
+#    with open('../BenchmarkCorpus/benchmarks.p','rb') as f:
+#        urlDats = pickle.load(f)
+#except:
+
+def mess_length(word_length,bcm):
+    with open('bcm.p','rb') as f:
+        big_complex_mess = pickle.load(big_complex_mess,f)
+    reduced = big_complex_mess[0:word_length]
+    urlDat = {}
+    pmegmess = text_proc(reduced,urlDat)
+    return mess_length, pmegmess
+"""
+def get_greg_nicholas():
+    urlDat = {}
+    urlDat['link'] = "nicholas"
+    urlDat['page_rank'] = 'nicholas'
+    #pdf_file = requests.get(link, stream=True)
+    #bufferd = convert_pdf_to_txt(pdf_file)
+    #File_object = open(r"local_text.txt","Access_Mode")
+    file1 = open("local_text.txt","r") 
+    txt = file1.readlines()
+    new_str = ''
+    for i in txt:
+        new_str+=str(i)
+    urlDat = text_proc(new_str,urlDat)
+    print(urlDat)
+    #add to benchmarks
+    with open('benchmarks.p','rb') as f:
+        urlDats = pickle.load(f)
+    urlDats.append(urlDat)
+    with open('benchmarks.p','wb') as f:
+        pickle.dump(urlDats,f)
+
+    return urlDat
+"""
+
+def get_bmarks():
+    xkcd_self_sufficient = str('http://splasho.com/upgoer5/library.php')
+    high_standard = str('https://elifesciences.org/download/aHR0cHM6Ly9jZG4uZWxpZmVzY2llbmNlcy5vcmcvYXJ0aWNsZXMvMjc3MjUvZWxpZmUtMjc3MjUtdjIucGRm/elife-27725-v2.pdf?_hash=WA%2Fey48HnQ4FpVd6bc0xCTZPXjE5ralhFP2TaMBMp1c%3D')
+    the_science_of_writing = str('https://cseweb.ucsd.edu/~swanson/papers/science-of-writing.pdf')
+    pmeg = str('http://www.elsewhere.org/pomo/') # Note this is so obfuscated, even the english language classifier rejects it.
+    this_manuscript = str('https://www.overleaf.com/read/dqkttvmqjvhn')
+    this_readme = str('https://github.com/russelljjarvis/ScienceAccessibility')
+    links = [xkcd_self_sufficient,high_standard,the_science_of_writing,this_manuscript,this_readme ]
+    urlDats = list(map(process,links))
+
+    pmegs = []
+    for i in range(0,9):
+       p = process(pmeg)
+       if p is not None:
+           pmegs.append(p) # grab this constantly changing page 10 times to get the mean value.
+    if pmegs[0] is not None:
+        urlDats.append(process(pmegs[0]))
+    big_complex_mess = ''
+    urlDat = {}
+    for p in pmegs:
+        if p is not None:
+            for s in p['tokens']:
+                big_complex_mess += s+str(' ')
+    bcm = ''
+    for p in pmegs[0:2]:
+        if p is not None:
+            for s in p['tokens']:
+                bcm += s+str(' ')
+
+    pmegmess_2 = text_proc(bcm,urlDat)
+    #import pdb; pdb.set_trace()
+    with open('bcm.p','wb') as f:
+        pickle.dump(big_complex_mess,f)
+
+    urlDats[-1]['standard'] = np.mean([p['standard'] for p in pmegs])
+    #import pdb
+    #pdb.set_trace()
+    urlDats[-1]['sp'] = np.mean([p['sp'] for p in pmegs])
+    urlDats[-1]['gf'] = np.mean([p['gf'] for p in pmegs])
+    with open('benchmarks.p','wb') as f:
+        pickle.dump(urlDats,f)
+
+    return urlDats
+
+
+def check_self_contained(file_name):
+    royal = '../BenchmarkCorpus/' +str(file_name)
+    klpdr = open(royal)
+    strText = klpdr.read()
+    urlDat = {'link':'local_resource_royal'}
+    klpdfr = text_proc(strText,urlDat, WORD_LIM = 100)
+    return klpdfr
+
+
+def getText(filename):
+    # convert docx files.
+    # https://stackoverflow.com/questions/44741226/converting-docx-to-pure-text
+    doc = docx.Document(filename)
+    fullText = []
+    for para in doc.paragraphs:
+        txt = para.text.encode('ascii', 'ignore')
+        fullText.append(txt)
+    return '\n'.join(fullText)
diff --git a/science_access/online_app_backend.py b/science_access/online_app_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..113a7edea13dd6c407b52bde3fc56d3b0425f606
--- /dev/null
+++ b/science_access/online_app_backend.py
@@ -0,0 +1,203 @@
+import copy
+import matplotlib.pyplot as plt
+import seaborn as sns
+import os.path
+import pdb
+import pickle
+from collections import OrderedDict
+
+import IPython.display as d
+import numpy as np
+import pandas as pd
+from bs4 import BeautifulSoup
+
+from .crawl import collect_pubs
+from .get_bmark_corpus import process
+from .t_analysis import text_proc
+from .t_analysis import text_proc, perplexity, unigram_zipf
+
+import streamlit as st
+
+if 'DYNO' in os.environ:
+    heroku = True
+else:
+    heroku = False
+from time import sleep
+import numpy as np
+
+
+def metricss(rg):
+    if isinstance(rg,list):
+        pub_count = len(rg)
+        mean_standard = np.mean([ r['standard'] for r in rg if 'standard' in r.keys()])
+        return mean_standard
+    else:
+        return None
+def metricsp(rg):
+    if isinstance(rg,list):
+        pub_count = len(rg)
+        penalty = np.mean([ r['penalty'] for r in rg if 'penalty' in r.keys()])
+        penalty = np.mean([ r['perplexity'] for r in rg if 'perplexity' in r.keys() ])
+
+        return penalty
+    else:
+        return None
+
+def filter_empty(the_list):
+    the_list = [ tl for tl in the_list if tl is not None ]
+    the_list = [ tl for tl in the_list if type(tl) is not type(str('')) ]
+
+    return [ tl for tl in the_list if 'standard' in tl.keys() ]
+
+from tqdm import tqdm
+import streamlit as st
+
+
+class tqdm:
+    def __init__(self, iterable, title=None):
+        if title:
+            st.write(title)
+        self.prog_bar = st.progress(0)
+        self.iterable = iterable
+        self.length = len(iterable)
+        self.i = 0
+
+    def __iter__(self):
+        for obj in self.iterable:
+            yield obj
+            self.i += 1
+            current_prog = self.i / self.length
+            self.prog_bar.progress(current_prog)
+
+
+def take_url_from_gui(author_link_scholar_link_list):
+    '''
+    inputs a URL that's full of publication orientated links, preferably the
+    authors scholar page.
+    '''
+    author_results = []
+    if heroku:
+        follow_links = collect_pubs(author_link_scholar_link_list)[3:25]
+    else:
+        follow_links = collect_pubs(author_link_scholar_link_list)[0:15]
+
+    for r in tqdm(follow_links,title='Progess of scraping'):
+  
+        try:
+            urlDat = process(r)
+        except:
+            follow_more_links = collect_pubs(r)
+            for r in tqdm(follow_more_links,title='Progess of scraping'):
+                if heroku:
+                    sleep(np.random.uniform(1,3))
+                urlDat = process(r)        
+        if not isinstance(urlDat,type(None)):
+            author_results.append(urlDat)
+    return author_results
+
+def unigram_model(author_results):
+    '''
+    takes author results.
+    '''
+    terms = []
+    for k,v in author_results.items():
+        try:
+            #author_results_r[k] = list(s for s in v.values()  )
+            author_results[k]['files'] = list(s for s in v.values()  )
+
+            words = [ ws['tokens'] for ws in author_results[k]['files'] if ws is not None ]
+            author_results[k]['words'] = words
+            terms.extend(words)# if isinstance(terms,dict) ]
+        except:
+            print(terms[-1])
+    big_model = unigram(terms)
+    with open('author_results_processed.p','wb') as file:
+        pickle.dump(author_results,file)
+    with open('big_model_science.p','wb') as file:
+        pickle.dump(list(big_model),file)
+
+    return big_model
+
+def info_models(author_results):
+    big_model = unigram_model(author_results)
+    compete_results = {}
+    for k,v in author_results.items():
+        per_dpc = []
+        try:
+            for doc in author_results[k]['words']:
+                per_doc.append(perplexity(doc, big_model))
+        except:
+            pass
+        compete_results[k] = np.mean(per_doc)
+        author_results[k]['perplexity'] = compete_results[k]
+    return author_results, compete_results
+
+
+
+def update_web_form(url):
+    author_results = take_url_from_gui(url)
+    ar =  copy.copy(author_results)
+    datax = filter_empty(ar)
+    datay = metricss(ar)
+    df = pd.DataFrame(datax)
+    return df, datay, author_results
+
+def enter_name_here(scholar_page, name):
+    df, datay, author_results = update_web_form(scholar_page)
+    return df, datay, author_results
+
+def find_nearest(array, value):
+    array = np.asarray(array)
+    idx = (np.abs(array - value)).argmin()
+    return idx
+
+def ar_manipulation(ar):
+    ar = [ tl for tl in ar if tl is not None ]
+    ar = [ tl for tl in ar if type(tl) is not type(str('')) ]
+    ar = [ tl for tl in ar if 'standard' in tl.keys() ]
+
+    with open('data/traingDats.p','rb') as f:
+        trainingDats = pickle.load(f)
+        
+    trainingDats.extend(ar)
+    return (ar, trainingDats)
+
+import os
+from crossref_commons.iteration import iterate_publications_as_json
+import requests
+def call_from_front_end(NAME):
+    if not heroku:
+        scholar_link=str('https://scholar.google.com/scholar?hl=en&as_sdt=0%2C3&q=')+str(NAME)
+        #for link in scholar_link:
+        #    st.text(link) 
+
+        _, _, ar  = enter_name_here(scholar_link,NAME)
+
+
+    if heroku:
+        filter_ = {'type': 'journal-article'}
+        queries = {'query.author': NAME}
+        ar = []
+        bi =[p for p in iterate_publications_as_json(max_results=50, filter=filter_, queries=queries)]   
+        for p in bi[0:9]:    
+            res = str('https://api.unpaywall.org/v2/')+str(p['DOI'])+str('?email=YOUR_EMAIL')
+            response = requests.get(res)
+            temp = response['best_oa_location']['url_for_pdf']
+
+            #temp=str('https://unpaywall.org/'+str(p['DOI'])) 
+            #st.text(temp) 
+            urlDat = process(temp)        
+            if not isinstance(urlDat,type(None)):
+                ar.append(urlDat)
+                #st.text(urlDat) 
+
+
+    (ar, trainingDats) = ar_manipulation(ar)
+    '''
+    with open('data/traingDats.p','rb') as f:            
+        trainingDats_old = pickle.load(f)
+    trainingDats.extend(trainingDats_old)    
+    with open('data/traingDats.p','wb') as f:            
+        pickle.dump(trainingDats,f)        
+    '''
+    return ar
diff --git a/science_access/scholar.py b/science_access/scholar.py
new file mode 100755
index 0000000000000000000000000000000000000000..13ccd4394b714b68d7245a22e4bcb8106887c30b
--- /dev/null
+++ b/science_access/scholar.py
@@ -0,0 +1,1310 @@
+#! /usr/bin/env python
+"""
+This module provides classes for querying Google Scholar and parsing
+returned results. It currently *only* processes the first results
+page. It is not a recursive crawler.
+"""
+# ChangeLog
+# ---------
+#
+# 2.11  The Scholar site seems to have become more picky about the
+#       number of results requested. The default of 20 in scholar.py
+#       could cause HTTP 503 responses. scholar.py now doesn't request
+#       a maximum unless you provide it at the comment line. (For the
+#       time being, you still cannot request more than 20 results.)
+#
+# 2.10  Merged a fix for the "TypError: quote_from_bytes()" problem on
+#       Python 3.x from hinnefe2.
+#
+# 2.9   Fixed Unicode problem in certain queries. Thanks to smidm for
+#       this contribution.
+#
+# 2.8   Improved quotation-mark handling for multi-word phrases in
+#       queries. Also, log URLs %-decoded in debugging output, for
+#       easier interpretation.
+#
+# 2.7   Ability to extract content excerpts as reported in search results.
+#       Also a fix to -s|--some and -n|--none: these did not yet support
+#       passing lists of phrases. This now works correctly if you provide
+#       separate phrases via commas.
+#
+# 2.6   Ability to disable inclusion of patents and citations. This
+#       has the same effect as unchecking the two patents/citations
+#       checkboxes in the Scholar UI, which are checked by default.
+#       Accordingly, the command-line options are --no-patents and
+#       --no-citations.
+#
+# 2.5:  Ability to parse global result attributes. This right now means
+#       only the total number of results as reported by Scholar at the
+#       top of the results pages (e.g. "About 31 results"). Such
+#       global result attributes end up in the new attrs member of the
+#       used ScholarQuery class. To render those attributes, you need
+#       to use the new --txt-globals flag.
+#
+#       Rendering global results is currently not supported for CSV
+#       (as they don't fit the one-line-per-article pattern). For
+#       grepping, you can separate the global results from the
+#       per-article ones by looking for a line prefix of "[G]":
+#
+#       $ scholar.py --txt-globals -a "Einstein"
+#       [G]    Results 11900
+#
+#                Title Can quantum-mechanical description of physical reality be considered complete?
+#                  URL http://journals.aps.org/pr/abstract/10.1103/PhysRev.47.777
+#                 Year 1935
+#            Citations 12804
+#             Versions 80
+#              Cluster ID 8174092782678430881
+#       Citations list http://scholar.google.com/scholar?cites=8174092782678430881&as_sdt=2005&sciodt=0,5&hl=en
+#        Versions list http://scholar.google.com/scholar?cluster=8174092782678430881&hl=en&as_sdt=0,5
+#
+# 2.4:  Bugfixes:
+#
+#       - Correctly handle Unicode characters when reporting results
+#         in text format.
+#
+#       - Correctly parse citation-only (i.e. linkless) results in
+#         Google Scholar results.
+#
+# 2.3:  Additional features:
+#
+#       - Direct extraction of first PDF version of an article
+#
+#       - Ability to pull up an article cluster's results directly.
+#
+#       This is based on work from @aliparsai on GitHub -- thanks!
+#
+#       - Suppress missing search results (so far shown as "None" in
+#         the textual output form.
+#
+# 2.2:  Added a logging option that reports full HTML contents, for
+#       debugging, as well as incrementally more detailed logging via
+#       -d up to -dddd.
+#
+# 2.1:  Additional features:
+#
+#       - Improved cookie support: the new --cookie-file options
+#         allows the reuse of a cookie across invocations of the tool;
+#         this allows higher query rates than would otherwise result
+#         when invoking scholar.py repeatedly.
+#
+#       - Workaround: remove the num= URL-encoded argument from parsed
+#         URLs. For some reason, Google Scholar decides to propagate
+#         the value from the original query into the URLs embedded in
+#         the results.
+#
+# 2.0:  Thorough overhaul of design, with substantial improvements:
+#
+#       - Full support for advanced search arguments provided by
+#         Google Scholar
+#
+#       - Support for retrieval of external citation formats, such as
+#         BibTeX or EndNote
+#
+#       - Simple logging framework to track activity during execution
+#
+# 1.7:  Python 3 and BeautifulSoup 4 compatibility, as well as printing
+#       of usage info when no options are given. Thanks to Pablo
+#       Oliveira (https://github.com/pablooliveira)!
+#
+#       Also a bunch of pylinting and code cleanups.
+#
+# 1.6:  Cookie support, from Matej Smid (https://github.com/palmstrom).
+#
+# 1.5:  A few changes:
+#
+#       - Tweak suggested by Tobias Isenberg: use unicode during CSV
+#         formatting.
+#
+#       - The option -c|--count now understands numbers up to 100 as
+#         well. Likewise suggested by Tobias.
+#
+#       - By default, text rendering mode is now active. This avoids
+#         confusion when playing with the script, as it used to report
+#         nothing when the user didn't select an explicit output mode.
+#
+# 1.4:  Updates to reflect changes in Scholar's page rendering,
+#       contributed by Amanda Hay at Tufts -- thanks!
+#
+# 1.3:  Updates to reflect changes in Scholar's page rendering.
+#
+# 1.2:  Minor tweaks, mostly thanks to helpful feedback from Dan Bolser.
+#       Thanks Dan!
+#
+# 1.1:  Made author field explicit, added --author option.
+#
+# Don't complain about missing docstrings: pylint: disable-msg=C0111
+#
+# Copyright 2010--2017 Christian Kreibich. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+#    1. Redistributions of source code must retain the above copyright
+#       notice, this list of conditions and the following disclaimer.
+#
+#    2. Redistributions in binary form must reproduce the above
+#       copyright notice, this list of conditions and the following
+#       disclaimer in the documentation and/or other materials provided
+#       with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT,
+# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+import optparse
+import os
+import re
+import sys
+import warnings
+
+try:
+    # Try importing for Python 3
+    # pylint: disable-msg=F0401
+    # pylint: disable-msg=E0611
+    from urllib.request import HTTPCookieProcessor, Request, build_opener
+    from urllib.parse import quote, unquote
+    from http.cookiejar import MozillaCookieJar
+except ImportError:
+    # Fallback for Python 2
+    from urllib2 import Request, build_opener, HTTPCookieProcessor
+    from urllib import quote, unquote
+    from cookielib import MozillaCookieJar
+
+# Import BeautifulSoup -- try 4 first, fall back to older
+try:
+    from bs4 import BeautifulSoup
+except ImportError:
+    try:
+        from BeautifulSoup import BeautifulSoup
+    except ImportError:
+        print('We need BeautifulSoup, sorry...')
+        sys.exit(1)
+
+# Support unicode in both Python 2 and 3. In Python 3, unicode is str.
+if sys.version_info[0] == 3:
+    unicode = str # pylint: disable-msg=W0622
+    encode = lambda s: unicode(s) # pylint: disable-msg=C0103
+else:
+    def encode(s):
+        if isinstance(s, basestring):
+            return s.encode('utf-8') # pylint: disable-msg=C0103
+        else:
+            return str(s)
+
+
+class Error(Exception):
+    """Base class for any Scholar error."""
+
+
+class FormatError(Error):
+    """A query argument or setting was formatted incorrectly."""
+
+
+class QueryArgumentError(Error):
+    """A query did not have a suitable set of arguments."""
+
+
+class SoupKitchen(object):
+    """Factory for creating BeautifulSoup instances."""
+
+    @staticmethod
+    def make_soup(markup, parser=None):
+        """Factory method returning a BeautifulSoup instance. The created
+        instance will use a parser of the given name, if supported by
+        the underlying BeautifulSoup instance.
+        """
+        if 'bs4' in sys.modules:
+            # We support parser specification. If the caller didn't
+            # specify one, leave it to BeautifulSoup to pick the most
+            # suitable one, but suppress the user warning that asks to
+            # select the most suitable parser ... which BS then
+            # selects anyway.
+            if parser is None:
+                warnings.filterwarnings('ignore', 'No parser was explicitly specified')
+            return BeautifulSoup(markup, parser)
+
+        return BeautifulSoup(markup)
+
+class ScholarConf(object):
+    """Helper class for global settings."""
+
+    VERSION = '2.10'
+    LOG_LEVEL = 1
+    MAX_PAGE_RESULTS = 10 # Current default for per-page results
+    SCHOLAR_SITE = 'http://scholar.google.com'
+
+    # USER_AGENT = 'Mozilla/5.0 (X11; U; FreeBSD i386; en-US; rv:1.9.2.9) Gecko/20100913 Firefox/3.6.9'
+    # Let's update at this point (3/14):
+    USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/27.0'
+
+    # If set, we will use this file to read/save cookies to enable
+    # cookie use across sessions.
+    COOKIE_JAR_FILE = None
+
+class ScholarUtils(object):
+    """A wrapper for various utensils that come in handy."""
+
+    LOG_LEVELS = {'error': 1,
+                  'warn':  2,
+                  'info':  3,
+                  'debug': 4}
+
+    @staticmethod
+    def ensure_int(arg, msg=None):
+        try:
+            return int(arg)
+        except ValueError:
+            raise FormatError(msg)
+
+    @staticmethod
+    def log(level, msg):
+        if level not in ScholarUtils.LOG_LEVELS.keys():
+            return
+        if ScholarUtils.LOG_LEVELS[level] > ScholarConf.LOG_LEVEL:
+            return
+        sys.stderr.write('[%5s]  %s' % (level.upper(), msg + '\n'))
+        sys.stderr.flush()
+
+
+class ScholarArticle(object):
+    """
+    A class representing articles listed on Google Scholar.  The class
+    provides basic dictionary-like behavior.
+    """
+    def __init__(self):
+        # The triplets for each keyword correspond to (1) the actual
+        # value, (2) a user-suitable label for the item, and (3) an
+        # ordering index:
+        self.attrs = {
+            'title':         [None, 'Title',          0],
+            'url':           [None, 'URL',            1],
+            'year':          [None, 'Year',           2],
+            'num_citations': [0,    'Citations',      3],
+            'num_versions':  [0,    'Versions',       4],
+            'cluster_id':    [None, 'Cluster ID',     5],
+            'url_pdf':       [None, 'PDF link',       6],
+            'url_citations': [None, 'Citations list', 7],
+            'url_versions':  [None, 'Versions list',  8],
+            'url_citation':  [None, 'Citation link',  9],
+            'excerpt':       [None, 'Excerpt',       10],
+        }
+
+        # The citation data in one of the standard export formats,
+        # e.g. BibTeX.
+        self.citation_data = None
+
+    def __getitem__(self, key):
+        if key in self.attrs:
+            return self.attrs[key][0]
+        return None
+
+    def __len__(self):
+        return len(self.attrs)
+
+    def __setitem__(self, key, item):
+        if key in self.attrs:
+            self.attrs[key][0] = item
+        else:
+            self.attrs[key] = [item, key, len(self.attrs)]
+
+    def __delitem__(self, key):
+        if key in self.attrs:
+            del self.attrs[key]
+
+    def set_citation_data(self, citation_data):
+        self.citation_data = citation_data
+
+    def as_txt(self):
+        # Get items sorted in specified order:
+        items = sorted(list(self.attrs.values()), key=lambda item: item[2])
+        # Find largest label length:
+        max_label_len = max([len(str(item[1])) for item in items])
+        fmt = '%%%ds %%s' % max_label_len
+        res = []
+        for item in items:
+            if item[0] is not None:
+                res.append(fmt % (item[1], item[0]))
+        return '\n'.join(res)
+
+    def as_csv(self, header=False, sep='|'):
+        # Get keys sorted in specified order:
+        keys = [pair[0] for pair in \
+                sorted([(key, val[2]) for key, val in list(self.attrs.items())],
+                       key=lambda pair: pair[1])]
+        res = []
+        if header:
+            res.append(sep.join(keys))
+        res.append(sep.join([unicode(self.attrs[key][0]) for key in keys]))
+        return '\n'.join(res)
+
+    def as_citation(self):
+        """
+        Reports the article in a standard citation format. This works only
+        if you have configured the querier to retrieve a particular
+        citation export format. (See ScholarSettings.)
+        """
+        return self.citation_data or ''
+
+
+class ScholarArticleParser(object):
+    """
+    ScholarArticleParser can parse HTML document strings obtained from
+    Google Scholar. This is a base class; concrete implementations
+    adapting to tweaks made by Google over time follow below.
+    """
+    def __init__(self, site=None):
+        self.soup = None
+        self.article = None
+        self.site = site or ScholarConf.SCHOLAR_SITE
+        self.year_re = re.compile(r'\b(?:20|19)\d{2}\b')
+
+    def handle_article(self, art):
+        """
+        The parser invokes this callback on each article parsed
+        successfully.  In this base class, the callback does nothing.
+        """
+
+    def handle_num_results(self, num_results):
+        """
+        The parser invokes this callback if it determines the overall
+        number of results, as reported on the parsed results page. The
+        base class implementation does nothing.
+        """
+
+    def parse(self, html):
+        """
+        This method initiates parsing of HTML content, cleans resulting
+        content as needed, and notifies the parser instance of
+        resulting instances via the handle_article callback.
+        """
+        self.soup = SoupKitchen.make_soup(html)
+
+        # This parses any global, non-itemized attributes from the page.
+        self._parse_globals()
+
+        # Now parse out listed articles:
+        for div in self.soup.findAll(ScholarArticleParser._tag_results_checker):
+            self._parse_article(div)
+            self._clean_article()
+            if self.article['title']:
+                self.handle_article(self.article)
+
+    def _clean_article(self):
+        """
+        This gets invoked after we have parsed an article, to do any
+        needed cleanup/polishing before we hand off the resulting
+        article.
+        """
+        if self.article['title']:
+            self.article['title'] = self.article['title'].strip()
+
+    def _parse_globals(self):
+        tag = self.soup.find(name='div', attrs={'id': 'gs_ab_md'})
+        if tag is not None:
+            raw_text = tag.findAll(text=True)
+            # raw text is a list because the body contains <b> etc
+            if raw_text is not None and len(raw_text) > 0:
+                try:
+                    num_results = raw_text[0].split()[1]
+                    # num_results may now contain commas to separate
+                    # thousands, strip:
+                    num_results = num_results.replace(',', '')
+                    num_results = int(num_results)
+                    self.handle_num_results(num_results)
+                except (IndexError, ValueError):
+                    pass
+
+    def _parse_article(self, div):
+        self.article = ScholarArticle()
+
+        for tag in div:
+            if not hasattr(tag, 'name'):
+                continue
+
+            if tag.name == 'div' and self._tag_has_class(tag, 'gs_rt') and \
+                    tag.h3 and tag.h3.a:
+                self.article['title'] = ''.join(tag.h3.a.findAll(text=True))
+                self.article['url'] = self._path2url(tag.h3.a['href'])
+                if self.article['url'].endswith('.pdf'):
+                    self.article['url_pdf'] = self.article['url']
+
+            if tag.name == 'font':
+                for tag2 in tag:
+                    if not hasattr(tag2, 'name'):
+                        continue
+                    if tag2.name == 'span' and \
+                       self._tag_has_class(tag2, 'gs_fl'):
+                        self._parse_links(tag2)
+
+    def _parse_links(self, span):
+        for tag in span:
+            if not hasattr(tag, 'name'):
+                continue
+            if tag.name != 'a' or tag.get('href') is None:
+                continue
+
+            if tag.get('href').startswith('/scholar?cites'):
+                if hasattr(tag, 'string') and tag.string.startswith('Cited by'):
+                    self.article['num_citations'] = \
+                        self._as_int(tag.string.split()[-1])
+
+                # Weird Google Scholar behavior here: if the original
+                # search query came with a number-of-results limit,
+                # then this limit gets propagated to the URLs embedded
+                # in the results page as well. Same applies to
+                # versions URL in next if-block.
+                self.article['url_citations'] = \
+                    self._strip_url_arg('num', self._path2url(tag.get('href')))
+
+                # We can also extract the cluster ID from the versions
+                # URL. Note that we know that the string contains "?",
+                # from the above if-statement.
+                args = self.article['url_citations'].split('?', 1)[1]
+                for arg in args.split('&'):
+                    if arg.startswith('cites='):
+                        self.article['cluster_id'] = arg[6:]
+
+            if tag.get('href').startswith('/scholar?cluster'):
+                if hasattr(tag, 'string') and tag.string.startswith('All '):
+                    self.article['num_versions'] = \
+                        self._as_int(tag.string.split()[1])
+                self.article['url_versions'] = \
+                    self._strip_url_arg('num', self._path2url(tag.get('href')))
+
+            if tag.getText().startswith('Import'):
+                self.article['url_citation'] = self._path2url(tag.get('href'))
+
+
+    @staticmethod
+    def _tag_has_class(tag, klass):
+        """
+        This predicate function checks whether a BeatifulSoup Tag instance
+        has a class attribute.
+        """
+        res = tag.get('class') or []
+        if type(res) != list:
+            # BeautifulSoup 3 can return e.g. 'gs_md_wp gs_ttss',
+            # so split -- conveniently produces a list in any case
+            res = res.split()
+        return klass in res
+
+    @staticmethod
+    def _tag_results_checker(tag):
+        return tag.name == 'div' \
+            and ScholarArticleParser._tag_has_class(tag, 'gs_r')
+
+    @staticmethod
+    def _as_int(obj):
+        try:
+            return int(obj)
+        except ValueError:
+            return None
+
+    def _path2url(self, path):
+        """Helper, returns full URL in case path isn't one."""
+        if path.startswith('http://'):
+            return path
+        if not path.startswith('/'):
+            path = '/' + path
+        return self.site + path
+
+    def _strip_url_arg(self, arg, url):
+        """Helper, removes a URL-encoded argument, if present."""
+        parts = url.split('?', 1)
+        if len(parts) != 2:
+            return url
+        res = []
+        for part in parts[1].split('&'):
+            if not part.startswith(arg + '='):
+                res.append(part)
+        return parts[0] + '?' + '&'.join(res)
+
+
+class ScholarArticleParser120201(ScholarArticleParser):
+    """
+    This class reflects update to the Scholar results page layout that
+    Google recently.
+    """
+    def _parse_article(self, div):
+        self.article = ScholarArticle()
+
+        for tag in div:
+            if not hasattr(tag, 'name'):
+                continue
+
+            if tag.name == 'h3' and self._tag_has_class(tag, 'gs_rt') and tag.a:
+                self.article['title'] = ''.join(tag.a.findAll(text=True))
+                self.article['url'] = self._path2url(tag.a['href'])
+                if self.article['url'].endswith('.pdf'):
+                    self.article['url_pdf'] = self.article['url']
+
+            if tag.name == 'div' and self._tag_has_class(tag, 'gs_a'):
+                year = self.year_re.findall(tag.text)
+                self.article['year'] = year[0] if len(year) > 0 else None
+
+            if tag.name == 'div' and self._tag_has_class(tag, 'gs_fl'):
+                self._parse_links(tag)
+
+
+class ScholarArticleParser120726(ScholarArticleParser):
+    """
+    This class reflects update to the Scholar results page layout that
+    Google made 07/26/12.
+    """
+    def _parse_article(self, div):
+        self.article = ScholarArticle()
+
+        for tag in div:
+            if not hasattr(tag, 'name'):
+                continue
+            if str(tag).lower().find('.pdf'):
+                if tag.find('div', {'class': 'gs_ttss'}):
+                    self._parse_links(tag.find('div', {'class': 'gs_ttss'}))
+
+            if tag.name == 'div' and self._tag_has_class(tag, 'gs_ri'):
+                # There are (at least) two formats here. In the first
+                # one, we have a link, e.g.:
+                #
+                # <h3 class="gs_rt">
+                #   <a href="http://dl.acm.org/citation.cfm?id=972384" class="yC0">
+                #     <b>Honeycomb</b>: creating intrusion detection signatures using
+                #        honeypots
+                #   </a>
+                # </h3>
+                #
+                # In the other, there's no actual link -- it's what
+                # Scholar renders as "CITATION" in the HTML:
+                #
+                # <h3 class="gs_rt">
+                #   <span class="gs_ctu">
+                #     <span class="gs_ct1">[CITATION]</span>
+                #     <span class="gs_ct2">[C]</span>
+                #   </span>
+                #   <b>Honeycomb</b> automated ids signature creation using honeypots
+                # </h3>
+                #
+                # We now distinguish the two.
+                try:
+                    atag = tag.h3.a
+                    self.article['title'] = ''.join(atag.findAll(text=True))
+                    self.article['url'] = self._path2url(atag['href'])
+                    if self.article['url'].endswith('.pdf'):
+                        self.article['url_pdf'] = self.article['url']
+                except:
+                    # Remove a few spans that have unneeded content (e.g. [CITATION])
+                    for span in tag.h3.findAll(name='span'):
+                        span.clear()
+                    self.article['title'] = ''.join(tag.h3.findAll(text=True))
+
+                if tag.find('div', {'class': 'gs_a'}):
+                    year = self.year_re.findall(tag.find('div', {'class': 'gs_a'}).text)
+                    self.article['year'] = year[0] if len(year) > 0 else None
+
+                if tag.find('div', {'class': 'gs_fl'}):
+                    self._parse_links(tag.find('div', {'class': 'gs_fl'}))
+
+                if tag.find('div', {'class': 'gs_rs'}):
+                    # These are the content excerpts rendered into the results.
+                    raw_text = tag.find('div', {'class': 'gs_rs'}).findAll(text=True)
+                    if len(raw_text) > 0:
+                        raw_text = ''.join(raw_text)
+                        raw_text = raw_text.replace('\n', '')
+                        self.article['excerpt'] = raw_text
+
+
+class ScholarQuery(object):
+    """
+    The base class for any kind of results query we send to Scholar.
+    """
+    def __init__(self):
+        self.url = None
+
+        # The number of results requested from Scholar -- not the
+        # total number of results it reports (the latter gets stored
+        # in attrs, see below).
+        self.num_results = None
+
+        # Queries may have global result attributes, similar to
+        # per-article attributes in ScholarArticle. The exact set of
+        # attributes may differ by query type, but they all share the
+        # basic data structure:
+        self.attrs = {}
+
+    def set_num_page_results(self, num_page_results):
+        self.num_results = ScholarUtils.ensure_int(
+            num_page_results,
+            'maximum number of results on page must be numeric')
+
+    def get_url(self):
+        """
+        Returns a complete, submittable URL string for this particular
+        query instance. The URL and its arguments will vary depending
+        on the query.
+        """
+        return None
+
+    def _add_attribute_type(self, key, label, default_value=None):
+        """
+        Adds a new type of attribute to the list of attributes
+        understood by this query. Meant to be used by the constructors
+        in derived classes.
+        """
+        if len(self.attrs) == 0:
+            self.attrs[key] = [default_value, label, 0]
+            return
+        idx = max([item[2] for item in self.attrs.values()]) + 1
+        self.attrs[key] = [default_value, label, idx]
+
+    def __getitem__(self, key):
+        """Getter for attribute value. Returns None if no such key."""
+        if key in self.attrs:
+            return self.attrs[key][0]
+        return None
+
+    def __setitem__(self, key, item):
+        """Setter for attribute value. Does nothing if no such key."""
+        if key in self.attrs:
+            self.attrs[key][0] = item
+
+    def _parenthesize_phrases(self, query):
+        """
+        Turns a query string containing comma-separated phrases into a
+        space-separated list of tokens, quoted if containing
+        whitespace. For example, input
+
+          'some words, foo, bar'
+
+        becomes
+
+          '"some words" foo bar'
+
+        This comes in handy during the composition of certain queries.
+        """
+        if query.find(',') < 0:
+            return query
+        phrases = []
+        for phrase in query.split(','):
+            phrase = phrase.strip()
+            if phrase.find(' ') > 0:
+                phrase = '"' + phrase + '"'
+            phrases.append(phrase)
+        return ' '.join(phrases)
+
+
+class ClusterScholarQuery(ScholarQuery):
+    """
+    This version just pulls up an article cluster whose ID we already
+    know about.
+    """
+    SCHOLAR_CLUSTER_URL = ScholarConf.SCHOLAR_SITE + '/scholar?' \
+        + 'cluster=%(cluster)s' \
+        + '%(num)s'
+
+    def __init__(self, cluster=None):
+        ScholarQuery.__init__(self)
+        self._add_attribute_type('num_results', 'Results', 0)
+        self.cluster = None
+        self.set_cluster(cluster)
+
+    def set_cluster(self, cluster):
+        """
+        Sets search to a Google Scholar results cluster ID.
+        """
+        msg = 'cluster ID must be numeric'
+        self.cluster = ScholarUtils.ensure_int(cluster, msg)
+
+    def get_url(self):
+        if self.cluster is None:
+            raise QueryArgumentError('cluster query needs cluster ID')
+
+        urlargs = {'cluster': self.cluster }
+
+        for key, val in urlargs.items():
+            urlargs[key] = quote(encode(val))
+
+        # The following URL arguments must not be quoted, or the
+        # server will not recognize them:
+        urlargs['num'] = ('&num=%d' % self.num_results
+                          if self.num_results is not None else '')
+
+        return self.SCHOLAR_CLUSTER_URL % urlargs
+
+
+class SearchScholarQuery(ScholarQuery):
+    """
+    This version represents the search query parameters the user can
+    configure on the Scholar website, in the advanced search options.
+    """
+    SCHOLAR_QUERY_URL = ScholarConf.SCHOLAR_SITE + '/scholar?' \
+        + 'as_q=%(words)s' \
+        + '&as_epq=%(phrase)s' \
+        + '&as_oq=%(words_some)s' \
+        + '&as_eq=%(words_none)s' \
+        + '&as_occt=%(scope)s' \
+        + '&as_sauthors=%(authors)s' \
+        + '&as_publication=%(pub)s' \
+        + '&as_ylo=%(ylo)s' \
+        + '&as_yhi=%(yhi)s' \
+        + '&as_vis=%(citations)s' \
+        + '&btnG=&hl=en' \
+        + '%(num)s' \
+        + '&as_sdt=%(patents)s%%2C5'
+
+    def __init__(self):
+        ScholarQuery.__init__(self)
+        self._add_attribute_type('num_results', 'Results', 0)
+        self.words = None # The default search behavior
+        self.words_some = None # At least one of those words
+        self.words_none = None # None of these words
+        self.phrase = None
+        self.scope_title = False # If True, search in title only
+        self.author = None
+        self.pub = None
+        self.timeframe = [None, None]
+        self.include_patents = True
+        self.include_citations = True
+
+    def set_words(self, words):
+        """Sets words that *all* must be found in the result."""
+        self.words = words
+
+    def set_words_some(self, words):
+        """Sets words of which *at least one* must be found in result."""
+        self.words_some = words
+
+    def set_words_none(self, words):
+        """Sets words of which *none* must be found in the result."""
+        self.words_none = words
+
+    def set_phrase(self, phrase):
+        """Sets phrase that must be found in the result exactly."""
+        self.phrase = phrase
+
+    def set_scope(self, title_only):
+        """
+        Sets Boolean indicating whether to search entire article or title
+        only.
+        """
+        self.scope_title = title_only
+
+    def set_author(self, author):
+        """Sets names that must be on the result's author list."""
+        self.author = author
+
+    def set_pub(self, pub):
+        """Sets the publication in which the result must be found."""
+        self.pub = pub
+
+    def set_timeframe(self, start=None, end=None):
+        """
+        Sets timeframe (in years as integer) in which result must have
+        appeared. It's fine to specify just start or end, or both.
+        """
+        if start:
+            start = ScholarUtils.ensure_int(start)
+        if end:
+            end = ScholarUtils.ensure_int(end)
+        self.timeframe = [start, end]
+
+    def set_include_citations(self, yesorno):
+        self.include_citations = yesorno
+
+    def set_include_patents(self, yesorno):
+        self.include_patents = yesorno
+
+    def get_url(self):
+        if self.words is None and self.words_some is None \
+           and self.words_none is None and self.phrase is None \
+           and self.author is None and self.pub is None \
+           and self.timeframe[0] is None and self.timeframe[1] is None:
+            raise QueryArgumentError('search query needs more parameters')
+
+        # If we have some-words or none-words lists, we need to
+        # process them so GS understands them. For simple
+        # space-separeted word lists, there's nothing to do. For lists
+        # of phrases we have to ensure quotations around the phrases,
+        # separating them by whitespace.
+        words_some = None
+        words_none = None
+
+        if self.words_some:
+            words_some = self._parenthesize_phrases(self.words_some)
+        if self.words_none:
+            words_none = self._parenthesize_phrases(self.words_none)
+
+        urlargs = {'words': self.words or '',
+                   'words_some': words_some or '',
+                   'words_none': words_none or '',
+                   'phrase': self.phrase or '',
+                   'scope': 'title' if self.scope_title else 'any',
+                   'authors': self.author or '',
+                   'pub': self.pub or '',
+                   'ylo': self.timeframe[0] or '',
+                   'yhi': self.timeframe[1] or '',
+                   'patents': '0' if self.include_patents else '1',
+                   'citations': '0' if self.include_citations else '1'}
+
+        for key, val in urlargs.items():
+            urlargs[key] = quote(encode(val))
+
+        # The following URL arguments must not be quoted, or the
+        # server will not recognize them:
+        urlargs['num'] = ('&num=%d' % self.num_results
+                          if self.num_results is not None else '')
+
+        return self.SCHOLAR_QUERY_URL % urlargs
+
+
+class ScholarSettings(object):
+    """
+    This class lets you adjust the Scholar settings for your
+    session. It's intended to mirror the features tunable in the
+    Scholar Settings pane, but right now it's a bit basic.
+    """
+    CITFORM_NONE = 0
+    CITFORM_REFWORKS = 1
+    CITFORM_REFMAN = 2
+    CITFORM_ENDNOTE = 3
+    CITFORM_BIBTEX = 4
+
+    def __init__(self):
+        self.citform = 0 # Citation format, default none
+        self.per_page_results = None
+        self._is_configured = False
+
+    def set_citation_format(self, citform):
+        citform = ScholarUtils.ensure_int(citform)
+        if citform < 0 or citform > self.CITFORM_BIBTEX:
+            raise FormatError('citation format invalid, is "%s"'
+                              % citform)
+        self.citform = citform
+        self._is_configured = True
+
+    def set_per_page_results(self, per_page_results):
+        self.per_page_results = ScholarUtils.ensure_int(
+            per_page_results, 'page results must be integer')
+        self.per_page_results = min(
+            self.per_page_results, ScholarConf.MAX_PAGE_RESULTS)
+        self._is_configured = True
+
+    def is_configured(self):
+        return self._is_configured
+
+
+class ScholarQuerier(object):
+    """
+    ScholarQuerier instances can conduct a search on Google Scholar
+    with subsequent parsing of the resulting HTML content.  The
+    articles found are collected in the articles member, a list of
+    ScholarArticle instances.
+    """
+
+    # Default URLs for visiting and submitting Settings pane, as of 3/14
+    GET_SETTINGS_URL = ScholarConf.SCHOLAR_SITE + '/scholar_settings?' \
+        + 'sciifh=1&hl=en&as_sdt=0,5'
+
+    SET_SETTINGS_URL = ScholarConf.SCHOLAR_SITE + '/scholar_setprefs?' \
+        + 'q=' \
+        + '&scisig=%(scisig)s' \
+        + '&inststart=0' \
+        + '&as_sdt=1,5' \
+        + '&as_sdtp=' \
+        + '&num=%(num)s' \
+        + '&scis=%(scis)s' \
+        + '%(scisf)s' \
+        + '&hl=en&lang=all&instq=&inst=569367360547434339&save='
+
+    # Older URLs:
+    # ScholarConf.SCHOLAR_SITE + '/scholar?q=%s&hl=en&btnG=Search&as_sdt=2001&as_sdtp=on
+
+    class Parser(ScholarArticleParser120726):
+        def __init__(self, querier):
+            ScholarArticleParser120726.__init__(self)
+            self.querier = querier
+
+        def handle_num_results(self, num_results):
+            if self.querier is not None and self.querier.query is not None:
+                self.querier.query['num_results'] = num_results
+
+        def handle_article(self, art):
+            self.querier.add_article(art)
+
+    def __init__(self):
+        self.articles = []
+        self.query = None
+        self.cjar = MozillaCookieJar()
+
+        # If we have a cookie file, load it:
+        if ScholarConf.COOKIE_JAR_FILE and \
+           os.path.exists(ScholarConf.COOKIE_JAR_FILE):
+            try:
+                self.cjar.load(ScholarConf.COOKIE_JAR_FILE,
+                               ignore_discard=True)
+                ScholarUtils.log('info', 'loaded cookies file')
+            except Exception as msg:
+                ScholarUtils.log('warn', 'could not load cookies file: %s' % msg)
+                self.cjar = MozillaCookieJar() # Just to be safe
+
+        self.opener = build_opener(HTTPCookieProcessor(self.cjar))
+        self.settings = None # Last settings object, if any
+
+    def apply_settings(self, settings):
+        """
+        Applies settings as provided by a ScholarSettings instance.
+        """
+        if settings is None or not settings.is_configured():
+            return True
+
+        self.settings = settings
+
+        # This is a bit of work. We need to actually retrieve the
+        # contents of the Settings pane HTML in order to extract
+        # hidden fields before we can compose the query for updating
+        # the settings.
+        html = self._get_http_response(url=self.GET_SETTINGS_URL,
+                                       log_msg='dump of settings form HTML',
+                                       err_msg='requesting settings failed')
+        if html is None:
+            return False
+
+        # Now parse the required stuff out of the form. We require the
+        # "scisig" token to make the upload of our settings acceptable
+        # to Google.
+        soup = SoupKitchen.make_soup(html)
+
+        tag = soup.find(name='form', attrs={'id': 'gs_settings_form'})
+        if tag is None:
+            ScholarUtils.log('info', 'parsing settings failed: no form')
+            return False
+
+        tag = tag.find('input', attrs={'type':'hidden', 'name':'scisig'})
+        if tag is None:
+            ScholarUtils.log('info', 'parsing settings failed: scisig')
+            return False
+
+        urlargs = {'scisig': tag['value'],
+                   'num': settings.per_page_results,
+                   'scis': 'no',
+                   'scisf': ''}
+
+        if settings.citform != 0:
+            urlargs['scis'] = 'yes'
+            urlargs['scisf'] = '&scisf=%d' % settings.citform
+
+        html = self._get_http_response(url=self.SET_SETTINGS_URL % urlargs,
+                                       log_msg='dump of settings result HTML',
+                                       err_msg='applying setttings failed')
+        if html is None:
+            return False
+
+        ScholarUtils.log('info', 'settings applied')
+        return True
+
+    def send_query(self, query):
+        """
+        This method initiates a search query (a ScholarQuery instance)
+        with subsequent parsing of the response.
+        """
+        self.clear_articles()
+        self.query = query
+
+        html = self._get_http_response(url=query.get_url(),
+                                       log_msg='dump of query response HTML',
+                                       err_msg='results retrieval failed')
+        if html is None:
+            return
+
+        self.parse(html)
+
+    def get_citation_data(self, article):
+        """
+        Given an article, retrieves citation link. Note, this requires that
+        you adjusted the settings to tell Google Scholar to actually
+        provide this information, *prior* to retrieving the article.
+        """
+        if article['url_citation'] is None:
+            return False
+        if article.citation_data is not None:
+            return True
+
+        ScholarUtils.log('info', 'retrieving citation export data')
+        data = self._get_http_response(url=article['url_citation'],
+                                       log_msg='citation data response',
+                                       err_msg='requesting citation data failed')
+        if data is None:
+            return False
+
+        article.set_citation_data(data)
+        return True
+
+    def parse(self, html):
+        """
+        This method allows parsing of provided HTML content.
+        """
+        parser = self.Parser(self)
+        parser.parse(html)
+
+    def add_article(self, art):
+        self.get_citation_data(art)
+        self.articles.append(art)
+
+    def clear_articles(self):
+        """Clears any existing articles stored from previous queries."""
+        self.articles = []
+
+    def save_cookies(self):
+        """
+        This stores the latest cookies we're using to disk, for reuse in a
+        later session.
+        """
+        if ScholarConf.COOKIE_JAR_FILE is None:
+            return False
+        try:
+            self.cjar.save(ScholarConf.COOKIE_JAR_FILE,
+                           ignore_discard=True)
+            ScholarUtils.log('info', 'saved cookies file')
+            return True
+        except Exception as msg:
+            ScholarUtils.log('warn', 'could not save cookies file: %s' % msg)
+            return False
+
+    def _get_http_response(self, url, log_msg=None, err_msg=None):
+        """
+        Helper method, sends HTTP request and returns response payload.
+        """
+        if log_msg is None:
+            log_msg = 'HTTP response data follow'
+        if err_msg is None:
+            err_msg = 'request failed'
+        try:
+            ScholarUtils.log('info', 'requesting %s' % unquote(url))
+
+            req = Request(url=url, headers={'User-Agent': ScholarConf.USER_AGENT})
+            hdl = self.opener.open(req)
+            html = hdl.read()
+
+            ScholarUtils.log('debug', log_msg)
+            ScholarUtils.log('debug', '>>>>' + '-'*68)
+            ScholarUtils.log('debug', 'url: %s' % hdl.geturl())
+            ScholarUtils.log('debug', 'result: %s' % hdl.getcode())
+            ScholarUtils.log('debug', 'headers:\n' + str(hdl.info()))
+            ScholarUtils.log('debug', 'data:\n' + html.decode('utf-8')) # For Python 3
+            ScholarUtils.log('debug', '<<<<' + '-'*68)
+
+            return html
+        except Exception as err:
+            ScholarUtils.log('info', err_msg + ': %s' % err)
+            return None
+
+
+def txt(querier, with_globals):
+    if with_globals:
+        # If we have any articles, check their attribute labels to get
+        # the maximum length -- makes for nicer alignment.
+        max_label_len = 0
+        if len(querier.articles) > 0:
+            items = sorted(list(querier.articles[0].attrs.values()),
+                           key=lambda item: item[2])
+            max_label_len = max([len(str(item[1])) for item in items])
+
+        # Get items sorted in specified order:
+        items = sorted(list(querier.query.attrs.values()), key=lambda item: item[2])
+        # Find largest label length:
+        max_label_len = max([len(str(item[1])) for item in items] + [max_label_len])
+        fmt = '[G] %%%ds %%s' % max(0, max_label_len-4)
+        for item in items:
+            if item[0] is not None:
+                print(fmt % (item[1], item[0]))
+        if len(items) > 0:
+            print
+
+    articles = querier.articles
+    for art in articles:
+        print(encode(art.as_txt()) + '\n')
+
+def csv(querier, header=False, sep='|'):
+    articles = querier.articles
+    for art in articles:
+        result = art.as_csv(header=header, sep=sep)
+        print(encode(result))
+        header = False
+
+def citation_export(querier):
+    articles = querier.articles
+    for art in articles:
+        print(art.as_citation() + '\n')
+
+
+def main():
+    usage = """scholar.py [options] <query string>
+A command-line interface to Google Scholar.
+
+Examples:
+
+# Retrieve one article written by Einstein on quantum theory:
+scholar.py -c 1 --author "albert einstein" --phrase "quantum theory"
+
+# Retrieve a BibTeX entry for that quantum theory paper:
+scholar.py -c 1 -C 17749203648027613321 --citation bt
+
+# Retrieve five articles written by Einstein after 1970 where the title
+# does not contain the words "quantum" and "theory":
+scholar.py -c 5 -a "albert einstein" -t --none "quantum theory" --after 1970"""
+
+    fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100)
+    parser = optparse.OptionParser(usage=usage, formatter=fmt)
+    group = optparse.OptionGroup(parser, 'Query arguments',
+                                 'These options define search query arguments and parameters.')
+    group.add_option('-a', '--author', metavar='AUTHORS', default=None,
+                     help='Author name(s)')
+    group.add_option('-A', '--all', metavar='WORDS', default=None, dest='allw',
+                     help='Results must contain all of these words')
+    group.add_option('-s', '--some', metavar='WORDS', default=None,
+                     help='Results must contain at least one of these words. Pass arguments in form -s "foo bar baz" for simple words, and -s "a phrase, another phrase" for phrases')
+    group.add_option('-n', '--none', metavar='WORDS', default=None,
+                     help='Results must contain none of these words. See -s|--some re. formatting')
+    group.add_option('-p', '--phrase', metavar='PHRASE', default=None,
+                     help='Results must contain exact phrase')
+    group.add_option('-t', '--title-only', action='store_true', default=False,
+                     help='Search title only')
+    group.add_option('-P', '--pub', metavar='PUBLICATIONS', default=None,
+                     help='Results must have appeared in this publication')
+    group.add_option('--after', metavar='YEAR', default=None,
+                     help='Results must have appeared in or after given year')
+    group.add_option('--before', metavar='YEAR', default=None,
+                     help='Results must have appeared in or before given year')
+    group.add_option('--no-patents', action='store_true', default=False,
+                     help='Do not include patents in results')
+    group.add_option('--no-citations', action='store_true', default=False,
+                     help='Do not include citations in results')
+    group.add_option('-C', '--cluster-id', metavar='CLUSTER_ID', default=None,
+                     help='Do not search, just use articles in given cluster ID')
+    group.add_option('-c', '--count', type='int', default=None,
+                     help='Maximum number of results')
+    parser.add_option_group(group)
+
+    group = optparse.OptionGroup(parser, 'Output format',
+                                 'These options control the appearance of the results.')
+    group.add_option('--txt', action='store_true',
+                     help='Print article data in text format (default)')
+    group.add_option('--txt-globals', action='store_true',
+                     help='Like --txt, but first print global results too')
+    group.add_option('--csv', action='store_true',
+                     help='Print article data in CSV form (separator is "|")')
+    group.add_option('--csv-header', action='store_true',
+                     help='Like --csv, but print header with column names')
+    group.add_option('--citation', metavar='FORMAT', default=None,
+                     help='Print article details in standard citation format. Argument Must be one of "bt" (BibTeX), "en" (EndNote), "rm" (RefMan), or "rw" (RefWorks).')
+    parser.add_option_group(group)
+
+    group = optparse.OptionGroup(parser, 'Miscellaneous')
+    group.add_option('--cookie-file', metavar='FILE', default=None,
+                     help='File to use for cookie storage. If given, will read any existing cookies if found at startup, and save resulting cookies in the end.')
+    group.add_option('-d', '--debug', action='count', default=0,
+                     help='Enable verbose logging to stderr. Repeated options increase detail of debug output.')
+    group.add_option('-v', '--version', action='store_true', default=False,
+                     help='Show version information')
+    parser.add_option_group(group)
+
+    options, _ = parser.parse_args()
+
+    # Show help if we have neither keyword search nor author name
+    if len(sys.argv) == 1:
+        parser.print_help()
+        return 1
+
+    if options.debug > 0:
+        options.debug = min(options.debug, ScholarUtils.LOG_LEVELS['debug'])
+        ScholarConf.LOG_LEVEL = options.debug
+        ScholarUtils.log('info', 'using log level %d' % ScholarConf.LOG_LEVEL)
+
+    if options.version:
+        print('This is scholar.py %s.' % ScholarConf.VERSION)
+        return 0
+
+    if options.cookie_file:
+        ScholarConf.COOKIE_JAR_FILE = options.cookie_file
+
+    # Sanity-check the options: if they include a cluster ID query, it
+    # makes no sense to have search arguments:
+    if options.cluster_id is not None:
+        if options.author or options.allw or options.some or options.none \
+           or options.phrase or options.title_only or options.pub \
+           or options.after or options.before:
+            print('Cluster ID queries do not allow additional search arguments.')
+            return 1
+
+    querier = ScholarQuerier()
+    settings = ScholarSettings()
+
+    if options.citation == 'bt':
+        settings.set_citation_format(ScholarSettings.CITFORM_BIBTEX)
+    elif options.citation == 'en':
+        settings.set_citation_format(ScholarSettings.CITFORM_ENDNOTE)
+    elif options.citation == 'rm':
+        settings.set_citation_format(ScholarSettings.CITFORM_REFMAN)
+    elif options.citation == 'rw':
+        settings.set_citation_format(ScholarSettings.CITFORM_REFWORKS)
+    elif options.citation is not None:
+        print('Invalid citation link format, must be one of "bt", "en", "rm", or "rw".')
+        return 1
+
+    querier.apply_settings(settings)
+
+    if options.cluster_id:
+        query = ClusterScholarQuery(cluster=options.cluster_id)
+    else:
+        query = SearchScholarQuery()
+        if options.author:
+            query.set_author(options.author)
+        if options.allw:
+            query.set_words(options.allw)
+        if options.some:
+            query.set_words_some(options.some)
+        if options.none:
+            query.set_words_none(options.none)
+        if options.phrase:
+            query.set_phrase(options.phrase)
+        if options.title_only:
+            query.set_scope(True)
+        if options.pub:
+            query.set_pub(options.pub)
+        if options.after or options.before:
+            query.set_timeframe(options.after, options.before)
+        if options.no_patents:
+            query.set_include_patents(False)
+        if options.no_citations:
+            query.set_include_citations(False)
+
+    if options.count is not None:
+        options.count = min(options.count, ScholarConf.MAX_PAGE_RESULTS)
+        query.set_num_page_results(options.count)
+
+    querier.send_query(query)
+
+    if options.csv:
+        csv(querier)
+    elif options.csv_header:
+        csv(querier, header=True)
+    elif options.citation is not None:
+        citation_export(querier)
+    else:
+        txt(querier, with_globals=options.txt_globals)
+
+    if options.cookie_file:
+        querier.save_cookies()
+
+    return 0
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/science_access/scrape.py b/science_access/scrape.py
new file mode 100644
index 0000000000000000000000000000000000000000..57f71ae0ad71697fa3543b92d79b5028182e4590
--- /dev/null
+++ b/science_access/scrape.py
@@ -0,0 +1,387 @@
+# Scientific readability project
+# authors: other authors,
+# ...,
+# Russell Jarvis
+# https://github.com/russelljjarvis/
+# rjjarvis@asu.edu
+
+# Patrick McGurrin
+# patrick.mcgurrin@gmail.com
+from numpy import random
+import os
+from bs4 import BeautifulSoup
+import pickle
+import _pickle as cPickle #Using cPickle will result in performance gains
+#from GoogleScraper import scrape_with_config, GoogleSearchError
+import dask.bag as db
+
+import pdfminer
+from pdfminer.pdfparser import PDFParser
+from pdfminer.pdfdocument import PDFDocument
+from pdfminer.pdfpage import PDFPage
+from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
+from pdfminer.pdfdevice import PDFDevice
+from pdfminer.layout import LAParams
+from pdfminer.converter import  TextConverter
+
+import os
+import sys, getopt
+from io import StringIO
+
+from delver import Crawler
+C = Crawler()
+import requests
+import io
+import selenium
+
+
+from .crawl import convert_pdf_to_txt
+from .crawl import print_best_text
+from .crawl import collect_pubs
+from science_access import scholar
+
+
+import re
+from bs4 import BeautifulSoup
+import bs4 as bs
+import urllib.request
+from io import StringIO
+import io
+from selenium.webdriver.firefox.options import Options
+from selenium.common.exceptions import NoSuchElementException
+import os
+from selenium import webdriver
+if 'DYNO' in os.environ:
+    heroku = False
+else:
+    heroku = True
+def get_driver():
+    if 'DYNO' in os.environ:
+        heroku = True
+    else:
+        heroku = False
+
+    options = Options()
+    options.add_argument("--headless")
+    options.add_argument("--disable-dev-shm-usage")
+    options.add_argument("--no-sandbox")
+    try:
+        driver = webdriver.Firefox(options=options)
+    except:
+        try:
+            options.binary_location = "/app/vendor/firefox/firefox"
+            driver = webdriver.Firefox(options=options)
+            GECKODRIVER_PATH=str(os.getcwd())+str("/geckodriver")
+            driver = webdriver.Firefox(options=options,executable_path=GECKODRIVER_PATH)
+        except:
+            try:
+                chrome_options = webdriver.ChromeOptions()
+                chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
+                chrome_options.add_argument("--headless")
+                chrome_options.add_argument("--disable-dev-shm-usage")
+                chrome_options.add_argument("--no-sandbox")
+                driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options)
+            except:
+                try:
+                    GECKODRIVER_PATH=str(os.getcwd())+str("/geckodriver")
+                    options.binary_location = str('./firefox')
+                    driver = webdriver.Firefox(options=options,executable_path=GECKODRIVER_PATH)
+                except:
+                    os.system("wget wget https://ftp.mozilla.org/pub/firefox/releases/45.0.2/linux-x86_64/en-GB/firefox-45.0.2.tar.bz2")
+                    os.system("wget https://github.com/mozilla/geckodriver/releases/download/v0.26.0/geckodriver-v0.26.0-linux64.tar.gz")
+                    os.system("tar -xf geckodriver-v0.26.0-linux64.tar.gz")
+                    os.system("tar xvf firefox-45.0.2.tar.bz2")
+                    GECKODRIVER_PATH=str(os.getcwd())+str("/geckodriver")
+                    options.binary_location = str('./firefox')
+                    driver = webdriver.Firefox(options=options,executable_path=GECKODRIVER_PATH)
+    return driver
+
+
+#driver = get_driver()
+
+rsrcmgr = PDFResourceManager()
+retstr = StringIO()
+laparams = LAParams()
+codec = 'utf-8'
+device = TextConverter(rsrcmgr, retstr, laparams = laparams)
+interpreter = PDFPageInterpreter(rsrcmgr, device)
+
+
+#converts pdf, returns its text content as a string
+def pdf_to_txt_(infile):#, pages=None):
+    output = StringIO()
+    manager = PDFResourceManager()
+    converter = TextConverter(manager, output, laparams=LAParams())
+    interpreter = PDFPageInterpreter(manager, converter)
+
+    for page in PDFPage.get_pages(infile, pagenums):
+        interpreter.process_page(page)
+    infile.close()
+    converter.close()
+    text = output.getvalue()
+    output.close
+    return text
+
+
+import PyPDF2
+from PyPDF2 import PdfFileReader
+
+
+def pdf_to_txt(url):
+
+    if str(content) == str('<Response [404]>'):
+        return None
+    else:
+        # from
+        # https://medium.com/@rqaiserr/how-to-convert-pdfs-into-searchable-key-words-with-python-85aab86c544f
+        try:
+            input_buffer = StringIO(content.content)
+            pdfReader = PyPDF2.PdfFileReader(input_buffer)
+        except:
+            pdfFileObj = io.BytesIO(content.content)
+            pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
+
+        num_pages = pdfReader.numPages
+        count = 0
+        text = ""
+        while count < num_pages:
+            pageObj = pdfReader.getPage(count)
+            count +=1
+            text += pageObj.extractText()
+        if text != "":
+           text = text
+        else:
+           text = textract.process(fileurl, method='tesseract', language='eng')
+    return text
+
+def html_to_txt(content):
+    soup = BeautifulSoup(content, 'html.parser')
+    #strip HTML
+
+    for script in soup(["script", "style"]):
+        script.extract()    # rip it out
+    text = soup.get_text()
+    wt = copy.copy(text)
+    #organize text
+    lines = (line.strip() for line in text.splitlines())  # break into lines and remove leading and trailing space on each
+    chunks = (phrase.strip() for line in lines for phrase in line.split("  ")) # break multi-headlines into a line each
+    text = '\n'.join(chunk for chunk in chunks if chunk) # drop blank lines
+    str_text = str(text)
+
+    return str_text
+
+def convert(content,link):
+    # This is really ugly, but it's proven to be both fault tolerant and effective.
+    try:
+        if str('.html') in link:
+            text = html_to_txt(content)
+            print(text)
+
+        elif str('.pdf') in link:
+            text = pdf_to_txt(content)
+        else:
+            try:
+                text = html_to_txt(content)
+                print(text)
+            except:
+                text = None
+    except:
+        text = None
+    return text
+
+
+def url_to_text(link_tuple):
+    se_b, page_rank, link, category, buff = link_tuple
+    if str('pdf') not in link:
+        if C.open(link) is not None:
+            content = C.open(link).content
+            buff = convert(content,link)
+        else:
+            print('problem')
+    else:
+        pdf_file = requests.get(link, stream=True)
+        f = io.BytesIO(pdf_file.content)
+        reader = PdfFileReader(f)
+        buff = reader.getPage(0).extractText().split('\n')
+
+
+    print(buff)
+    link_tuple = ( se_b, page_rank, link, category, buff )
+    return link_tuple
+
+#@jit
+def buffer_to_pickle(link_tuple):
+    se_b, page_rank, link, category, buff = link_tuple
+    link_tuple = se_b, page_rank, link, category, buff
+    fname = 'results_dir/{0}_{1}_{2}.p'.format(category,se_b,page_rank)
+    if type(buff) is not None:
+        with open(fname,'wb') as f:
+            pickle.dump(link_tuple,f)
+    return
+
+def process(item):
+    text = url_to_text(item)
+    buffer_to_pickle(text)
+    return
+
+
+# this should not be hard coded, it should be set in the class init, but can't be bothered refactoring.
+NUM_LINKS = 10
+
+
+
+# this should be a class method with self and self.NUM_LINKS but can't be bothered refactoring.
+def wiki_get(get_links):
+    # wikipedia is robot friendly
+    # surfraw is fine.
+    se_,index,link,category,buff = get_links
+    url_of_links = str('https://en.wikipedia.org/w/index.php?search=')+str(category)
+    links = collect_pubs(url_of_links)
+    if len(links) > NUM_LINKS: links = links[0:NUM_LINKS]
+    [ process((se_,index,l,category,buff)) for index,l in enumerate(links) ]
+
+# this should be a class method with self and self.NUM_LINKS but can't be bothered refactoring.
+
+def scholar_pedia_get(get_links):
+    # wikipedia is robot friendly
+    # surfraw is fine.
+    se_,index,link,category,buff = get_links
+    url_of_links = str('http://www.scholarpedia.org/w/index.php?search=')+str(category)+str('&title=Special%3ASearch')
+    links = collect_pubs(url_of_links)
+    if len(links) > NUM_LINKS: links = links[0:NUM_LINKS]
+    [ process((se_,index,l,category,buff)) for index,l in enumerate(links) ]
+
+# this should be a class method with self and self.NUM_LINKS but can't be bothered refactoring.
+def search_scholar(get_links):
+    # from https://github.com/ckreibich/scholar.py/issues/80
+    se_,index,category,category,buff = get_links
+    querier = scholar.ScholarQuerier()
+    settings = scholar.ScholarSettings()
+    querier.apply_settings(settings)
+    query = scholar.SearchScholarQuery()
+
+    query.set_words(category)
+    querier.send_query(query)
+    links = [ a.attrs['url'][0] for a in querier.articles if a.attrs['url'][0] is not None ]
+    #links = query.get_url()
+    #print(links)
+    #if len(links) > NUM_LINKS: links = links[0:NUM_LINKS]
+
+    [ process((se_,index,l,category,buff)) for index,l in enumerate(links) ]
+
+def search_author(get_links):
+    # from https://github.com/ckreibich/scholar.py/issues/80
+    se_,index,category,category,buff = get_links
+    querier = scholar.ScholarQuerier()
+    settings = scholar.ScholarSettings()
+    querier.apply_settings(settings)
+    query = scholar.SearchScholarQuery()
+
+    query.set_words(category)
+    querier.send_query(query)
+    links = [ a.attrs['url'][0] for a in querier.articles if a.attrs['url'][0] is not None ]
+    #links = query.get_url()
+    #print(links)
+    #if len(links) > NUM_LINKS: links = links[0:NUM_LINKS]
+
+    [ process((se_,index,l,category,buff)) for index,l in enumerate(links) ]
+
+class SW(object):
+    def __init__(self,sengines,sterms,nlinks=10):
+        self.NUM_LINKS = nlinks
+        self.links = None
+        if not os.path.exists('results_dir'):
+            os.makedirs('results_dir')
+        self.iterable = [ (v,category) for category in sterms for v in sengines.values() ]
+        random.shuffle(self.iterable)
+
+    def slat_(self,config):
+        try:
+            if str('wiki') in config['search_engines']:
+                get_links = (str('wikipedia'),0,None,config['keyword'],None)
+                wiki_get(get_links)
+
+            elif str('info_wars') in config['search_engines']:
+                get_links = (str('info_wars'),0,None,config['keyword'],None)
+                info_wars_get(get_links)
+
+            elif str('scholar') in config['search_engines']:
+                get_links = (str('scholar'),0,None,config['keyword'],None)
+                search_scholar(get_links)
+
+            elif str('scholarpedia') in config['search_engines']:
+                get_links = (str('scholar'),0,None,config['keyword'],None)
+                scholar_pedia_get(get_links)
+
+            else:
+                search = scrape_with_config(config)
+                links = []
+                for serp in search.serps:
+                    print(serp)
+                    links.extend([link.link for link in serp.links])
+
+                # This code block jumps over gate two
+                # The (possibly private, or hosted server as a gatekeeper).
+                if len(links) > self.NUM_LINKS: links = links[0:self.NUM_LINKS]
+                if len(links) > 0:
+                    print(links)
+                    buffer = None
+                    se_ = config['search_engines']
+                    category = config['keyword']
+                    get_links = ((se_,index,link,category,buffer) for index, link in enumerate(links) )
+                    for gl in get_links:
+                        process(gl)
+                    # map over the function in parallel since it's 2018
+                    #b = db.from_sequence(get_links,npartitions=8)
+                    #_ = list(b.map(process).compute())
+        except GoogleSearchError as e:
+            print(e)
+            return None
+        print('done scraping')
+
+    #@jit
+    def scrapelandtext(self,fi):
+        se_,category = fi
+        config = {}
+        #driver = rotate_profiles()
+        # This code block, jumps over gate one (the search engine as a gatekeeper)
+        # google scholar or wikipedia is not supported by google scraper
+        # duckduckgo bang expansion _cannot_ be used as to access engines that GS does not support
+        # without significant development. Redirection to the right search results does occur,
+        # but google scrape also has tools for reading links out of web pages, and it needs to know
+        # which brand of SE to expect in order to deal with idiosyncratic formatting.
+        # it's easier not to use bang expansion, for that reason.
+        # for example twitter etc
+
+        config['keyword'] = str(category)
+
+
+        config['search_engines'] = se_
+        #config['scrape_method'] = 'http'
+
+        config['scrape_method'] = 'selenium'
+        config['num_pages_for_keyword'] = 1
+        config['use_own_ip'] = True
+        config['sel_browser'] = 'chrome'
+        config['do_caching'] = False # bloat warning.
+
+        # Google scrap + selenium implements a lot of human centric browser masquarading tools.
+        # Search Engine: 'who are you?' code: 'I am an honest human centric browser, and certainly note a robot surfing in the nude'. Search Engine: 'good, here are some pages'.
+        # Time elapses and the reality is exposed just like in 'the Emperors New Clothes'.
+        # The file crawl.py contains methods for crawling the scrapped links.
+        # For this reason, a subsequent action, c.download (crawl download ) is ncessary.
+
+        config['output_filename'] = '{0}_{1}.csv'.format(category,se_)
+
+        self.slat_(config)
+        return
+
+    def run(self):
+        # someone should write a unit_test.
+        # one reason I have not, is I would want to use travis.cl, and scrapping probably violates policies.
+        # a unit test might begin like this:
+        # self.iterable.insert(0,("scholar"),str("arbitrary test")))
+        # self.iterable.insert(0,("wiki"),str("arbitrary test")))
+
+        _ = list(map(self.scrapelandtext,self.iterable))
+        return
diff --git a/science_access/t_analysis.py b/science_access/t_analysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ab72440a627dd1ddffe2594abe3c7b59cd02a75
--- /dev/null
+++ b/science_access/t_analysis.py
@@ -0,0 +1,247 @@
+# Scientific readability project
+# authors ...,
+# Russell Jarvis
+# https://github.com/russelljjarvis/
+# rjjarvis@asu.edu
+# Patrick McGurrin
+# patrick.mcgurrin@gmail.com
+
+
+import base64
+import copy
+import math
+import os
+import pickle
+import re
+import sys
+import time
+import collections
+
+#import matplotlib  # Its not that this file is responsible for doing plotting, but it calls many modules that are, such that it needs to pre-empt
+#matplotlib.use('Agg')
+
+import numpy as np
+import pandas as pd
+from nltk import pos_tag, sent_tokenize, word_tokenize
+from nltk.classify import NaiveBayesClassifier
+from nltk.corpus import cmudict, stopwords, subjectivity
+from nltk.probability import FreqDist
+from nltk.sentiment import SentimentAnalyzer
+from nltk.tag.perceptron import PerceptronTagger
+import nltk
+# english_check
+#from tabulate import tabulate
+from textblob import TextBlob
+from textstat.textstat import textstat
+tagger = PerceptronTagger(load=False)
+import matplotlib.pyplot as plt
+import numpy as np
+import pandas as pd
+import re
+import seaborn as sns
+
+from .utils import (black_string, clue_links, clue_words,
+                               comp_ratio, publication_check)
+
+
+def unigram_zipf(tokens):
+    '''
+    Get the zipf slope histogram for a corpus
+    '''
+    model = collections.defaultdict(lambda: 0.01)
+    tokens = [ term for t in tokens for term in t ]
+    model = {}
+
+    for word in tokens:
+        count = model.get(word,0)
+        model[word] = count + 1
+    '''
+    normalize observations relative to number of words in the model
+    '''
+    for word in model:
+        model[word] = model[word]/float(sum(model.values()))
+    return model
+    
+    
+#    https://github.com/nltk/nltk/blob/model/nltk/model/ngram.py
+
+def entropy(self, text):
+    """
+    https://github.com/nltk/nltk/blob/model/nltk/model/ngram.py
+    Calculate the approximate cross-entropy of the n-gram model for a
+    given evaluation text.
+    This is the average log probability of each word in the text.
+    :param text: words to use for evaluation
+    :type text: Iterable[str]
+    """
+
+    normed_text = (self._check_against_vocab(word) for word in text)
+    H = 0.0     # entropy is conventionally denoted by "H"
+    processed_ngrams = 0
+    for ngram in self.ngram_counter.to_ngrams(normed_text):
+        context, word = tuple(ngram[:-1]), ngram[-1]
+        H += self.logscore(word, context)
+        processed_ngrams += 1
+    return - (H / processed_ngrams)
+
+def perplexity(self, text):
+    """
+    Calculates the perplexity of the given text.
+    This is simply 2 ** cross-entropy for the text.
+    :param text: words to calculate perplexity of
+    :type text: Iterable[str]
+    """
+
+    return pow(2.0, self.entropy(text))   
+
+
+def zipf_plot(tokens):
+    # https://www.kaggle.com/kaitlyn/zipf-s-law
+    df = pd.DataFrame(tokens,columns='text')
+    df['clean_text'] = df.text.apply(lambda x: re.sub('[^A-Za-z\']', ' ', x.lower()))
+    # Create a word count dataframe
+    word_list = ' '.join(df.clean_text.values).split(' ')
+    words = pd.DataFrame(word_list, columns=['word'])
+    word_counts = words.word.value_counts().reset_index()
+    word_counts.columns = ['word', 'n']
+    word_counts['word_rank'] = word_counts.n.rank(ascending=False)    
+    f, ax = plt.subplots(figsize=(7, 7))
+    ax.set(xscale="log", yscale="log")
+    sns.regplot("n", "word_rank", word_counts, ax=ax, scatter_kws={"s": 100})
+    return
+
+
+def perplexity(testset, model):
+    # https://stackoverflow.com/questions/33266956/nltk-package-to-estimate-the-unigram-perplexity
+    perplexity = 1
+    N = 0
+    for word in testset:
+        N += 1
+        perplexity = perplexity + (1.0/model[word])
+    return perplexity
+
+def bi_log_value(value):
+    # Bi-symmetric log-like transformation, from:
+    # http://iopscience.iop.org/article/10.1088/0957-0233/24/2/027001/pdf
+    trans = np.sign(value)*np.log(1+np.abs(value*2.302585))
+    return trans
+    #df[col] = trans
+
+
+DEBUG = False
+#from numba import jit
+
+# word limit smaller than 1000 gets product/merchandise sites.
+def text_proc(corpus, urlDat = {}, WORD_LIM = 100):
+
+    #remove unreadable characters
+    if type(corpus) is str and str('privacy policy') not in corpus:
+        corpus = corpus.replace("-", " ") #remove characters that nltk can't read
+        textNum = re.findall(r'\d', corpus) #locate numbers that nltk cannot see to analyze
+        tokens = word_tokenize(corpus)
+
+        stop_words = stopwords.words('english')
+        #We create a list comprehension which only returns a list of words #that are NOT IN stop_words and NOT IN punctuations.
+
+        tokens = [ word for word in tokens if not word in stop_words]
+        tokens = [ w.lower() for w in tokens ] #make everything lower case
+
+        # the kind of change that might break everything
+        urlDat['wcount'] = textstat.lexicon_count(str(tokens))
+        word_lim = bool(urlDat['wcount']  > WORD_LIM)
+
+        ## Remove the search term from the tokens somehow.
+        urlDat['tokens'] = tokens
+
+        if 'big_model' in urlDat.keys():
+            urlDat['perplexity'] = perplexity(corpus, urlDat['big_model'])
+        else:
+            urlDat['perplexity'] = None
+        # Word limits can be used to filter out product merchandise websites, which otherwise dominate scraped results.
+        # Search engine business model is revenue orientated, so most links will be for merchandise.
+
+        urlDat['publication'] = publication_check(str(tokens))[1]
+        urlDat['clue_words'] = clue_words(str(tokens))[1]
+        if str('link') in urlDat.keys():
+            urlDat['clue_links'] = clue_links(urlDat['link'])[1]
+
+            temp = len(urlDat['clue_words'])+len(urlDat['publication'])+len(urlDat['clue_links'])
+            if temp  > 10 and str('wiki') not in urlDat['link']:
+                urlDat['science'] = True
+            else:
+                urlDat['science'] = False
+            if str('wiki') in urlDat['link']:
+                urlDat['wiki'] = True
+            else:
+                urlDat['wiki'] = False
+        # The post modern essay generator is so obfuscated, that ENGLISH classification fails, and this criteria needs to be relaxed.
+        not_empty = bool(len(tokens) != 0)
+
+        if not_empty and word_lim: #  and server_error:
+
+            tokens = [ w.lower() for w in tokens if w.isalpha() ]
+            #fdist = FreqDist(tokens) #frequency distribution of words only
+            # The larger the ratio of unqiue words to repeated words the more colourful the language.
+            lexicon = textstat.lexicon_count(corpus, True)
+            urlDat['uniqueness'] = len(set(tokens))/float(len(tokens))
+            # It's harder to have a good unique ratio in a long document, as 'and', 'the' and 'a', will dominate.
+            # big deltas mean redudancy/sparse information/information/density
+
+
+            urlDat['info_density'] =  comp_ratio(corpus)
+
+            #Sentiment and Subjectivity analysis
+            testimonial = TextBlob(corpus)
+            urlDat['sp'] = testimonial.sentiment.polarity
+            urlDat['ss'] = testimonial.sentiment.subjectivity
+            urlDat['sp_norm'] = np.abs(testimonial.sentiment.polarity)
+            urlDat['ss_norm'] = np.abs(testimonial.sentiment.subjectivity)
+            urlDat['gf'] = textstat.gunning_fog(corpus)
+
+            # explanation of metrics
+            # https://github.com/shivam5992/textstat
+
+            urlDat['standard'] = textstat.text_standard(corpus, float_output=True)
+            #urlDat['standard_'] = copy.copy(urlDat['standard'] )
+            # special sauce
+            # Good writing should be readable, objective, concise.
+            # The writing should be articulate/expressive enough not to have to repeat phrases,
+            # thereby seeming redundant. Articulate expressive writing then employs
+            # many unique words, and does not yield high compression savings.
+            # Good writing should not be obfucstated either. The reading level is a check for obfucstation.
+            # The resulting metric is a balance of concision, low obfucstation, expression.
+
+            wc = float(1.0/urlDat['wcount'])
+            # compressed/uncompressed. Smaller is better.
+            # as it means writing was low entropy, redundant, and easily compressible.
+            urlDat['scaled'] = wc * urlDat['standard']
+            urlDat['conciseness'] = urlDat['wcount']*(urlDat['uniqueness']) + \
+            urlDat['wcount']*(urlDat['info_density'])
+
+            urlDat['conciseness'] = bi_log_value(urlDat['conciseness'])
+            if urlDat['perplexity'] is not None:
+                urlDat['perplexity'] = bi_log_value(urlDat['perplexity'])
+
+                penalty = (urlDat['standard'] + urlDat['conciseness']+\
+                urlDat['scaled'] + urlDat['perplexity'])/4.0
+            else:
+                penalty = (urlDat['standard'] + urlDat['conciseness']+urlDat['scaled'] )/3.0
+
+            #computes perplexity of the unigram model on a testset
+            urlDat['penalty'] = penalty
+
+        return urlDat
+
+from tqdm import tqdm
+
+def process_dics(urlDats):
+    dfs = []
+    for urlDat in tqdm(urlDats):
+        # pandas Data frames are best data container for maths/stats, but steep learning curve.
+        # Other exclusion criteria. Exclude reading levels above grade 100,
+        # as this is most likely a problem with the metric algorithm, and or rubbish data in.
+        # TODO: speed everything up, by performing exclusion criteri above not here.
+        if len(dfs) == 0:
+            dfs = pd.DataFrame(pd.Series(urlDat)).T
+        dfs = pd.concat([ dfs, pd.DataFrame(pd.Series(urlDat)).T ])
+    return dfs
diff --git a/science_access/utils.py b/science_access/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..454d36048e214d76db49d4ced03816ea8a975854
--- /dev/null
+++ b/science_access/utils.py
@@ -0,0 +1,296 @@
+# Scientific readability project
+# authors: other_authors
+# Russell Jarvis
+# https://github.com/russelljjarvis/
+# rjjarvis@asu.edu
+
+# Patrick McGurrin
+# patrick.mcgurrin@gmail.com
+
+import os
+
+import pycld2 as cld2
+import lzma
+
+
+def isPassive(sentence):
+    # https://github.com/flycrane01/nltk-passive-voice-detector-for-English/blob/master/Passive-voice.py
+    beforms = ['am', 'is', 'are', 'been', 'was', 'were', 'be', 'being']               # all forms of "be"
+    aux = ['do', 'did', 'does', 'have', 'has', 'had']                                  # NLTK tags "do" and "have" as verbs, which can be misleading in the following section.
+    words = nltk.word_tokenize(sentence)
+    tokens = nltk.pos_tag(words)
+    tags = [i[1] for i in tokens]
+    if tags.count('VBN') == 0:                                                            # no PP, no passive voice.
+        return False
+    elif tags.count('VBN') == 1 and 'been' in words:                                    # one PP "been", still no passive voice.
+        return False
+    else:
+        pos = [i for i in range(len(tags)) if tags[i] == 'VBN' and words[i] != 'been']  # gather all the PPs that are not "been".
+        for end in pos:
+            chunk = tags[:end]
+            start = 0
+            for i in range(len(chunk), 0, -1):
+                last = chunk.pop()
+                if last == 'NN' or last == 'PRP':
+                    start = i                                                             # get the chunk between PP and the previous NN or PRP (which in most cases are subjects)
+                    break
+            sentchunk = words[start:end]
+            tagschunk = tags[start:end]
+            verbspos = [i for i in range(len(tagschunk)) if tagschunk[i].startswith('V')] # get all the verbs in between
+            if verbspos != []:                                                            # if there are no verbs in between, it's not passive
+                for i in verbspos:
+                    if sentchunk[i].lower() not in beforms and sentchunk[i].lower() not in aux:  # check if they are all forms of "be" or auxiliaries such as "do" or "have".
+                        break
+                else:
+                    return True
+    return False
+
+
+
+
+def argument_density(sentence0,sentence1):
+    # https://github.com/flycrane01/nltk-passive-voice-detector-for-English/blob/master/Passive-voice.py
+    CLAIMS = ['I think that', 'I believe that']               # all forms of "be"
+    CAUSAL = ['because','so','thus','therefore','since']                                  # NLTK tags "do" and "have" as verbs, which can be misleading in the following section.
+    terms = nltk.word_tokenize(sentence1)
+    #tokens = nltk.pos_tag(terms)
+    befores = []
+    for t in terms:
+        if t in CAUSAL:
+            befores.append(sentence0)
+    return befores
+
+
+
+        #for C in CAUSAL:
+        #    if
+
+    '''
+    tags = [i[1] for i in tokens]
+    if tags.count('VBN') == 0:                                                            # no PP, no passive voice.
+        return False
+    elif tags.count('VBN') == 1:                                    # one PP "been", still no passive voice.
+        return False
+    else:
+        pos = [i for i in range(len(tags)) if tags[i] == 'VBN' and words[i] != 'been']  # gather all the PPs that are not "been".
+        for end in pos:
+            chunk = tags[:end]
+            start = 0
+            for i in range(len(chunk), 0, -1):
+                last = chunk.pop()
+                if last == 'NN' or last == 'PRP':
+                    start = i                                                             # get the chunk between PP and the previous NN or PRP (which in most cases are subjects)
+                    break
+            sentchunk = words[start:end]
+            tagschunk = tags[start:end]
+            verbspos = [i for i in range(len(tagschunk)) if tagschunk[i].startswith('V')] # get all the verbs in between
+            if verbspos != []:                                                            # if there are no verbs in between, it's not passive
+                for i in verbspos:
+                    if sentchunk[i].lower() not in beforms and sentchunk[i].lower() not in aux:  # check if they are all forms of "be" or auxiliaries such as "do" or "have".
+                        break
+                else:
+                    return True
+    return False
+    '''
+
+def convert_pdf_to_txt(content):
+    pdf = io.BytesIO(content.content)
+    parser = PDFParser(pdf)
+    document = PDFDocument(parser, password=None) # this fails
+    write_text = ''
+    for page in PDFPage.create_pages(document):
+        interpreter.process_page(page)
+        write_text +=  retstr.getvalue()
+        #write_text = write_text.join(retstr.getvalue())
+    # Process all pages in the document
+    text = str(write_text)
+    return text
+
+def html_to_txt(content):
+    soup = BeautifulSoup(content, 'html.parser')
+    #strip HTML
+    for script in soup(["script", "style"]):
+        script.extract()    # rip it out
+    text = soup.get_text()
+    #organize text
+    lines = (line.strip() for line in text.splitlines())  # break into lines and remove leading and trailing space on each
+    chunks = (phrase.strip() for line in lines for phrase in line.split("  ")) # break multi-headlines into a line each
+    text = '\n'.join(chunk for chunk in chunks if chunk) # drop blank lines
+    str_text = str(text)
+    return str_text
+
+def comp_ratio(test_string):
+    # If we are agnostic about what the symbols are, and we just observe the relative frequency of each symbol.
+    # The distribution of frequencies would make some texts harder to compress, even if we don't know what the symbols mean.
+    # http://www.beamreach.org/data/101/Science/processing/Nora/Papers/Information%20entropy%20o%20fjumpback%20whale%20songs.pdf
+
+    c = lzma.LZMACompressor()
+    bytes_in = bytes(test_string,'utf-8')
+    bytes_out = c.compress(bytes_in)
+    return len(bytes_out)/len(bytes_in)
+
+def english_check(corpus):
+
+    # It's not that we are cultural imperialists, but the people at textstat, and nltk may have been,
+    # so we are also forced into this tacit agreement.
+    # Japanese characters massively distort information theory estimates, as they are potentially very concise.
+    _, _, details = cld2.detect(' '.join(corpus), bestEffort=True)
+    detectedLangName, _ = details[0][:2]
+    return bool(detectedLangName == 'ENGLISH')
+
+
+
+
+def engine_dict_list():
+    se = {0:"google",1:"yahoo",2:"duckduckgo",3:"wikipedia",4:"scholar",5:"bing"}
+    return se, list(se.values())
+
+def search_params():
+    SEARCHLIST = ["autosomes","respiration", "bacteriophage",'Neutron','Vaccine','Transgenic','GMO','Genetically Modified Organism','neuromorphic hardware', 'mustang unicorn', 'scrook rgerkin neuron', 'prancercise philosophy', 'play dough delicious deserts']
+    _, ses = engine_dict_list()
+    WEB = len(ses) #how many search engines to include (many possible- google google scholar bing yahoo)
+    LINKSTOGET= 10 #number of links to pull from each search engine (this can be any value, but more processing with higher number)
+    return SEARCHLIST, WEB, LINKSTOGET
+
+def search_known_corpus():
+    '''
+    hardcoded links to get. journal seek is a data base of known academic journals.
+    '''
+    LINKSTOGET = []
+    PUBLISHERS = str('https://journalseek.net/publishers.htm')
+    LINKSTOGET.append(str('https://academic.oup.com/beheco/article-abstract/29/1/264/4677340'))
+    LINKSTOGET.append(str('http://splasho.com/upgoer5/library.php'))
+    LINKSTOGET.append(str('https://elifesciences.org/download/aHR0cHM6Ly9jZG4uZWxpZmVzY2llbmNlcy5vcmcvYXJ0aWNsZXMvMjc3MjUvZWxpZmUtMjc3MjUtdjIucGRm/elife-27725-v2.pdf?_hash=WA%2Fey48HnQ4FpVd6bc0xCTZPXjE5ralhFP2TaMBMp1c%3D'))
+    LINKSTOGET.append(str('https://scholar.google.com/scholar?hl=en&as_sdt=0%2C3&q=Patrick+mcgurrin+ASU&btnG='))
+    LINKSTOGET.append(str('https://scholar.google.com/citations?user=GzG5kRAAAAAJ&hl=en&oi=sra'))
+    LINKSTOGET.append(str('https://scholar.google.com/citations?user=xnsDhO4AAAAJ&hl=en&oe=ASCII&oi=sra'))
+    LINKSTOGET.append(str('https://scholar.google.com/citations?user=2agHNksAAAAJ&hl=en&oi=sra'))
+    #_, ses = engine_dict_list()
+    WEB = 1
+    #WEB = len(ses) #how many search engines to include (many possible- google google scholar bing yahoo)
+    LINKSTOGET= 10 #number of links to pull from each search engine (this can be any value, but more processing with higher number)
+    return PUBLISHERS, WEB, LINKSTOGET
+
+
+
+
+
+def clue_links(check_with):
+    '''
+    The goal of this function/string comparison
+    is just to give a clue, about whether the text is
+    an official scientific publication, or a blog, or psuedo science publication
+    It is not meant to act as a definitive classifier.
+    '''
+    # TODO query with pyhthon crossref api
+
+    # https://pypi.org/project/crossrefapi/1.0.7/
+    CHECKS = [str('.fda'),str('.epa'),str('.gov'),str('.org'),str('.nih'),str('.nasa'),str('.pdf')]
+    assume_false = []
+    for check in CHECKS:
+        if check in check_with:
+            assume_false.append(check)
+    if len(assume_false) == 1:
+        return (True, assume_false)
+    else:
+        return (False, assume_false)
+
+
+def publication_check(wt):
+    '''
+    The goal of this function/string comparison
+    is just to give a clue, about whether the text is
+    an official scientific publication, or a blog, or psuedo science publication
+    It is not meant to act as a definitive classifier.
+    '''
+    publication = {}
+    if 'issn' in wt:
+        publication['issn'] = wt.split("issn",1)[1]
+    if 'isbn' in wt:
+        publication['isbn'] = wt.split("isbn",1)[1]
+    if 'pmid' in wt:
+        publication['pmid'] = wt.split("pmid",1)[1]
+    for k,v in publication.items():
+        publication[k] = v[0:15]
+
+    if len(publication) >= 1:
+        return (True, publication)
+    else:
+        return (False, publication)
+
+
+def clue_words(check_with):
+    '''
+    The goal of this function/string comparison
+    is just to give a clue, about whether the text is an official scientific publication, or a blog, or psuedo science publication
+    It is not meant to act as a definitive classifier.
+    To get ISSN (for any format) there is a national center in each country.
+    It may be National Library in some cases. List of National ISSN centers are listed in issn website.
+    For DOI, there are representatives in western countries, also you can apply to doi.org or crossref.org.
+    How are the e-ISSN Number, DOI and abbreviation provided for a new journal ?.
+    Available from: https://www.researchgate.net/post/How_are_the_e-ISSN_Number_DOI_and_abbreviation_provided_for_a_new_journal [accessed Apr 7, 2015].
+    '''
+    #TODO query with pyhthon crossref api
+    # https://pypi.org/project/crossrefapi/1.0.7/
+    # check_with should be lower cse now
+
+    CHECKS = [str('isbn'),str("issn"),str("doi"),str('volume'),str('issue'), \
+    str("journal of"),str("abstract"),str("materials and methods"),str("nature"), \
+    str("conflict of interest"), str("objectives"), str("significance"), \
+    str("published"), str("references"), str("acknowledgements"), str("authors"), str("hypothesis"), \
+    str("nih"),str('article'),str('affiliations'),str('et al')]
+    assume_false = []
+    for check in CHECKS:
+        if check in check_with:
+            assume_false.append(check)
+    if len(assume_false) >= 6:
+        return (True, assume_false)
+    else:
+        return (False, assume_false)
+
+
+def argument_density(check_with):
+    density_histogram = {}
+    # https://github.com/flycrane01/nltk-passive-voice-detector-for-English/blob/master/Passive-voice.py
+    CLAIMS = ['I think that', 'I believe that']               # all forms of "be"
+    CAUSAL = ['because','so','thus','therefore','since']                                  # NLTK tags "do" and "have" as verbs, which can be misleading in the following section.
+    for c in CLAIMS:
+        if c in check_with:
+            density_histogram[c] += 1
+    for c in CAUSAL:
+        if c in check_with:
+            density_histogram[c] += 1
+    return density_histogram
+
+
+
+def black_string(check_with):
+    if len(check_with) == 1145:
+        return True
+    #check="Privacy_policy"
+    #if check in check_with:
+    #    return True
+    check="Our systems have detected unusual traffic from your computer network.\\nThis page checks to see if it\'s really you sending the requests, and not a robot.\\nWhy did this happen?\\nThis page appears when Google automatically detects requests coming from your computer network which appear to be in violation of the Terms of Service. The block will expire shortly after those requests stop.\\nIn the meantime, solving the above CAPTCHA will let you continue to use our services.This traffic may have been sent by malicious software, a browser plug in, or a script that sends automated requests.\\nIf you share your network connection, ask your administrator for help  a different computer using the same IP address may be responsible.\\nLearn moreSometimes you may be asked to solve the CAPTCHA if you are using advanced terms that robots are known to use, or sending requests very quickly."
+    if check in check_with:
+        return True
+    check="Google ScholarLoading...The system can't perform the operation now."
+    if check in check_with:
+        return True
+    check="Please show you're not a robotSorry, we can't verify that you're not a robot when"
+    if check in check_with:
+        return True
+    check=" JavaScript is turned off.Please enable JavaScript in your browser and reload this page.HelpPrivacyTerms"
+    if check in check_with:
+        return True
+    if check in check_with:
+        return True
+    check = "\\x00\\x00\\x00\\x00"
+    if check in check_with:
+        return True
+    check = "Please click here if you are not redirected within a few seconds."
+    if check in check_with:
+        return True
+    check="DuckDuckGo  Privacy, simplified.\\nAbout DuckDuckGo\\nDuck it!\\nThe search engine that doesn\'t track you.\\nLearn More."
+    if check in check_with:
+        return True
+    return False
diff --git a/setup.py b/setup.py
index cf1fdf68a04911d11889f992f95e3928de56d7a6..a9fec82d711a9979de7ac154524656b889bacd5a 100644
--- a/setup.py
+++ b/setup.py
@@ -1,14 +1,14 @@
 
 #!/usr/bin/env python
 # old functional:
-#from distutils.core import setup
-#import setuptools
+from distutils.core import setup
+import setuptools
 
-# new dysfunctional.
-try:
-    from setuptools import setup
-except ImportError:
-    from distutils.core import setup, find_packages
+import os
+#try:
+from setuptools import setup
+#except ImportError:
+    #from distutils.core import setup, find_packages
 
 
 def read_requirements():
@@ -26,4 +26,8 @@ setup(name='scomplexity',
       author_email='don_t_email_we_are_on_github@gmail.com',
       url='https://github.com/russelljjarvis/ScienceAccessibility',
       packages = setuptools.find_packages()
-      )
+      ) 
+import nltk
+import nltk; nltk.download('punkt')
+import nltk; nltk.download('stopwords')
+os.system('bash install/user_install.sh')
\ No newline at end of file