Guest User

Untitled

a guest
Mar 23rd, 2021
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.08 KB | None | 0 0
  1. import numpy as np
  2. import json
  3. import pandas as pd
  4.  
  5. import requests
  6. import requests_cache
  7.  
  8. requests_cache.install_cache('cache', allowable_methods=("POST","GET"))
  9.  
  10. def get_json(restarttoken=None, count=3000, active=True):
  11.     if not restarttoken:
  12.         restarttoken = ""
  13.  
  14.     else:
  15.         restarttoken = json.dumps(restarttoken)
  16.         print(restarttoken)
  17.  
  18.     modelid = 404287
  19.     if not active:
  20.         modelid = 404284
  21.  
  22.     headers = {
  23.         'Connection': 'keep-alive',
  24.         'sec-ch-ua': '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
  25.         'DNT': '1',
  26.         'sec-ch-ua-mobile': '?0',
  27.         'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36',
  28.  
  29.         # active
  30.         'ActivityId': '66b5ae32-554c-470a-9c78-b54a8718b77c',
  31.         'Accept': 'application/json, text/plain, */*',
  32.         'RequestId': '2c7ab566-5a12-fe1a-0ac5-c54dd3d9c532',
  33.         'X-PowerBI-ResourceKey': 'b2c8d2f2-3ad1-48dc-883c-d4163a6e2d8f',
  34.  
  35.  
  36.         'Content-Type': 'application/json;charset=UTF-8',
  37.         'Origin': 'https://app.powerbigov.us',
  38.         'Sec-Fetch-Site': 'cross-site',
  39.         'Sec-Fetch-Mode': 'cors',
  40.         'Sec-Fetch-Dest': 'empty',
  41.         'Referer': 'https://app.powerbigov.us/',
  42.         'Accept-Language': 'en-US,en;q=0.9',
  43.     }
  44.  
  45.     if not active:
  46.         headers.update({
  47.             # inactive
  48.             'ActivityId': '4e140a40-456c-4847-bd80-f17e1ddaf836',
  49.             'Accept': 'application/json, text/plain, */*',
  50.             'RequestId': '2814cc0b-5dce-7363-7dba-b948e9387405',
  51.             'X-PowerBI-ResourceKey': '87914378-578f-4f43-b75e-8ddaeafbdda2',
  52.         })
  53.  
  54.  
  55.     params = (
  56.         ('synchronous', 'true'),
  57.     )
  58.  
  59.  
  60.     data = """
  61.    {
  62.      "version": "1.0.0",
  63.      "queries": [
  64.        {
  65.          "Query": {
  66.            "Commands": [
  67.              {
  68.                "SemanticQueryDataShapeCommand": {
  69.                  "Query": {
  70.                    "Version": 2,
  71.                    "From": [
  72.                      {
  73.                        "Name": "q1",
  74.                        "Entity": "CCRB Active - Oracle",
  75.                        "Type": 0
  76.                      }
  77.                    ],
  78.                    "Select": [
  79.  
  80.  
  81.    { "Name": "Query1.Unique Id", "Column": { "Expression": { "SourceRef": { "Source": "q1" } }, "Property": "Unique Id" }, },
  82.    { "Name": "Query1.Command1", "Column": { "Expression": { "SourceRef": { "Source": "q1" } }, "Property": "Command" }, },
  83.    { "Name": "Query1.Last Name1", "Column": { "Expression": { "SourceRef": { "Source": "q1" } }, "Property": "Last Name" }, },
  84.    { "Name": "Query1.First Name1", "Column": { "Expression": { "SourceRef": { "Source": "q1" } }, "Property": "First Name" }, },
  85.    { "Name": "Query1.Rank1", "Column": { "Expression": { "SourceRef": { "Source": "q1" } }, "Property": "Rank" }, },
  86.    { "Name": "Query1.ShieldNo", "Column": { "Expression": { "SourceRef": { "Source": "q1" } }, "Property": "Shield No" }, },
  87.    { "Name": "Query1.Complaint Id", "Column": { "Expression": { "SourceRef": { "Source": "q1" } }, "Property": "Complaint ID" }, },
  88.    { "Name": "Query1.Sub Complaints", "Column": { "Expression": { "SourceRef": { "Source": "q1" } }, "Property": "Sub Complaints" }, },
  89.    { "Name": "Query1.Total Complaints", "Column": { "Expression": { "SourceRef": { "Source": "q1" } }, "Property": "Total Complaints" }, },
  90.  
  91.  
  92.  
  93.                    ],
  94.                    "Where": [
  95.  
  96.  
  97.                    ],
  98.                    "OrderBy": [
  99.                      {
  100.                        "Direction": 1,
  101.                        "Expression": {
  102.                          "Column": {
  103.                            "Expression": {
  104.                              "SourceRef": {
  105.                                "Source": "q1"
  106.                              }
  107.                            },
  108.                            "Property": "Command"
  109.                          }
  110.                        }
  111.                      }
  112.                    ]
  113.                  },
  114.                  "Binding": {
  115.                    "Primary": {
  116.                      "Groupings": [
  117.                        {
  118.                          "Projections": [
  119.                            0,
  120.                            1,
  121.                            2,
  122.                            3,
  123.                            4,
  124.                            5,
  125.                            6,
  126.                            7,
  127.                            8,
  128.                          ]
  129.                        }
  130.                      ]
  131.                    },
  132.                    "DataReduction": {
  133.                      "Primary": {
  134.                        "Window": {
  135.                          "Count": %i,
  136.                          "RestartTokens": [%s],
  137.                        }
  138.                      }
  139.                    },
  140.                    "Version": 1
  141.                  }
  142.                }
  143.              }
  144.            ]
  145.          },
  146.          "QueryId": "",
  147.          "ApplicationContext": {
  148.            "DatasetId": "523ab509-8e2d-43ed-bfad-11fcd05180d7",
  149.            "Sources": [
  150.              {
  151.                "ReportId": "f508555a-b39d-4c10-8d46-a14bc282e079"
  152.              }
  153.            ]
  154.          }
  155.        }
  156.      ],
  157.      "cancelQueries": [],
  158.      "modelId": %i
  159.    }
  160.    """ % (count, restarttoken, modelid)
  161.  
  162.     response = requests.post('https://wabi-us-gov-virginia-api.analysis.usgovcloudapi.net/public/reports/querydata', headers=headers, params=params, data=data)
  163.  
  164.     print(response.from_cache)
  165.  
  166.     return response.json()
  167.  
  168.  
  169. def parse_json(data):
  170.     if "results" not in data:
  171.         print(data)
  172.     try:
  173.         restarttoken = data["results"][0]["result"]["data"]["dsr"]["DS"][0]["RT"][0]
  174.     except:
  175.         restarttoken = None
  176.     # print(restarttoken)
  177.     rawrows = data["results"][0]["result"]["data"]["dsr"]["DS"][0]["PH"][0]["DM0"]
  178.  
  179.     rawlookup = data["results"][0]["result"]["data"]["dsr"]["DS"][0]["ValueDicts"]
  180.     lookup = dict()
  181.     for k, v in rawlookup.items():
  182.         lookup[int(k[1:])] = v
  183.         # print(k, len(v), v)
  184.         # print()
  185.  
  186.     def get_indices(mask):
  187.         indices = []
  188.         for i in range(16):
  189.             if mask & (2 << i):
  190.                 indices.append(i+1)
  191.         return indices
  192.  
  193.     rows = []
  194.     # allowed_lookups = set()
  195.     for ix,x in enumerate(rawrows):
  196.         # if ix == 0:
  197.         #     print(x)
  198.  
  199.         rawrow = x["C"]
  200.         mask = x.get("R", 0)
  201.         indices = []
  202.         if mask > 0:
  203.             indices = get_indices(mask)
  204.             for idx in indices:
  205.                 rawrow.insert(idx, None)
  206.         row = []
  207.         for i,c in enumerate(rawrow):
  208.             if isinstance(c, int) and (i in lookup) and (c < 1e6):
  209.                 row.append(lookup[i][c])
  210.             else:
  211.                 row.append(c)
  212.  
  213.         rows.append(row)
  214.  
  215.     df = pd.DataFrame(rows)
  216.     df = df.ffill()
  217.     return restarttoken, df
  218.  
  219. if __name__ == "__main__":
  220.  
  221.     count = 10000
  222.  
  223.     dfs = []
  224.  
  225.     for active in [True, False]:
  226.         restarttoken = None
  227.         for i in range(50):
  228.             if i > 0 and not restarttoken:
  229.                 break
  230.             data = get_json(restarttoken, count, active=active)
  231.             restarttoken, df = parse_json(data)
  232.             print(active, i, restarttoken, df.shape)
  233.             df["active"] = active
  234.             dfs.append(df)
  235.  
  236.  
  237.     dfc = pd.concat(dfs)
  238.     dfc.columns = [
  239.             "id",
  240.             "command",
  241.             "lastname",
  242.             "firstname",
  243.             "rank",
  244.             "shieldno",
  245.             "complaintid",
  246.             "subcomplaints",
  247.             "totcomplaints",
  248.             "active",
  249.             ]
  250.     print(dfc)
  251.  
  252.     dfc = dfc.dropna()
  253.     dfc["totcomplaints"] = dfc["totcomplaints"].astype(int)
  254.     dfc = dfc.drop_duplicates(["command","lastname","firstname","shieldno"]).drop(columns=["complaintid"])
  255.     dfc = dfc.reset_index(drop=True)
  256.  
  257.     dfc.to_json("overview.jsonl.gz", lines=True, orient="records")
  258.  
Advertisement
Add Comment
Please, Sign In to add comment