Пример #1
0
def bio(request):

    # recieve value input and store it in estate
    estate = 'NY'
    if request.method == 'POST':
        estate = request.POST.get('name')
        print(request.POST)

    #store legislator API in data to iterate through
    po.set_api_key('001b2e03-a7f3-49b5-a7ed-99afe9e918d6')
    data = po.search_legislators(state=estate)
    form = inputForm()

    #iterate through list of dictionaries in data and store the specific keys in a list
    list = []
    for entry in data:

        #   print(entry['full_name'],entry['offices'][0]['email'])
        dic = {
            'full_name': entry['full_name'],
            'chamber': entry['chamber'],
            'district': entry['district'],
            'party': entry['party'],
            'email': entry['offices'][0]['email']
        }
        list.append(dic)

    #output the full name and email of all legislator in the data dictionary
    return render(request, 'bios/bio.html', {'list': list, 'form': form})
Пример #2
0
class DefaultConfig(object):
    PROJECT = 'CallPower'
    DEBUG = False
    TESTING = False
    VERSION = "1.4.0"
    ENVIRONMENT = os.environ.get('APP_ENVIRONMENT', "Default")

    APP_NAME = "call_server"
    APPLICATION_ROOT = None  # the path where the application is configured

    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URI',
        'sqlite:////%s/dev.db' % os.path.abspath(os.curdir))
    SQLALCHEMY_ECHO = False
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    BABEL_DEFAULT_LOCALE = 'en'
    BABEL_DEFAULT_TIMEZONE = 'UTC'
    ACCEPT_LANGUAGES = {'en': 'English',
                        'es': 'Spanish'}

    CACHE_TYPE = 'simple'
    CACHE_THRESHOLD = 100000  # because we're caching political data
    CACHE_DEFAULT_TIMEOUT = 60*60*24*365*2  # there's no infinite timeout, so default to 2 year election cycle

    CSRF_ENABLED = False

    INSTALLED_ORG = os.environ.get('INSTALLED_ORG')
    SITENAME = os.environ.get('SITENAME', PROJECT)

    STORE_PROVIDER = 'flask_store.providers.local.LocalProvider'
    STORE_DOMAIN = 'http://localhost:5000' # requires url scheme for Flask-store.absolute_url to work

    TWILIO_CLIENT = twilio.rest.Client(
        os.environ.get('TWILIO_ACCOUNT_SID'),
        os.environ.get('TWILIO_AUTH_TOKEN'))
    TWILIO_PLAYBACK_APP = os.environ.get('TWILIO_PLAYBACK_APP')
    # limit on the length of the call
    TWILIO_TIME_LIMIT = os.environ.get('TWILIO_TIME_LIMIT', 60 * 60)  # one hour max
    # limit on the amount of time to ring before giving up
    TWILIO_TIMEOUT = os.environ.get('TWILIO_TIMEOUT', 60)  # seconds

    SECRET_KEY = os.environ.get('SECRET_KEY')

    GEOCODE_API_KEY = os.environ.get('GEOCODE_API_KEY')
    OPENSTATES_API_KEY = os.environ.get('OPENSTATES_API_KEY')
    if not OPENSTATES_API_KEY:
        OPENSTATES_API_KEY = os.environ.get('OPENSTATES_API_KEY')
    pyopenstates.set_api_key(OPENSTATES_API_KEY)

    LOG_PHONE_NUMBERS = True

    MAIL_SERVER = 'localhost'

    CRM_INTEGRATION = os.environ.get('CRM_INTEGRATION')
    if CRM_INTEGRATION == 'ActionKit':
        ACTIONKIT_DOMAIN = os.environ.get('ACTIONKIT_DOMAIN')
        ACTIONKIT_USER = os.environ.get('ACTIONKIT_USER')
        ACTIONKIT_API_KEY = os.environ.get('ACTIONKIT_API_KEY')
        ACTIONKIT_PASSWORD = os.environ.get('ACTIONKIT_PASSWORD')
Пример #3
0
class Chamber:

    pyos.set_api_key(pyopenstates_key)

    def __init__(self, state, chamber):
        self.state = state
        self.chamber = chamber
        self._members = None
        self._current_session_bills = None

    @property
    def members(self):
        if self._members is None:
            #df = pd.read_sql('',connection)

            print('...downloading.....')
            results = pyos.search_legislators(state=self.state,
                                              chamber=self.chamber)
            print('..parsing.......')
            df = pd.DataFrame(results)
            columns = [
                'id', 'all_ids', 'full_name', 'first_name', 'last_name',
                'district', 'party', 'roles', 'created_at', 'updated_at'
            ]

            self._members = df[columns]
            #self._members['role_count'] = df['roles'].map(lambda x: len(x))

        return self._members

    @property
    def current_session_bills(self):
        if self._current_session_bills is None:

            print('...downloading.....')
            results = pyos.search_bills(state=self.state,
                                        chamber=self.chamber,
                                        search_window='session')
            print('..parsing.......')
            df = pd.DataFrame(results)
            columns = [
                'bill_id', 'title', 'action_dates', 'actions', 'created_at',
                'sources', 'sponsors', 'summary', 'updated_at', 'versions'
            ]

            if self.chamber == 'upper':
                df = df[df.bill_id.str.startswith('S')]
                self._current_session_bills = df[columns]
            elif self.chamber == 'lower':
                df = df[df.bill_id.str.startswith('A')]
                self._current_session_bills = df[columns]
            #self._current_session_bills['sponsor_count'] = df['sponsors'].map(lambda x: len(x))

        return self._current_session_bills
Пример #4
0
 def query(self):
     pyopenstates.set_api_key(config.OPENSTATES_API_KEY)
        else:
            score = round(total_right / float(total_possible),3)
        
        lines = line + ',' + str(score) + ',' + str(letter_score) + '\n')
    return lines

# Main:
# Validate input
if len(sys.argv) < 2:
    raise ValueError("Must provide input file as argument in command line")
input_file = sys.argv[1]
if not os.path.isfile(input_file):
    raise ValueError("Input file does not exist: " + input_file)

# Setup Open States API Client
osClient.set_api_key(config.openstates_api_key)

upper_legislators = GetLegislators(state=config.state, chamber='upper')
lower_legislators = GetLegislators(state=config.state, chamber='lower')

tracked_votes = []
for line in open(input_file):
    if line.startswith('#'):
        continue
    input_vote_info = line.strip('\n\r').split(',')
    tracked_votes.append({
        'vote_session' : input_vote_info[0],
        'vote_bill_no' : input_vote_info[1],
        'vote_id' : input_vote_info[2],
        'vote_preference' : input_vote_info[3],
        'vote_weight' : input_vote_info[4]
Пример #6
0
"""
    This file searches for NJ Political information
"""
import os
import json
from datetime import datetime, timedelta
from dotenv import load_dotenv
import pyopenstates

load_dotenv()

API_KEY = os.getenv("POLITICS_API_KEY")
pyopenstates.set_api_key(API_KEY)

BILL_CACHE_FILE = "bill_cache.json"
POLITICIAN_CACHE_FILE = "politician_cache.json"

BILL_CACHE_LIFE = 21600

POLITICIAN_CACHE_LIFE = 86400


def get_cached_bills():
    """Get bills that have been cached"""
    with open(BILL_CACHE_FILE, "r", encoding="utf8") as cache:
        old_response = json.load(cache)
        if "timestamp" not in old_response:
            return None
        curr_time = datetime.now().timestamp()
        if curr_time - old_response["timestamp"] < BILL_CACHE_LIFE:
            return old_response
Пример #7
0
import requests
from lxml import html
import re, os
import datetime

from dex.models import *

import pyopenstates

from MnHouseMemAdditionalInfo import process_text, parse_info, get_member

apiKey = 'd2c0db7e-6a6e-4606-a9b0-83c18e647ff6'
state = raw_input("Which state? ")
# state = sys.argv[1]
pyopenstates.set_api_key(apiKey)


DIGISTATE = dx_State.objects.get(state_name__code=state)
HOUSE, c1 = Org.objects.get_or_create(name="MN House of Representative",
                                      digistate=DIGISTATE)
SENATE, c2 = Org.objects.get_or_create(name="MN State Senate",
                                       digistate=DIGISTATE)

cmts = pyopenstates.search_committees(state=state)
reps = pyopenstates.search_legislators(state=state)
districts_lower = pyopoenstates.search_districts(state=state, chamber="lower")
#districts_upper = pyopenstates.search_districts(state=state, chamber="upper")
bills_upper = pyopenstates.search_bills(state=state, chamber="upper", updated_since="2017-01-01")
bills_lower = pyopenstates.search_bills(state=state, chamber="lower", updated_since="2017-01-01")
Пример #8
0
 def __init__(self):
     pyopenstates.set_api_key(config.OPENSTATES_API_KEY)
     self.raw_dictionary = pyopenstates.get_metadata(state=config.STATE)
     self.latest_term_name = self.raw_dictionary['terms'][-1]['name']
     self.latest_session_name = self.raw_dictionary['terms'][-1][
         'sessions'][-1]
Пример #9
0
    def scrape(self):
        state = 'MN'
        session = self.jurisdiction.legislative_sessions[0]
        apiKey = 'd2c0db7e-6a6e-4606-a9b0-83c18e647ff6'
        pyopenstates.set_api_key(apiKey)
        bills_upper = pyopenstates.search_bills(state=state,
                                                chamber="upper",
                                                updated_since="2017-01-01")
        bills_lower = pyopenstates.search_bills(state=state,
                                                chamber="lower",
                                                updated_since="2017-01-01")

        for b in bills_lower:
            number = b['bill_id']
            title = b['title']
            bill_id = b['id']
            dbill = pyopenstates.get_bill(bill_id)
            url = dbill['sources'][0]['url']

            bill = Bill(identifier=number,
                        legislative_session=session['identifier'],
                        title=title,
                        classification=b['type'][0],
                        chamber='upper')
            bill.add_source(url)
            bill.add_identifier(bill_id, scheme='openstatesv1')

            subjects = b['subjects']
            for s in subjects:
                bill.add_subject(s)

            sponsors = dbill['sponsors']
            for sponsor in sponsors:
                if not sponsor['leg_id'] == None:
                    l = pyopenstates.get_legislator(sponsor['leg_id'])
                    full_name = l['full_name'].split(' ')
                    if len(full_name) == 3:
                        full_name.pop(1)
                    full_name = (' ').join(full_name)
                    primary = False
                    if sponsor['type'] == 'primary':
                        primary = True
                    try:
                        bill.add_sponsorship(name=full_name,
                                             classification=sponsor['type'],
                                             entity_type='person',
                                             primary=primary)
                    except:
                        pass

            actions = dbill['actions']
            for act in actions:
                action = act['action']
                actor = act['actor']
                date = tz.localize(datetime.strptime(act['date'], DATE_FORMAT))
                Action_Type = act['type']
                bill.add_action(action, date, chamber=actor)

            action_dates = dbill['action_dates']
            for act in action_dates.items():
                k, v = act[0], act[1]
                if '_' in k:
                    chamber = k.split('_')[1]
                elif k == 'signed':
                    chamber = 'executive'
                else:
                    chamber = None
                k.replace('_', ' ')
                if not v == None and not k in ['first', 'last']:
                    bill.add_action(k, tz.localize(v), chamber=chamber)
            yield bill

        for b in bills_upper:
            number = b['bill_id']
            title = b['title']
            bill_id = b['id']
            dbill = pyopenstates.get_bill(bill_id)
            url = dbill['sources'][0]['url']

            bill = Bill(identifier=number,
                        legislative_session=session['identifier'],
                        title=title,
                        classification=b['type'][0],
                        chamber='upper')
            bill.add_source(url)
            bill.add_identifier(bill_id, scheme='openstatesv1')

            subjects = b['subjects']
            for s in subjects:
                bill.add_subject(s)

            sponsors = dbill['sponsors']
            for sponsor in sponsors:
                if not sponsor['leg_id'] == None:
                    l = pyopenstates.get_legislator(sponsor['leg_id'])
                    full_name = l['full_name'].split(' ')
                    if len(full_name) == 3:
                        full_name.pop(1)
                    full_name = (' ').join(full_name)
                    primary = False
                    if sponsor['type'] == 'primary':
                        primary = True
                    try:
                        bill.add_sponsorship(name=full_name,
                                             classification=sponsor['type'],
                                             entity_type='person',
                                             primary=primary)
                    except:
                        pass

            actions = dbill['actions']
            for act in actions:
                action = act['action']
                actor = act['actor']
                date = tz.localize(datetime.strptime(act['date'], DATE_FORMAT))
                Action_Type = act['type']
                bill.add_action(action, date, chamber=actor)

            action_dates = dbill['action_dates']
            for act in action_dates.items():
                k, v = act[0], act[1]
                if '_' in k:
                    chamber = k.split('_')[1]
                elif k == 'signed':
                    chamber = 'executive'
                else:
                    chamber = None
                k.replace('_', ' ')
                if not v == None and not k in ['first', 'last']:
                    bill.add_action(k, tz.localize(v), chamber=chamber)
            yield bill
Пример #10
0
 def __init__(self):
     # validate API key
     pyopenstates.set_api_key(app.config['OPENSTATES_API_KEY'])
     self.search_window = "term"  #only this session
Пример #11
0
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core.  If not, see <http://www.gnu.org/licenses/>.

from adapt.intent import IntentBuilder

from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger

import us
import pyopenstates
pyopenstates.set_api_key('0e79f99b-a749-4ebc-961c-4801400294d2')

__author__ = 'eClarity'

LOGGER = getLogger(__name__)


class OpenStatesSkill(MycroftSkill):
    def __init__(self):
        super(OpenStatesSkill, self).__init__(name="OpenStatesSkill")
        self.name_given = False

    def initialize(self):
        search_bills_intent = IntentBuilder("SearchBillsIntent"). \
            require("SearchBillsKeyword").require("State").build()
        self.register_intent(search_bills_intent,