index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
54,024 | tylhhh/API_qianchengdai | refs/heads/master | /扩展学习/04_request请求操作.py | import requests
# url = "http://api.lemonban.com/futureloan/member/login"
# data = {"mobile_phone":"18600001112","pwd":"123456789"}
# headers = {"X-Lemonban-Media-Type": "lemonban.v2","Content-Type":"application/json"}
# resp = requests.post(url, json=data, headers=headers)
# # 响应状态码
# print(resp.status_code)
# # 响应头
# print(resp.headers)
# # 响应体
# print(resp.json())
"""
requests实现cookies鉴权
方法一:创建一个会话对象,自动去获取
"""
print("\n************************************requests实现cookies鉴权,方法一**********************************************")
# 实例化Session()对象
s = requests.Session()
# 登录,获取cookies鉴权,即cookies的值
login_url = "https://v4.ketangpai.com/UserApi/login"
login_data = {"email": "2441413919@qq.com", "password": "a1b2c3d4", "remember": 0}
s.post(login_url, data=login_data) # 主动将响应中的set-cookies添加到对象中
print("登录之后的cookies:",s.cookies)
# 获取用户信息
user_url = "https://v4.ketangpai.com/UserApi/getUserInfo"
resp = s.get(user_url)
print(resp.json())
"""
requests实现cookies鉴权
方法二:需要自己主动获取cookies,并在后续的请求中,主动加上cookies
"""
print("\n************************************requests实现cookies鉴权,方法二**********************************************")
login_url = "https://v4.ketangpai.com/UserApi/login"
login_data = {"email": "2441413919@qq.com", "password": "a1b2c3d4", "remember": 0}
resp = requests.post(url=login_url,data=login_data)
print(resp.json())
# 主动获取cookies
cookies = resp.cookies
print("主动获取的cookies:",cookies)
# 获取用户信息
user_url = "https://v4.ketangpai.com/UserApi/getUserInfo"
resp = requests.get(user_url,cookies=cookies)
print(resp.json())
"""
requests实现token鉴权
"""
print("\n************************************requests实现token鉴权**********************************************")
# 登录,获取token
login = "http://api.lemonban.com/futureloan/member/login"
login_datas = {"mobile_phone":"18678451245","pwd":"123456789"}
headers = {"X-Lemonban-Media-Type": "lemonban.v2","Content-Type":"application/json"}
resp = requests.post(login, json=login_datas, headers=headers)
print(resp.json())
# 在响应中获取token的值
token = resp.json()["data"]["token_info"]["token"]
# 在响应中获取member_id的值
member_id = resp.json()["data"]["id"]
print(token)
# 充值,将token添加到请求头当中
headers["Authorization"] = "Bearer {}".format(token)
"""
客服系统后台登录鉴权
"""
print("\n************************************客服系统后台登录鉴权**********************************************")
dandian_login_url="https://passport.ijunhai.com/auth/login"
dandian_login_data ={"username":"tangyuling002","password":"u06ivJGV","redirect_url":"https://cshw-test.ijunhai.com/login","application_id":21}
headers = {"Content-Type":"application/json"}
resp = requests.post(url=dandian_login_url,json=dandian_login_data,headers=headers)
print(resp.json())
# 1、获取单点系统授权的code
code = resp.json()["content"]["code"]
kefu_login_url="https://cshw-test.ijunhai.com/api/login"
kefu_login_data = {"code":code}
resp = requests.post(url=kefu_login_url,json=kefu_login_data,headers=headers)
# 2、获取客服后台登录后的token值
token = resp.json()["token"]
# 3、将token添加到请求头当中
headers["authorization"] = "Bearer {}".format(token)
# 例如获取个人信息
get_me_url = "https://cshw-test.ijunhai.com/api/admin/staff/me"
resp = requests.get(url=get_me_url,headers=headers)
print(resp.json())
"""
少女心后台登录鉴权,token值就是单点登录后的code值,放在请求参数中
"""
print("\n************************************少女心后台登录鉴权**********************************************")
dandian_login_url="https://passport.ijunhai.com/auth/login"
dandian_login_data ={"username":"tangyuling002","password":"u06ivJGV","redirect_url":"http://mkt.itrigirls.com:8090/ad-system.html","application_id":21}
headers = {"Content-Type":"application/json"}
resp = requests.post(url=dandian_login_url,json=dandian_login_data,headers=headers)
print(resp.json())
# 1、获取单点系统授权的code
code = resp.json()["content"]["code"]
itrigirls_login_url="http://mkt.itrigirls.com:8090/v1/login"
itrigirls_login_data = {"auth_code":code}
resp = requests.get(url=itrigirls_login_url,params=itrigirls_login_data)
print(resp.json())
# 将auth_code值添加到请求参数中,例如获取素材数据
material_url = "http://mkt.itrigirls.com:8090/v1/material/getFile"
material_data = {"pid":"","per_page":100,"page":1,"search":"","material_type":[],"material_size":[],"material_format":[],"creator":[],"date":[],"order_field":"created_at","order_type":"desc","tag_ids":[],"auth_token":code}
resp = requests.post(url=material_url,json=material_data)
print(resp.json())
| {"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]} |
54,025 | tylhhh/API_qianchengdai | refs/heads/master | /TestCases/test_update_name.py | import unittest
import json
from Common.handle_excel import HandleExcel
from Common.myddt import ddt,data
from Common.handle_path import datas_dir
from Common.handle_log import logger
from Common.handle_requests import send_requests
from Common.handle_data import replace_case_by_regular,EnvData,clear_EnvData_atts
from Common.handle_phone import get_old_phone
from jsonpath import jsonpath
get_excel = HandleExcel(datas_dir+"/api_cases.xlsx","更新昵称")
cases = get_excel.read_all_datas()
get_excel.close_file()
@ddt
class TestUpdate(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
logger.info("****************************登录前置*******************************")
clear_EnvData_atts() # 清理EnvData里设置的属性
user, passwd = get_old_phone()
resp = send_requests("POST", "member/login", {"mobile_phone": user, "pwd": passwd})
setattr(EnvData, "member_id", jsonpath(resp.json(), "$..id")[0])
setattr(EnvData, "token", jsonpath(resp.json(), "$..token")[0])
def tearDown(self) -> None:
logger.info("****************************更新用户信息用例结束*******************************")
@data(*cases)
def test_update(self,case):
logger.info("***************执行第{}条用例:{}*********************".format(case["case_id"], case["title"]))
if case["request_data"].find("#member_id#") != -1:
case = replace_case_by_regular(case)
resp = send_requests(case["method"],case["url"],case["request_data"], token=EnvData.token)
expected = json.loads(case["expected"])
logger.info("用例的期望结果为:{}".format(expected))
try:
self.assertEqual(resp.json()["code"], expected["code"])
self.assertEqual(resp.json()["msg"], expected["msg"])
except AssertionError as e:
logger.exception("断言失败!")
raise e
| {"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]} |
54,026 | tylhhh/API_qianchengdai | refs/heads/master | /扩展学习/07_动态设置类属性.py | """
反射:指通过“字符串”对 对象的属性和方法进行操作(查找/获取/删除/添加)
反射常常用在动态加载的模块中
hasattr:通过“字符串”判断对象的属性或方法是否存在
getattr:通过“字符串”获取对象的属性或方法
setattr:通过“字符串”设置对象的属性或方法
delattr:通过“字符串”删除对象的属性或方法
"""
class AAA:
name = "小明"
pass
s = AAA()
setattr(s, "age", 18)
setattr(s, "name", "哈哈哈")
setattr(AAA,"age", 20)
print(getattr(s, "age"))
print(hasattr(s, "age"))
# delattr(s, "age")
# print(hasattr(s, "age"))
print(AAA.__dict__) # 打印类中的属性有哪些
print(s.__dict__) # 打印实例化对象的属性有哪些
print(AAA.age)
# 清理类属性
values = dict(AAA.__dict__)
for key,value in values.items():
if key.startswith("__"):
pass
else:
delattr(AAA, key)
print(AAA.__dict__)
# 清理对象属性
values = dict(s.__dict__)
for key,value in values.items():
delattr(s, key)
print(s.__dict__)
| {"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]} |
54,027 | tylhhh/API_qianchengdai | refs/heads/master | /main.py | import unittest
from BeautifulReport import BeautifulReport
from Common.handle_path import cases_dir,reports_dir
s = unittest.TestLoader().discover(cases_dir)
br = BeautifulReport(s)
br.report("前程贷接口自动化测试报告","report_html",reports_dir)
| {"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]} |
54,028 | tylhhh/API_qianchengdai | refs/heads/master | /扩展学习/12_随机生成手机号码.py | """
随机字符:random.choice('abcdefghijklmnopqrstuvwxyz!@#$%^&*()')
生成指定数量的随机字符:random.sqmple('zyxwvutsrqponmlkjihgfedcba',5)
从a-zA-Z0-9生成指定数量的随机字符:ran_str = ''.join(random.sample(string.ascii_letters + string.digits,8))
"""
# 第一种方法
import string
import random
num_start = ['134', '135', '136', '137', '138', '139', '150', '151', '152', '158', '159', '157', '182', '187', '188',
'147', '130', '131', '132', '155', '156', '185', '186', '133', '153', '180', '189']
def phone_num():
start = random.choice(num_start)
end = ''.join(random.sample(string.digits,8))
res = start+end
return res
print(phone_num())
# 第二种方法
def generator_phone():
index = random.randint(0, len(num_start)-1)
phone = str(num_start[index])
for _ in range(8):
phone += str(random.randint(0,9))
return phone
print(generator_phone())
# 第三种方法
def mobile():
start = random.choice(num_start)
phone = start + ''.join(random.choice("0123456789") for _ in range(8))
return phone
print(mobile())
| {"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]} |
54,029 | tylhhh/API_qianchengdai | refs/heads/master | /扩展学习/06_jsonpath应用.py | """
文章地址:
http://www.lemfix.com/topics/63
安装:pip install jsonpath
使用方式:jsonpath.jsonpath(字典对象,jsonpath表达式)
返回值:列表。
jsonpath用来解析多层嵌套的json数据
使用方法如下:
import jsonpath
res = jsonpath.jsonpath(dic_name,'$..key_name')
嵌套n层也能取到所有key_name信息,其中“$”表示最外层{},“..”表示模块匹配,当不传入不存在的key_name时,程序会返回false
"""
import jsonpath
d={
"error_code": 0,
"stu_info": [
{
"id": 2059,
"name": "小白",
"sex": "男",
"age": 28,
"addr": "河南省济源市北海大道32号",
"grade": "天蝎座",
"phone": "18378309272",
"gold": 10896,
"info":{
"card":434345432,
"bank_name":'中国银行'
}
},
{
"id": 2067,
"name": "小黑",
"sex": "男",
"age": 28,
"addr": "河南省济源市北海大道32号",
"grade": "天蝎座",
"phone": "12345678915",
"gold": 100
}
]
}
res = jsonpath.jsonpath(d, "$..name") # $表示最外层的{},获取所有学生姓名,存放在列表中
print(res)
a = jsonpath.jsonpath(d, "$..name")[0]
print(a)
res1 = jsonpath.jsonpath(d, "$.stu_info.[0].info.bank_name")
print(res1)
| {"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]} |
54,050 | ngpham/petits | refs/heads/master | /rrtl/rrtl/__init__.py | from .parser import Parser
from .symbol import SymbolType, Symbol
from .vertex import Vertex, VertexCluster
from .edge import Edge
from .graph import Graph
from .debug import Debug
from .clause import Clause, ClausesSet, Cycle, Verifier
from . import transform as __just_for_execution_of_the_module
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,051 | ngpham/petits | refs/heads/master | /pmdbpy/pmdbpy/util.py | import functools
def overrides(*classes):
def overrider(method):
assert(method.__name__ in
functools.reduce(lambda a, b: set(a) | set(b), map(dir, classes), set()))
return method
return overrider
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,052 | ngpham/petits | refs/heads/master | /pmdbpy/pmdbpy/command.py | import enum
import pmdbpy
import functools
class Command:
class CommandType(enum.Enum):
CREATE = 1
SELECT = 2
INSERT = 3
def __init__(self, cmdType):
self.cmdType = cmdType
self.cmd = None
self.attributes = []
def addAttribute(self, atb):
self.attributes.append(atb)
def execute(self): raise Exception('Command not yet supported')
### end Command
class TableExistedException(Exception): pass
class CreateCommand(Command):
def __init__(self, tableName):
super(CreateCommand, self).__init__(Command.CommandType.CREATE)
self.baseRelationName = tableName
@pmdbpy.overrides(Command)
def execute(self, dbs):
try:
if (dbs.dataDict.isTableNameExisted(self.baseRelationName)):
raise TableExistedException("Table already existed: " + self.baseRelationName)
baseRelation = pmdbpy.BaseRelation.fromAttributes(self.attributes)
tupleList = []
for atb in baseRelation.attributes:
if atb.dtype == pmdbpy.DataType.String:
datatype = 'S'
elif atb.dtype == pmdbpy.DataType.Integer:
datatype = 'I'
else: raise Exception('Unknown data type')
tupleList.append((
self.baseRelationName,
atb.name,
datatype,
baseRelation.filename))
(masterRelation, masterFile) = dbs.dataDict.getMasterTuple()
for t in tupleList:
masterFile.writeTuple(t)
dbs.dataDict.addBaseRelation(baseRelation)
print ('------Table Created Successfully')
except TableExistedException as e:
print('Error executing sql: ', e)
except Exception as e:
print('Error executing sql: ', e)
if (dbs.dataDict.isTableNameExisted(self.baseRelationName)):
dbs.dataDict.removeBaseRelationByName(self.baseRelationName)
class InsertCommand(Command):
def __init__(self, tableName):
super(InsertCommand, self).__init__(Command.CommandType.INSERT)
self.baseRelationName = tableName
def setValueTuple(self, vt):
self.valueTuple = vt
@pmdbpy.overrides(Command)
def execute(self, dbs):
try:
(relation, dbFile) = dbs.dataDict.getTableTupleByName(self.baseRelationName)
dbFile.writeTuple(self.valueTuple)
print ('Row inserted into database')
except Exception as e:
print('Error executing sql: ', e)
class SelectCommand(Command):
def __init__(self):
super(SelectCommand, self).__init__(Command.CommandType.SELECT)
self.selectClause = SelectClause()
def execute(self, dbs):
self.selectClause.prepare(dbs)
lazyTuples = self.selectClause.lazyTuples(dbs)
count = 0
if (self.selectClause.selectList == '*'):
selected = self.selectClause.flatAtbNameList
else:
selected = self.selectClause.selectList
print("<" + "--".join(selected) + ">")
for row in lazyTuples:
l = [str(x) for x in row]
count += 1
print(" ".join(l))
print("===={} rows found".format(count))
class WhereClause:
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
def __str__(self):
return (self.lhs.nameValue + ' = ' + self.rhs.nameValue)
class SelectClause(pmdbpy.Relation):
def __init__(self):
super(SelectClause, self).__init__();
self.whereClause = None
self.selectList = []
self.flatAtbNameList = []
self.relationName = None
self.relation = pmdbpy.Relation()
def setWhereClause(self, whereClause):
self.whereClause = whereClause
def setSelectList(self, atbNameList):
self.selectList = atbNameList
def prepare(self, dbs):
for r in self.relation.relationList:
if isinstance(r, SelectClause):
r.prepare(dbs)
if (r.selectList[0] == '*'):
for atbName in r.flatAtbNameList:
self.flatAtbNameList.append(atbName)
else:
for atbName in r.selectList:
self.flatAtbNameList.append(atbName)
else:
for atb in r.attributes:
self.flatAtbNameList.append(atb.name)
@pmdbpy.overrides(pmdbpy.Relation)
def lazyTuples(self, dbs):
res = self.relation.lazyTuples(dbs)
if (self.selectList[0] == '*'):
res.positionFilter = None
self.selectList = self.flatAtbNameList
else:
res.positionFilter = list(map(lambda x: self.flatAtbNameList.index(x),
self.selectList))
if (self.whereClause is not None):
lhs = self.whereClause.lhs
rhs = self.whereClause.rhs
if (lhs.isColumn and rhs.isColumn):
pos = list(map(lambda x: self.flatAtbNameList.index(x),
[lhs.nameValue, rhs.nameValue]))
pos1 = [i for i, x in
enumerate(self.flatAtbNameList) if x == lhs.nameValue]
pos2 = [i for i, x in
enumerate(self.flatAtbNameList) if x == rhs.nameValue]
if len(set(pos1) | set(pos2)) != 2:
raise Exception('WHERE Clause: "' + str(self.whereClause) +
'" Ambiguity in column names')
res.condition = ([pos1[0], pos2[-1]], 1)
elif (lhs.isColumn and not rhs.isColumn):
pos = list(map(lambda x: self.flatAtbNameList.index(x),
[lhs.nameValue]))
res.condition = (pos, rhs.nameValue)
else:
raise Exception('WHERE Clause: "' + str(self.whereClause) +
'" is not supported. Please use: column = column OR column = const')
return res
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,053 | ngpham/petits | refs/heads/master | /pmdbpy/pmdbpy/dbsys.py | import pmdbpy
class DbSys:
def __init__(self):
self.dataDict = pmdbpy.DataDictionary(self)
self.parser = pmdbpy.Parser(self)
def executeSQL(self, sql):
sql.execute(self)
def shutdown(self):
pass
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,054 | ngpham/petits | refs/heads/master | /pmdbpy/pmdbpy/__init__.py | from .util import overrides
from .relation import (
Relation, BaseRelation, Attribute,
CrossProductTupleIterator, AttributeValue)
from .dbfile import DbFile
from .dbsys import DbSys
from .datadict import DataDictionary
from .datatype import (
ByteOrderSetting, DataTypeFormat, DataType, DataTypeSize, String2DataType)
from .parser import Parser
from .command import (
Command, CreateCommand, InsertCommand, SelectClause,
SelectCommand, WhereClause)
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,055 | ngpham/petits | refs/heads/master | /rrtl/rrtl/symbol.py | import enum
class SymbolType(enum.Enum):
Function = 1
FreeVar = 2
SkolemConst = 3
class Symbol:
@classmethod
def default_free_var(cls):
return cls('x', SymbolType.FreeVar)
def __init__(self, name, sym_type):
self.name = name
self.sym_type = sym_type
def __repr__(self):
return '{}({}, {})'.format(
self.__class__.__qualname__,
self.name,
repr(self.sym_type)
)
def __str__(self):
return self.name
def __eq__(self, o):
return (self.name == o.name and self.sym_type == o.sym_type)
def __hash__(self):
return hash(self.name) + hash(self.sym_type)
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,056 | ngpham/petits | refs/heads/master | /rrtl/rrtl/parser.py | """BCNF Grammar
<identifier> ::= <alphanumeric>
<op> ::= "+" | "-"
<fun> ::= <identifier> "(" <identifier> ")"
<atom> ::= <fun> <op> <number> "<=" <fun>
| <fun> "<=" <fun>
<clause> ::= <atom>
| <atom> "or" <clause>
<formula> ::= <clause> "\n"
| <clause> "\n" <formula>
"""
import pyparsing as pp
import rrtl
class _Parser:
def __init__(self, fun_hook, atom_hook, clause_hook):
pp.ParserElement.setDefaultWhitespaceChars(' \t')
kwOr = pp.CaselessKeyword('or')
leq = pp.Literal('<=')
oprt = pp.Literal('+') | pp.Literal('-')
lpar, rpar = map(pp.Suppress, '()')
number = pp.Word(pp.nums).setParseAction(lambda x: int(x[0]))
identifier = pp.Word(pp.alphas, pp.alphanums)
fun = (
identifier('funName') + lpar + identifier('varName') + rpar
).setParseAction(fun_hook)
atom = (
(fun('lfun') + oprt('sign') + number('number') + leq + fun('rfun')) |
(fun('lfun') + leq + fun('rfun'))
).setParseAction(atom_hook)
clause = (
pp.Suppress(pp.lineStart) + pp.delimitedList(atom, kwOr) + pp.Suppress(pp.lineEnd)
).setParseAction(clause_hook)
self.formula = pp.Group(pp.OneOrMore(clause)) + pp.Suppress(pp.lineEnd)
def parse(self, input):
return self.formula.parseString(input)
class Parser:
def __init__(self, graph, clauses_set):
def _fun_as_vertex(toks):
fname = toks['funName']
vname = toks['varName']
fsym = rrtl.Symbol(fname, rrtl.SymbolType.Function)
vsym = (
rrtl.Symbol(vname, rrtl.SymbolType.FreeVar) if vname == vname.lower() else
rrtl.Symbol(vname, rrtl.SymbolType.SkolemConst)
)
return rrtl.Vertex(fsym, vsym)
def _atom_as_edge(toks):
weight = 0
if toks.get('number') is not None:
if toks.sign == '+': weight = toks.number
else: weight = - toks.number
edge = rrtl.Edge(toks.lfun, toks.rfun, weight)
graph.add_edge(edge)
return edge
def _add_clause(toks):
clause = rrtl.Clause()
for lit in toks: clause.add_literal(lit)
clauses_set.add_clause(clause)
return toks
self.delegate = _Parser(_fun_as_vertex, _atom_as_edge, _add_clause)
def parseSpec2Graph(self, spec):
try:
par_res = self.delegate.parse(spec)
except Exception as e:
print('Error during parsing')
raise e
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,057 | ngpham/petits | refs/heads/master | /pmdbpy/main.py | import pmdbpy
import itertools
import cmd
samples = [
"Create employee (id INT, name STRING, division STRING)",
"Create salary (id INT, salary INT)",
"Create head (boss INT, division STRING)",
"INSERT INTO employee (1, 'Alicia', 'Direction')",
"INSERT INTO salary( 1, 100000)",
"INSERT INTO employee (2, 'Bob', 'Production')",
"INSERT INTO salary (2, 95000)",
"INSERT INTO head (2, 'Production')",
"Select * from employee",
"Select * from salary",
"Select * from head",
"SELECT name, salary FROM employee, salary WHERE id = id",
"Select * from employee, salary",
"Select * from Employee, (Select * from Head)",
"Select * from (SELECT * from HEAD), (Select * from Salary)",
"select id, name from employee",
"Select name, salary from (select id, name from employee), salary",
"Select name, salary from (select id, name from employee), salary where id = id",
"Select name, salary from (select id, name from employee), salary where id = name",
"Select * from (select name, salary from employee, salary where id = id)",
"select * from (select * from (select * from employee, salary where id = id))",
"select * from (select * from (select * from employee, salary where id = id), head)",
"select * from (select * from (select * from employee, salary where id = id), head where id = id)",
"select * from (select * from (select * from head))",
"Select * from (select name, salary from employee, salary where id = id) where salary = 95000",
"Select id, name from (Select * from employee, salary Where id = id), head where id = 31",
]
class PoorManSqlCmd(cmd.Cmd):
intro ='''
This is a poor man's sql implementation.
Support nested query and simple WHERE clause.
Database format: master, _table1, _table2, ...
There is no "Drop table", please manually delete if needed.
There is no Key, thus duplication insertion is not detected.
Type "execute_samples" to generate a sample database and execute some commands.
Type "exit" to quit.'''
prompt = '(pmdbpy) '
def __init__(self, dbs):
super(PoorManSqlCmd, self).__init__()
self.dbs = dbs
def default(self, line):
if line == 'exit': exit(0)
elif line == 'execute_samples':
for sample in samples:
try:
print("*** ", sample)
sql = self.dbs.parser.parseSql(sample)
self.dbs.executeSQL(sql)
except Exception as e: print(e)
else:
try:
sql = self.dbs.parser.parseSql(line)
self.dbs.executeSQL(sql)
except Exception as e: print(e)
def emptyline(self): pass
def main():
dbs = pmdbpy.DbSys()
pmdbpyShell = PoorManSqlCmd(dbs)
pmdbpyShell.cmdloop()
if __name__ == '__main__': main()
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,058 | ngpham/petits | refs/heads/master | /rrtl/rrtl/clause.py | from rrtl import *
class Clause:
def __init__(self): self.literals = []
def add_literal(self, literal):
if not isinstance(literal, Edge): raise RuntimeError()
self.literals.append(literal)
def __repr__(self):
s = [self.__class__.__qualname__ + '(']
for l in self.literals:
s.append(repr(l))
return ''.join(s, ',') + ')'
def __str__(self):
s = ''
for lit in self.literals:
s += str(lit)
return s
class ClausesSet:
def __init__(self):
self.clauses = []
self.literal_dict = {} # {literal:[clause]}
def add_clause(self, clause):
if not isinstance(clause, Clause): raise RuntimeError()
self.clauses.append(clause)
for literal in clause.literals:
assoc = self.literal_dict.get(literal)
if assoc is None: assoc = []
assoc.append(clause)
self.literal_dict[literal] = assoc
def is_unsatisfied_with(self, literals):
literals_set = set(literals)
Debug.trace('compare: ', *literals_set)
for c in self.clauses:
found_all = True
Debug.trace('with ', *c.literals)
for lit in c.literals:
if lit not in literals_set:
found_all = False
break
if found_all:
Debug.trace('found unsatisfied clause!')
return True
Debug.trace('end-compare')
return False
def __str__(self):
s = 'Begin ClauseSet\n'
s += ' ' + 'All clauses:\n'
for clause in self.clauses:
s += ' ' + str(clause) + '\n'
s += ' ' + 'Litearl and associative clauses:\n'
for lit, clauses in self.literal_dict.items():
s += ' ' + str(lit) + ': ' + str(len(clauses)) + ' clauses\n'
s += 'End ClauseSet'
return s
class Cycle(Clause):
def __init__(self, *edges):
super(Cycle, self).__init__()
self.weight = 0
self.positive = False
self.negate_positive = False
for edge in edges:
self.add_literal(edge)
self.weight += edge.weight
if self.weight > 0:
self.positive = True
if len(self.literals) - self.weight > 0:
self.negate_positive = True
def __str__(self):
s = ''
if self.positive: s += 'positive cycle '
if self.negate_positive: s += 'positive negated cycle '
s += super(Cycle, self).__str__()
return s
class Verifier:
def __init__(self, clauses_set, cycles):
self.clauses_set = clauses_set
self.positive_cycles = []
for c in cycles:
if c.positive:
self.positive_cycles.append(c)
if c.negate_positive:
self.clauses_set.add_clause(c)
def verify(self):
def rec(clauses_set, cycle_index, num_cycles, literals):
if cycle_index == num_cycles: return False
for literal in self.positive_cycles[cycle_index].literals:
literals.append(literal)
sub_unsatisfied = False
if clauses_set.is_unsatisfied_with(literals):
sub_unsatisfied = True
else:
sub_unsatisfied = rec(clauses_set, cycle_index + 1, num_cycles, literals)
del(literals[-1])
if sub_unsatisfied: return True
return False
num_cycles = len(self.positive_cycles)
return rec(self.clauses_set, 0, num_cycles, [])
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,059 | ngpham/petits | refs/heads/master | /pmdbpy/pmdbpy/datadict.py | import pmdbpy
class DataDictionary:
def __init__(self, dbs):
self.dbs = dbs
self.baseRelationMap = {}
self.initMasterRelation('master')
def initMasterRelation(self, masterName):
atbs = list([
pmdbpy.Attribute(masterName, 'table', pmdbpy.DataType.String),
pmdbpy.Attribute(masterName, 'attribute', pmdbpy.DataType.String),
pmdbpy.Attribute(masterName, 'datatype', pmdbpy.DataType.String),
pmdbpy.Attribute(masterName, 'dbfile', pmdbpy.DataType.String)])
relation = pmdbpy.BaseRelation.fromAttributes(atbs, masterName)
dbFile = pmdbpy.DbFile(relation)
self.baseRelationMap['master'] = (relation, dbFile)
dbFile.resetFilePointer()
t = dbFile.readNextTuple()
tableName = t[0] if t is not None else ''
temp = []
while t is not None:
atb = pmdbpy.Attribute(t[0], t[1], pmdbpy.String2DataType[t[2]])
if t[0] == tableName:
temp.append(atb)
else:
r = pmdbpy.BaseRelation.fromAttributes(temp)
f = pmdbpy.DbFile(r)
self.baseRelationMap[tableName] = (r, f)
tableName = t[0]
temp = []
temp.append(atb)
t = dbFile.readNextTuple()
if tableName != '':
r = pmdbpy.BaseRelation.fromAttributes(temp)
f = pmdbpy.DbFile(r)
self.baseRelationMap[tableName] = (r, f)
def isTableNameExisted(self, tableName):
return (self.baseRelationMap.get(tableName, None) is not None)
def getTableTupleByName(self, tableName):
if (self.isTableNameExisted(tableName)):
return self.baseRelationMap[tableName]
else:
raise Exception('Table ', tableName, 'does not exist.')
def getMasterTuple(self):
return self.getTableTupleByName('master')
def addBaseRelation(self, relation):
dbFile = pmdbpy.DbFile(relation)
self.baseRelationMap[list(relation.relationMap.keys())[0]] = (relation, dbFile)
def removeBaseRelationByName(self, relationName):
del self.baseRelationMap[relationName]
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,060 | ngpham/petits | refs/heads/master | /pmdbpy/pmdbpy/datatype.py | import pmdbpy
import enum
class DataType(enum.Enum):
Integer = 1
String = 2
String2DataType = {
'S': DataType.String,
'I': DataType.Integer,
'STRING': DataType.String,
'INT': DataType.Integer
}
DataTypeFormat = {
DataType.Integer: 'i',
DataType.String: '64p'
}
DataTypeSize = {
DataType.Integer: 4,
DataType.String: 64
}
ByteOrderSetting = '!'
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,061 | ngpham/petits | refs/heads/master | /rrtl/main.py | import sys
import argparse
import rrtl
def main():
argp = argparse.ArgumentParser()
argp.add_argument('--input', '-i', default='input.txt')
argp.add_argument('--debug', dest='debug', action='store_true')
argp.add_argument('--no-debug', dest='debug', action='store_false')
argp.set_defaults(debug=False)
args = argp.parse_args()
rrtl.Debug.debug_on = args.debug
graph = rrtl.Graph()
clauses_set = rrtl.ClausesSet()
parser = rrtl.Parser(graph, clauses_set)
with open(args.input, 'r') as input:
spec = input.read()
print(spec)
parser.parseSpec2Graph(spec)
cycles = graph.shrink()
print('Total cycles found: %d' % (len(cycles)))
for cycle in cycles: print(cycle)
print(clauses_set)
unsatisfiable = rrtl.Verifier(clauses_set, cycles).verify()
print('unsatisfiable: ', unsatisfiable)
if __name__ == '__main__': main()
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,062 | ngpham/petits | refs/heads/master | /pmdbpy/pmdbpy/parser.py | import pmdbpy
import pyparsing as pp
import pprint
""" The BNF Grammar
<select> ::= "SELECT" <select list> <table expression>
<select list> ::= "*" | <select sublist>
<select sublist> ::= <column-identifier> | <column-identifier> "," <select sublist>
<table expression> ::= <from clause> [<where clause>]
<from clause> ::= "FROM" <table reference list>
<table reference list> ::= <table reference> | <table reference> "," <table reference list>
<table reference> ::= <table primary> | <join table>
<table primary> ::= <table-identifier> | <sub query>
<sub query> ::= "(" <select> ")"
<where clause> ::= "WHERE" <comparison predicate>
<comparison predicate> ::= <row value predicand> <comparison predicate part2>
<comparison predicate part2> ::= "=" <row value predicand>
<row value predicand> ::= <identifier> | <number> | <string>
<string> ::= "'" [a-Z0-9]* "'"
<number> ::= [0..9]*
<value> ::= <number> | <string>
<value list> ::= <value> | <value>, <value list>
"""
kwSelect = pp.CaselessKeyword('SELECT')
kwFrom = pp.CaselessKeyword('FROM')
kwCreate = pp.CaselessKeyword('CREATE')
kwInt = pp.CaselessKeyword('INT')
kwString = pp.CaselessKeyword('STRING')
kwWhere = pp.CaselessKeyword('WHERE')
kwInsert = pp.CaselessKeyword('INSERT')
kwInto = pp.CaselessKeyword('INTO')
comma = pp.Literal(',')
eqcomp = pp.Literal('=')
star = pp.Literal('*')
leftp, rightp = map(pp.Suppress, "()")
def toInteger(toks):
return int(toks[0])
identifier = pp.Word(pp.alphas, pp.alphanums).setParseAction(pp.downcaseTokens)
number = pp.Word(pp.nums).setParseAction(toInteger)
sqString = pp.sglQuotedString.setParseAction(pp.removeQuotes)
selectList = pp.Group(pp.delimitedList(identifier) | star)
value = number('number') | sqString('string')
valueList = pp.delimitedList(value)
column = pp.Group(identifier('name') + (kwInt | kwString)('dtype'))
columnList = pp.delimitedList(column)
def nameGenerator(x):
while True:
yield ('_tmpTable_' + str(x))
x += 1
relationNameGen = nameGenerator(0)
class DbsRef:
dbs = None
def genSelectCommand(toks):
rel = pmdbpy.SelectCommand()
rel.selectClause.relationName = next(relationNameGen)
rel.selectClause.relation = toks.tableReferenceList
rel.selectClause.setSelectList(toks.selectList)
if (toks.where != ''):
rel.selectClause.setWhereClause(pmdbpy.WhereClause(
toks.where.comparison.lhs,
toks.where.comparison.rhs))
return rel
def genSelectClause(toks):
rel = pmdbpy.SelectClause()
rel.relationName = next(relationNameGen)
rel.setSelectList(toks.sqlSelect.selectList)
rel.relation = toks.sqlSelect.tableReferenceList
if (toks.where != ''):
rel.setWhereClause(pmdbpy.WhereClause(
toks.sqlSelect.where.comparison.lhs,
toks.sqlSelect.where.comparison.rhs))
return rel
def genTable(toks):
return (DbsRef.dbs.dataDict.getTableTupleByName(toks.table)[0])
def genTableList(toks):
rel = pmdbpy.Relation()
for r in toks:
rel.addRelation(r)
return rel
def genValue(toks):
value = pmdbpy.AttributeValue()
if (toks.number != ''):
value.dtype = pmdbpy.DataType.Integer
value.nameValue = toks.number
value.isColumn = False
elif (toks.string != ''):
value.dtype = pmdbpy.DataType.String
value.nameValue = toks.string
value.isColumn = False
elif (toks.column != ''):
value.nameValue = toks.column
value.isColumn = True
return value
subquery = pp.Forward().setParseAction(genSelectClause)
colValue = (number('number') | sqString('string') | identifier('column'))
comparison = pp.Group(colValue('lhs').setParseAction(genValue)
+ '='
+ colValue('rhs').setParseAction(genValue))
where = (kwWhere + comparison('comparison'))
tableReference = identifier('table').addParseAction(genTable) | subquery('subquery')
tableReferenceList = pp.delimitedList(tableReference)
sqlSelect = (kwSelect +
selectList('selectList') + kwFrom +
tableReferenceList('tableReferenceList').setParseAction(genTableList) +
pp.Optional(where('where'))
)
subquery << leftp + sqlSelect('sqlSelect') + rightp
sqlCreate = (kwCreate +
identifier('table') + '(' + columnList('columnList') + ')'
)
sqlInsert = (kwInsert + kwInto + identifier('table') +
leftp + valueList('valueList') + rightp)
command = (pp.stringStart +
(sqlSelect('sqlSelect').setParseAction(genSelectCommand)
| sqlCreate('sqlCreate')
| sqlInsert('sqlInsert'))
+ pp.stringEnd)
class Parser:
def __init__(self, dbs):
self.command = command
self.dbs = dbs
DbsRef.dbs = dbs
def parseSql(self, sqlCmd):
try:
parseRes = self.command.parseString(sqlCmd)
except pp.ParseException as e:
raise Exception('Syntax error: ' + '"' + e.pstr[:(e.loc+1)] + '": '+e.msg)
if parseRes.sqlCreate != '':
sql = pmdbpy.CreateCommand(parseRes.table)
for col in parseRes.columnList:
sql.addAttribute(
pmdbpy.Attribute(parseRes.table, col[0], pmdbpy.String2DataType[col[1]]))
elif parseRes.sqlInsert != '':
sql = pmdbpy.InsertCommand(parseRes.table)
if not self.dbs.dataDict.isTableNameExisted(parseRes.table):
raise Exception("Table does not exist: " + parseRes.table)
(table, dbfile) = self.dbs.dataDict.getTableTupleByName(parseRes.table)
if len(table.attributes) != len(parseRes.valueList):
raise Exception('Mismatch number of attributes')
valueTuple = ()
for (atb, value) in zip(table.attributes, parseRes.valueList):
if atb.dtype == pmdbpy.DataType.Integer:
try:
v = int(value)
except Exception as e:
raise Exception('Cannot convert to INT as required by: ' + atb.name)
elif atb.dtype == pmdbpy.DataType.String:
v = value
valueTuple += (v,)
sql.setValueTuple(valueTuple)
elif parseRes.sqlSelect != '':
sql = parseRes.sqlSelect
# sql.gen(self.dbs)
# sql = sql.selectCommand
else:
raise Exception('Unknow query/command')
return sql
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,063 | ngpham/petits | refs/heads/master | /pmdbpy/pmdbpy/dbfile.py | import pmdbpy
import struct
class DbFile:
def __init__(self, relation):
if not isinstance(relation, pmdbpy.BaseRelation):
raise Exception('BaseRelation expected')
self.filename = relation.filename
self.fmt = pmdbpy.ByteOrderSetting
self.recordSize = 0
for atb in relation.attributes:
self.fmt += pmdbpy.DataTypeFormat[atb.dtype]
self.recordSize += pmdbpy.DataTypeSize[atb.dtype]
try:
self.dbf = open(self.filename, 'r+b')
except FileNotFoundError:
self.dbf = open(self.filename, 'w+b')
def __enter__(self):
try:
self.dbf = open(self.filename, 'r+b')
except FileNotFoundError:
self.dbf = open(self.filename, 'w+b')
return self
def __exit__(self, *argv):
self.dbf.flush()
self.dbf.close()
def writeTuple(self, values):
rawTuple = DbFile.tuple2raw(values)
binary = struct.pack(self.fmt, *rawTuple)
self.dbf.seek(0, 2)
self.dbf.write(binary)
self.dbf.flush()
def resetFilePointer(self):
self.dbf.seek(0)
def readNextTuple(self):
binary = self.dbf.read(self.recordSize)
if len(binary) == 0: return None
raw = struct.unpack(self.fmt, binary)
return DbFile.raw2tuple(raw)
@classmethod
def tuple2raw(self, values):
def toRaw(x):
if isinstance(x, int):
return x
elif isinstance(x, str):
return bytes(x, 'ascii')
return tuple(map(toRaw, values))
@classmethod
def raw2tuple(self, byteStrList):
def toValue(x):
if isinstance(x, bytes):
return str(x, 'ascii')
elif isinstance(x, int):
return x
else:
raise Exception('Unsupported type encountered')
return tuple(map(toValue, byteStrList))
### end DbFile
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,064 | ngpham/petits | refs/heads/master | /rrtl/rrtl/debug.py |
class Debug:
debug_on = True
@classmethod
def trace(self, *args):
if Debug.debug_on:
s = 'Debug: '
for a in args: s += str(a) + ' '
print(s)
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,065 | ngpham/petits | refs/heads/master | /pmdbpy/pmdbpy/relation.py | import pmdbpy
import copy
import itertools
import functools
class Attribute:
def __init__(self, relationName, name, dtype):
self.name = name
self.dtype = dtype
self.relationName = relationName
def __hash__(self):
return hash((self.name, self.dtype, self.relationName))
def __eq__(self, other):
if type(self) is type(other):
return (
self.name == other.dtype and
self.dtype == other.dtype and
self.relationName == other.relationName
)
else: return False
### end Attribute
class TupleIterator:
def __init__(self, dbfile):
self.dbfile = dbfile
self.positionFilter = None
self.condition = None
def __iter__(self):
self.dbfile.resetFilePointer()
return self
def __next__(self):
accepted = True
while True:
n = self.dbfile.readNextTuple()
if n is None:
raise StopIteration
else:
l = list(n)
if self.condition is not None:
indexes = self.condition[0]
const = self.condition[1]
if len(indexes) == 2:
if type(l[indexes[0]]) != type(l[indexes[1]]):
raise Exception('Type mistmached in WHERE condition')
else:
accepted = (l[indexes[0]] == l[indexes[1]])
if len(indexes) == 1:
if type(l[indexes[0]]) != type(const):
raise Exception('Type mistmached in WHERE condition')
else:
accepted = (l[indexes[0]] == const)
if accepted: break
if self.positionFilter is None:
return tuple(l)
else:
return tuple(l[i] for i in self.positionFilter)
class WrappedTupleIterator:
def __init__(self, iterator):
self.iter = iterator
self.positionFilter = None
self.condition = None
def __iter__(self):
self.iter.__iter__()
return self
def __next__(self):
accepted = True
while True:
n = next(self.iter)
if n is None:
raise StopIteration
else:
l = list(n)
if self.condition is not None:
indexes = self.condition[0]
const = self.condition[1]
if len(indexes) == 2:
if type(l[indexes[0]]) != type(l[indexes[1]]):
raise Exception('Type mistmached in WHERE condition')
else:
accepted = (l[indexes[0]] == l[indexes[1]])
if len(indexes) == 1:
if type(l[indexes[0]]) != type(const):
raise Exception('Type mistmached in WHERE condition')
else:
accepted = (l[indexes[0]] == const)
if accepted: break
if self.positionFilter is None:
return tuple(l)
else:
return tuple(l[i] for i in self.positionFilter)
class CrossProductTupleIterator:
def __init__(self, tupleIter1, tupleIter2):
self.tupleIter1 = tupleIter1
self.tupleIter2 = tupleIter2
self.crossprod = itertools.product(tupleIter1, tupleIter2)
# a list of positions to return [1, 2, 3]
self.positionFilter = None
# a tuple of condition ([pos1, pos2], 1) or ([post1], const)
# TODO: redesign
self.condition = None
def __iter__(self):
self.crossprod = itertools.product(self.tupleIter1, self.tupleIter2)
return self
def __next__(self):
accepted = True
try:
while True:
n = next(self.crossprod)
l = [elem for t in n for elem in t]
if self.condition is not None:
indexes = self.condition[0]
const = self.condition[1]
if len(indexes) == 2:
if type(l[indexes[0]]) != type(l[indexes[1]]):
raise Exception('Type mistmached in WHERE condition')
else:
accepted = (l[indexes[0]] == l[indexes[1]])
if len(indexes) == 1:
if type(l[indexes[0]]) != type(const):
raise Exception('Type mistmached in WHERE condition')
else:
accepted = (l[indexes[0]] == const)
if accepted: break
except StopIteration:
raise StopIteration
if self.positionFilter is None:
return tuple(l)
else:
return tuple(l[i] for i in self.positionFilter)
class Relation:
@classmethod
def fromAttributes(cls, atbs):
obj = cls()
for atb in atbs:
obj.addAttribute(atb)
return obj
def __init__(self):
# [attributes]
self.attributes = []
# {relationName: {attributeName:attribute}}
self.relationMap = {}
# {attributeName: [attributes]}
# i.e. same attribute name from multiple relations
self.attributeMap = {}
# list of sub-relation
self.relationList = []
def __iter__(self):
return iter(self.attributes)
def isBase(self): return False
def __copy__(self):
obj = self.__class__()
obj.attributes = self.attributes
obj.relationMap = self.relationMap
obj.attributeMap = self.attributeMap
return obj
def addRelation(self, relation):
if not isinstance(relation, Relation):
raise Exception('Type Error')
self.relationList.append(relation)
for atb in relation.attributes:
self.addAttribute(atb)
def addAttribute(self, atb):
relationName = atb.relationName
attributeName = atb.name
atbMap = None
if relationName in self.relationMap:
atbMap = self.relationMap.get(relationName)
if attributeName in atbMap:
raise Exception('Attribute name duplicated: ', attributeName)
self.attributes.append(atb)
if atbMap is None:
atbMap = {}
self.relationMap[relationName] = atbMap
atbMap[attributeName] = atb
atbList = self.attributeMap.get(attributeName, None)
if atbList is None:
atbList = []
self.attributeMap[attributeName] = atbList
atbList.append(atb)
def lazyTuples(self, dbs):
if (len(self.relationList) == 1):
return WrappedTupleIterator(self.relationList[0].lazyTuples(dbs))
res = functools.reduce(
lambda x, y: CrossProductTupleIterator(x, y),
map(lambda x: x.lazyTuples(dbs), self.relationList))
return res
### end Relation
class BaseRelation(Relation):
@classmethod
def fromAttributes(cls, atbs, filename=''):
obj = super(BaseRelation, cls).fromAttributes(atbs)
if filename == '':
filename = '_' + atbs[0].relationName
obj.filename = filename
return obj
def __init__(self):
super(BaseRelation, self).__init__()
@pmdbpy.overrides(Relation)
def lazyTuples(self, dbs):
(r ,dbf) = dbs.dataDict.getTableTupleByName(self.attributes[0].relationName)
return TupleIterator(dbf)
@pmdbpy.overrides(Relation)
def isBase(self): return true
### end BaseRelation
class AttributeValue:
def __init__(self):
self.dtype = None
self.nameValue = None
self.isColumn = False
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,066 | ngpham/petits | refs/heads/master | /rrtl/rrtl/transform.py | from rrtl import *
# unify functions: alpha-rewrite of free variable, or overwrite with Skolem constant.
class Unifier:
def __init__(self, sym1, sym2):
if not isinstance(sym1, Symbol) or not isinstance(sym2, Symbol): raise RuntimeError()
symbol = None
if sym1.sym_type == SymbolType.SkolemConst:
if sym2.sym_type == SymbolType.FreeVar:
symbol = sym1
else: pass
elif sym1.sym_type == SymbolType.FreeVar:
if (sym2.sym_type == SymbolType.SkolemConst or
sym2.sym_type == SymbolType.FreeVar):
symbol = sym2
self.sym = symbol
def substitute(self, vertex):
if self.sym is None: return None
if vertex.var_sym.sym_type == SymbolType.FreeVar:
return Vertex(vertex.fun_sym, self.sym)
else: return vertex
def __str__(self):
return str(self.sym)
# construct a new edge (literal) by unifying 2 edges.
# add new attribute for Edge to store the 2 constitutional edges.
def _combine_2_edges(cls, edge1, edge2):
if not isinstance(edge1, Edge) or not isinstance(edge2, Edge): raise RuntimeError()
if edge1.dst != edge2.src: raise RuntimeError()
combined = cls(edge1.src, edge2.dst, edge1.weight + edge2.weight)
combined.hyper_tuple = (edge1, edge2)
return combined
setattr(Edge, 'combine_2_edges', classmethod(_combine_2_edges))
setattr(Edge, 'hyper_tuple', None)
def _combine_2_edges_with_unifier(cls, edge1, edge2, uni):
if not isinstance(edge1, Edge) or not isinstance(edge2, Edge): raise RuntimeError()
combined = None
src = uni.substitute(edge1.src)
dst = uni.substitute(edge2.dst)
if src is not None and dst is not None:
combined = cls(src, dst, edge1.weight + edge2.weight)
combined.hyper_tuple = (edge1, edge2)
return combined
setattr(Edge, 'combine_2_edges_with_unifier', classmethod(_combine_2_edges_with_unifier))
def _trace_path(edge):
path = []
if edge.hyper_tuple is not None:
path = path + edge.hyper_tuple[0].trace_path()
path = path + edge.hyper_tuple[1].trace_path()
else:
path.append(edge)
return path
setattr(Edge, 'trace_path', _trace_path)
# An self edge is a cycle in the original graph, however, we need to
# reject "twisted" cycle i.e. 8-form
def _validate_get_cycle(self_edge):
cycle = self_edge.trace_path()
vertexes = []
valid = True
for arc in cycle:
is_in_same_cluster = False
for node in vertexes:
if node.fun_sym == arc.src.fun_sym:
is_in_same_cluster = True
break;
if is_in_same_cluster:
valid = False
break
vertexes.append(arc.src)
if valid: return cycle
else: return None
setattr(Edge, 'validate_get_cycle', _validate_get_cycle)
# consider a vertex, add new edges by combining 1 incomming egde with 1 outgoing.
# also consider the equivalent veretexes (by unification) in the same cluster.
# return any self arcs
def _cycle_invariant_add_with_unification(graph, vertex, cluster):
if (not isinstance(vertex, Vertex) or
not isinstance(cluster, VertexCluster)): raise RuntimeError()
incomming_arcs = []
outgoing_arcs = []
self_arcs = []
for arc in graph.edges:
if arc.dst == vertex or arc.src == vertex:
if arc.is_self_edge():
self_arcs.append(arc)
elif arc.dst == vertex:
incomming_arcs.append(arc)
else:
outgoing_arcs.append(arc)
for node in cluster.vertexes:
Debug.trace('in-cluster vertex: ', vertex)
if node == vertex:
for left in incomming_arcs:
for right in outgoing_arcs:
new_arc = Edge.combine_2_edges(left, right)
Debug.trace('new arc added for', vertex, ':', new_arc, 'by:', left, right)
if new_arc is not None: graph.add_edge(new_arc)
else:
Debug.trace('process pair: ', vertex, node)
uni = Unifier(vertex.var_sym, node.var_sym)
extra_incomming_arcs = []
extra_outgoing_arcs = []
if uni.sym is not None:
for arc in graph.edges:
if arc.dst == node or arc.src == node:
if arc.is_self_edge(): pass # will be considered when we call this function on "node"
elif arc.dst == node:
extra_incomming_arcs.append(arc)
else:
extra_outgoing_arcs.append(arc)
for left in extra_incomming_arcs:
for right in outgoing_arcs:
new_arc = Edge.combine_2_edges_with_unifier(left, right, uni)
Debug.trace('new edge added', vertex, node, uni, ':', new_arc)
if new_arc is not None: graph.add_edge(new_arc)
for left in incomming_arcs:
for right in extra_outgoing_arcs:
new_arc = Edge.combine_2_edges_with_unifier(left, right, uni)
Debug.trace('new edge added', vertex, node, uni, ':', new_arc)
if new_arc is not None: graph.add_edge(new_arc)
# (left in extra_incomming_arcs, right in extra_outgoing_arcs)
# will be consider when we call this function on "node"
return self_arcs
setattr(
Graph,
'cycle_invariant_add_with_unification',
_cycle_invariant_add_with_unification)
# keep removing vertices and discover cycles during the process
def _shrink(graph):
cycles = []
for fun_sym in sorted(graph.fun_sym_cluster.keys(), key = lambda x: x.name):
cluster = graph.fun_sym_cluster[fun_sym]
num_shrinked_vertexes = len(cluster.vertexes)
while (num_shrinked_vertexes > 0 and len(cluster.vertexes) > 0):
prev = len(cluster.vertexes)
vertex = cluster.vertexes[-1]
Debug.trace('ready to process', vertex)
self_arcs = (
graph.cycle_invariant_add_with_unification(vertex, cluster))
for arc in self_arcs:
circuit = arc.validate_get_cycle()
if circuit is not None:
cycle = Cycle(*circuit)
cycles.append(cycle)
Debug.trace('cycle found:', cycle)
graph.remove_edges_incident(vertex)
Debug.trace('to remove ', vertex)
graph.remove_if_isolated(vertex)
num_shrinked_vertexes = prev - len(cluster.vertexes)
return cycles
setattr(Graph, 'shrink', _shrink)
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,067 | ngpham/petits | refs/heads/master | /rrtl/rrtl/edge.py | from rrtl import *
class Edge:
def __init__(self, src, dst, weight):
if not isinstance(src, Vertex) or not isinstance(dst, Vertex): raise RuntimeError()
self.src = src
self.dst = dst
self.weight = weight
def contains(self, vertex):
return self.src == vertex or self.dst == vertex
def __eq__(self, o):
return (self.src == o.src and
self.dst == o.dst and
self.weight == o.weight)
def is_self_edge(self):
return self.src == self.dst
def __hash__(self):
return hash(self.src) + hash(self.dst) + self.weight
def __repr__(self):
return '{}({}, {}, {})'.format(
self.__class__.__qualname__,
repr(self.src),
repr(self.dst),
self.weight
)
def __str__(self):
s = '['
s += str(self.src) + "->" + str(self.dst) + ":" + str(self.weight) + ']'
return s
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,068 | ngpham/petits | refs/heads/master | /rrtl/rrtl/vertex.py | from rrtl import *
class Vertex:
def __init__(self, fun_sym, var_sym):
if (not isinstance(fun_sym, Symbol) or
not isinstance(var_sym, Symbol)): raise RuntimeError()
self.fun_sym = fun_sym
self.var_sym = var_sym
def __repr__(self):
return '{}({}, {})'.format(
self.__class__.__qualname__,
repr(self.fun_sym),
repr(self.var_sym)
)
def __str__(self):
s = 'Vertex:' + str(self.fun_sym) + '(' + str(self.var_sym) + ')'
return s
def __eq__(self, other):
return (self.fun_sym == other.fun_sym and self.var_sym == other.var_sym)
def __hash__(self):
return hash(self.fun_sym) + hash(self.var_sym)
class VertexCluster:
def __init__(self, fun_sym):
if not isinstance(fun_sym, Symbol): raise RuntimeError()
self.fun_sym = fun_sym
self.vertexes = []
def add_vertex(self, vertex):
if not isinstance(vertex, Vertex): raise RuntimeError()
if vertex not in self.vertexes:
self.vertexes.append(vertex)
def remove_vertex(self, vertex):
if not isinstance(vertex, Vertex): raise RuntimeError()
self.vertexes.remove(vertex)
def get_vertex(self, tup_sym):
if type(tup_sym) is not tuple: raise RuntimeError()
if self.fun_sym != tup_sym[0]: raise RuntimeError()
return next((v for v in self.vertexes if v.var_sym == tup_sym[1]), None)
def __repr__(self):
return '{}({})'.format(
self.__class__.__qualname__,
repr(self.fun_sym)
)
def __str__(self):
return 'Cluster:' + str(self.fun_sym)
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,069 | ngpham/petits | refs/heads/master | /rrtl/rrtl/graph.py |
from rrtl import *
class Graph:
def __init__(self):
self.fun_sym_cluster = {} # {vertex.fun_sym : cluster}
self.edges = []
def _add_vertex(self, v):
if not isinstance(v, Vertex): raise RuntimeError()
(self.fun_sym_cluster
.setdefault(v.fun_sym, VertexCluster(v.fun_sym))
.add_vertex(v))
def add_edge(self, e):
if not isinstance(e, Edge): raise RuntimeError()
if not e in self.edges:
self._add_vertex(e.src)
self._add_vertex(e.dst)
# e.src.add_dst(e.dst, e.weight)
self.edges.append(e)
def remove_edge_keeping_vertexes(self, edge):
if not isinstance(edge, Edge): raise RuntimeError()
self.edges.remove(edge)
def remove_if_isolated(self, vertex):
if not isinstance(vertex, Vertex): raise RuntimeError()
for edge in self.edges:
if edge.contains(vertex): return False
self.fun_sym_cluster.get(vertex.fun_sym).remove_vertex(vertex)
return True
def remove_edges_incident(self, vertex):
if not isinstance(vertex, Vertex): raise RuntimeError()
self.edges = [e for e in self.edges if e.src != vertex and e.dst != vertex]
def __repr__(self):
s1 = [self.__class__.__qualname__ + '(\n']
for fun_sym, cluster in self.fun_sym_cluster.items():
s2 = [repr(cluster) + '\n']
for v in cluster.vertexes:
s2.append(' ' + repr(v) + '\n')
s1.append("".join(s2))
return "".join(s1) + ')'
def __str__(self):
s = ''
for _, cluster in self.fun_sym_cluster.items():
s += str(cluster) + '\n'
for v in cluster.vertexes:
s += ' ' + str(v)
s += '\n'
return s
| {"/rrtl/rrtl/__init__.py": ["/rrtl/rrtl/parser.py", "/rrtl/rrtl/symbol.py", "/rrtl/rrtl/vertex.py", "/rrtl/rrtl/edge.py", "/rrtl/rrtl/graph.py", "/rrtl/rrtl/debug.py", "/rrtl/rrtl/clause.py"], "/pmdbpy/pmdbpy/__init__.py": ["/pmdbpy/pmdbpy/util.py", "/pmdbpy/pmdbpy/relation.py", "/pmdbpy/pmdbpy/dbfile.py", "/pmdbpy/pmdbpy/dbsys.py", "/pmdbpy/pmdbpy/datadict.py", "/pmdbpy/pmdbpy/datatype.py", "/pmdbpy/pmdbpy/parser.py", "/pmdbpy/pmdbpy/command.py"]} |
54,070 | ucldc/harvester | refs/heads/master | /scripts/populate_harvested_images_redis.py | '''one time script to populate redis with harvested image object data'''
from harvester.config import config
from harvester.couchdb_init import get_couchdb
from harvester.couchdb_pager import couchdb_pager
from redis import Redis
import redis_collections
_config = config()
_redis = Redis(host=_config['redis_host'],
port=_config['redis_port'],
password=_config['redis_password'],
socket_connect_timeout=_config['redis_connect_timeout'])
object_cache = redis_collections.Dict(key='ucldc:harvester:harvested-images',
redis=_redis)
_couchdb = get_couchdb(url=_config['couchdb_url'], dbname='ucldc')
v = couchdb_pager(_couchdb, include_docs='true')
for r in v:
doc = r.doc
if 'object' in doc:
did = doc['_id']
if 'object_dimensions' not in doc:
print "NO DIMS for {} -- not caching".format(did)
else:
object_cache[did] = [doc['object'], doc['object_dimensions']]
print "OBJECT CACHE : {} === {}".format(did, object_cache[did])
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,071 | ucldc/harvester | refs/heads/master | /scripts/queue_image_harvest_on_doc_id_list.py | #! /bin/env python
import sys
import os
from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
from harvester.image_harvest import harvest_image_for_doc
EMAIL_RETURN_ADDRESS = os.environ.get('EMAIL_RETURN_ADDRESS',
'example@example.com')
# csv delim email addresses
EMAIL_SYS_ADMIN = os.environ.get('EMAIL_SYS_ADMINS', None)
IMAGE_HARVEST_TIMEOUT = 144000
def def_args():
import argparse
parser = argparse.ArgumentParser(description='Harvest a collection')
parser.add_argument('user_email', type=str, help='user email')
parser.add_argument('rq_queue', type=str, help='RQ Queue to put job in')
parser.add_argument('doc_id_list_file', type=str,
help='File containing couchdb doc ids to process')
parser.add_argument('--object_auth', nargs='?',
help='HTTP Auth needed to download images - username:password')
parser.add_argument('--url_couchdb', nargs='?',
help='Override url to couchdb')
parser.add_argument('--timeout', nargs='?',
help='set image harvest timeout in sec (14400 - 4hrs default)')
parser.add_argument('--get_if_object', action='store_true',
default=False,
help='Should image harvester not get image if the object field exists for the doc (default: False, always get)')
return parser
def main(user_email, doc_id_list_file, rq_queue=None, url_couchdb=None):
enq = CouchDBJobEnqueue(rq_queue=rq_queue)
timeout = 10000000
with open(doc_id_list_file) as foo:
doc_id_list = [ l.strip() for l in foo.readlines()]
results = enq.queue_list_of_ids(doc_id_list,
timeout,
harvest_image_for_doc,
url_couchdb=url_couchdb,
)
print "Results:{}".format(results)
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args(sys.argv[1:])
if not args.user_email or not args.doc_id_list_file:
parser.print_help()
sys.exit(27)
kwargs = {}
if args.object_auth:
kwargs['object_auth'] = args.object_auth
if args.timeout:
kwargs['harvest_timeout'] = int(args.timeout)
if args.get_if_object:
kwargs['get_if_object'] = args.get_if_object
main(args.user_email,
args.doc_id_list_file,
rq_queue = args.rq_queue,
**kwargs)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,072 | ucldc/harvester | refs/heads/master | /scripts/grab_missing_object_vals_from_solr.py | import sys
py_version = sys.version_info
if py_version.major == 2 and py_version.minor == 7 and py_version.micro > 8:
#disable ssl verification
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
import os
from harvester.post_processing.run_transform_on_couchdb_docs import run_on_couchdb_by_collection
import solr
SOLR_URL = os.environ.get('URL_SOLR_API', None)
SOLR_API_KEY = os.environ.get('SOLR_API_KEY', None)
SOLR = solr.SearchHandler(
solr.Solr(
SOLR_URL,
post_headers={
'X-Authentication-Token': SOLR_API_KEY,
},
),
"/query"
)
def fill_object_values_from_solr(doc):
'''If no object field, try to get from current solr
'''
if 'object' not in doc:
query='harvest_id_s:"{}"'.format(doc['_id'])
msg = "NO OBJECT FOR {}".format(doc['_id'])
resp = SOLR(q=query,
fields='harvest_id_s, reference_image_md5, id, collection_url, reference_image_dimensions',
)
results = resp.results
if results:
solr_doc = results[0]
if 'reference_image_md5' in solr_doc:
doc['object'] = solr_doc['reference_image_md5']
doc['object_dimensions'] = solr_doc['reference_image_dimensions'].split(':')
print "OBJ DIM:{}".format(doc['object_dimensions'])
print 'UPDATING OBJECT -- {}'.format(doc['_id'])
return doc
else:
print 'NOT IN SOLR -- {}'.format(msg)
return None
run_on_couchdb_by_collection(fill_object_values_from_solr,
#collection_key="23066")
collection_key="26094")
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,073 | ucldc/harvester | refs/heads/master | /harvester/config.py | '''Configuration for the harvester and associated code.
UCLDC specfic information comes from environment variables and the
values are filled in directly in returned namedtuple.
DPLA values are contained in a ConfigParser object that is returned in the
namedtuple.
'''
import os
from collections import namedtuple
import ConfigParser
REDIS_HOST = '127.0.0.1'
REDIS_PORT = '6380'
DPLA_CONFIG_FILE = 'akara.ini'
RQ_Q_LIST = (
'high-production',
'normal-production',
'low-production',
'high-stage',
'normal-stage',
'low-stage',
)
def config(config_file=None, redis_required=False):
'''Return the HarvestConfig namedtuple for the harvester'''
if not config_file:
config_file = os.environ.get('DPLA_CONFIG_FILE', DPLA_CONFIG_FILE)
DPLA = None
if os.path.isfile(config_file):
DPLA = ConfigParser.ConfigParser()
DPLA.readfp(open(config_file))
env = parse_env(DPLA, redis_required=redis_required)
env['DPLA'] = DPLA
return env
def parse_env(DPLA, redis_required=False):
'''Get any overrides from the runtime environment for the server variables
If redis_required, raise KeyError if REDIS_PASSWORD not found
'''
env = {}
env['redis_host'] = os.environ.get('REDIS_HOST', REDIS_HOST)
env['redis_port'] = os.environ.get('REDIS_PORT', REDIS_PORT)
env['redis_connect_timeout'] = os.environ.get('REDIS_CONNECT_TIMEOUT', 10)
env['redis_password'] = None
try:
env['redis_password'] = os.environ['REDIS_PASSWORD']
except KeyError as e:
if redis_required:
raise KeyError(''.join(('Please set environment variable ',
'REDIS_PASSWORD to redis password!')))
env['rq_queue'] = os.environ.get('RQ_QUEUE')
env['couchdb_url'] = os.environ.get('COUCHDB_URL')
env['couchdb_username'] = os.environ.get('COUCHDB_USER')
env['couchdb_password'] = os.environ.get('COUCHDB_PASSWORD')
env['couchdb_dbname'] = os.environ.get('COUCHDB_DB')
env['couchdb_dashboard'] = os.environ.get('COUCHDB_DASHBOARD')
env['akara_port'] = '8889'
if DPLA:
if not env['couchdb_url']:
env['couchdb_url'] = DPLA.get("CouchDb", "URL")
if not env['couchdb_username']:
env['couchdb_username'] = DPLA.get("CouchDb", "Username")
if not env['couchdb_password']:
env['couchdb_password'] = DPLA.get("CouchDb", "Password")
if not env['couchdb_dbname']:
env['couchdb_dbname'] = DPLA.get("CouchDb", "ItemDatabase")
if not env['couchdb_dashboard']:
env['couchdb_dashboard'] = DPLA.get("CouchDb", "DashboardDatabase")
env['akara_port'] = DPLA.get("Akara", "Port")
if not env['couchdb_url']:
env['couchdb_url'] = 'http://127.0.0.1:5984'
if not env['couchdb_dbname']:
env['couchdb_dbname'] = 'ucldc'
if not env['couchdb_dashboard']:
env['couchdb_dashboard'] = 'dashboard'
return env
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,074 | ucldc/harvester | refs/heads/master | /test/test_oai_fetcher.py | # -*- coding: utf-8 -*-
import shutil
from unittest import TestCase
from test.utils import ConfigFileOverrideMixin, LogOverrideMixin
from test.utils import DIR_FIXTURES
from harvester.collection_registry_client import Collection
import harvester.fetcher as fetcher
from mypretty import httpretty
import pprint
# import httpretty
class HarvestOAIControllerTestCase(ConfigFileOverrideMixin,
LogOverrideMixin, TestCase):
'''Test the function of an OAI fetcher'''
def setUp(self):
super(HarvestOAIControllerTestCase, self).setUp()
def tearDown(self):
super(HarvestOAIControllerTestCase, self).tearDown()
shutil.rmtree(self.controller.dir_save)
@httpretty.activate
def testOAIHarvest(self):
'''Test the function of the OAI harvest'''
httpretty.register_uri(
httpretty.GET,
'http://registry.cdlib.org/api/v1/collection/',
body=open(DIR_FIXTURES+'/collection_api_test.json').read())
httpretty.register_uri(
httpretty.GET,
'http://content.cdlib.org/oai',
body=open(DIR_FIXTURES+'/testOAC-url_next-0.xml').read())
self.collection = Collection(
'http://registry.cdlib.org/api/v1/collection/')
self.setUp_config(self.collection)
self.controller = fetcher.HarvestController(
'email@example.com', self.collection,
config_file=self.config_file, profile_path=self.profile_path)
self.assertTrue(hasattr(self.controller, 'harvest'))
# TODO: fix why logbook.TestHandler not working for previous logging
# self.assertEqual(len(self.test_log_handler.records), 2)
self.tearDown_config()
class OAIFetcherTestCase(LogOverrideMixin, TestCase):
'''Test the OAIFetcher
'''
@httpretty.activate
def setUp(self):
super(OAIFetcherTestCase, self).setUp()
httpretty.register_uri(
httpretty.GET,
'http://content.cdlib.org/oai',
body=open(DIR_FIXTURES+'/testOAI.xml').read())
self.fetcher = fetcher.OAIFetcher('http://content.cdlib.org/oai',
'oac:images')
def tearDown(self):
super(OAIFetcherTestCase, self).tearDown()
httpretty.disable()
def testHarvestIsIter(self):
self.assertTrue(hasattr(self.fetcher, '__iter__'))
self.assertEqual(self.fetcher, self.fetcher.__iter__())
self.fetcher.next()
def testOAIFetcherReturnedData(self):
'''test that the data returned by the OAI Fetcher is a proper dc
dictionary
'''
rec = self.fetcher.next()
self.assertIsInstance(rec, dict)
self.assertIn('id', rec)
self.assertEqual(rec['id'], '13030/hb796nb5mn')
self.assertIn('datestamp', rec)
self.assertIn(rec['datestamp'], '2005-12-13')
def testDeletedRecords(self):
'''Test that the OAI harvest handles "deleted" records.
For now that means skipping over them.
'''
recs = []
for r in self.fetcher:
recs.append(r)
# skips over 5 "deleted" records
self.assertEqual(len(recs), 3)
@httpretty.activate
def testOverrideMetadataPrefix(self):
'''test that the metadataPrefix for an OAI feed can be overridden.
The extra_data for OAI can be either just a set spec or a html query
string of set= &metadataPrefix=
'''
httpretty.register_uri(
httpretty.GET,
'http://content.cdlib.org/oai',
body=open(DIR_FIXTURES+'/testOAI.xml').read())
set_fetcher = fetcher.OAIFetcher('http://content.cdlib.org/oai',
'set=oac:images')
self.assertEqual(set_fetcher._set, 'oac:images')
rec = set_fetcher.next()
self.assertIsInstance(rec, dict)
self.assertIn('id', rec)
self.assertEqual(rec['id'], '13030/hb796nb5mn')
self.assertIn('datestamp', rec)
self.assertIn(rec['datestamp'], '2005-12-13')
self.assertEqual(httpretty.last_request().querystring,
{u'verb': [u'ListRecords'], u'set': [u'oac:images'],
u'metadataPrefix': [u'oai_dc']})
httpretty.register_uri(
httpretty.GET,
'http://content.cdlib.org/oai',
body=open(DIR_FIXTURES+'/testOAI-didl.xml').read())
didl_fetcher = fetcher.OAIFetcher('http://content.cdlib.org/oai',
'set=oac:images&metadataPrefix=didl')
self.assertEqual(didl_fetcher._set, 'oac:images')
self.assertEqual(didl_fetcher._metadataPrefix, 'didl')
rec = didl_fetcher.next()
self.assertIsInstance(rec, dict)
self.assertIn('id', rec)
self.assertEqual(rec['id'], 'oai:ucispace-prod.lib.uci.edu:10575/25')
self.assertEqual(rec['title'], ['Schedule of lectures'])
self.assertIn('datestamp', rec)
self.assertEqual(rec['datestamp'], '2015-05-20T11:04:23Z')
self.assertEqual(httpretty.last_request().querystring,
{u'verb': [u'ListRecords'], u'set': [u'oac:images'],
u'metadataPrefix': [u'didl']})
self.assertEqual(rec['Resource']['@ref'],
'http://ucispace-prod.lib.uci.edu/xmlui/bitstream/' +
'10575/25/1/!COLLOQU.IA.pdf')
self.assertEqual(rec['Item']['@id'],
'uuid-640925bd-9cdf-46be-babb-b2138c3fce9c')
self.assertEqual(rec['Component']['@id'],
'uuid-897984d8-9392-4a68-912f-ffdf6fd7ce59')
self.assertIn('Descriptor', rec)
self.assertEqual(rec['Statement']['@mimeType'],
'application/xml; charset=utf-8')
self.assertEqual(
rec['DIDLInfo']
['{urn:mpeg:mpeg21:2002:02-DIDL-NS}DIDLInfo'][0]['text'],
'2015-05-20T20:30:26Z')
del didl_fetcher
httpretty.register_uri(
httpretty.GET,
'http://content.cdlib.org/oai',
body=open(DIR_FIXTURES+'/testOAI-tind.xml').read())
tind_fetcher = fetcher.OAIFetcher('http://content.cdlib.org/oai',
'set=sugoroku&metadataPrefix=marcxml')
self.assertEqual(tind_fetcher._set, 'sugoroku')
self.assertEqual(tind_fetcher._metadataPrefix, 'marcxml')
rec = tind_fetcher.next()
self.assertIsInstance(rec, dict)
self.assertIn('fields', rec)
filtered = filter(lambda x: '901' in x.keys(), rec['fields'])
self.assertEqual(len(filtered), 1)
self.assertEqual(filtered[0]['901']['subfields'][0]['m'], u'b17672647')
self.assertIn('datestamp', rec)
self.assertEqual(rec['datestamp'], '2019-11-21T18:01:27Z')
self.assertEqual(httpretty.last_request().querystring,
{u'verb': [u'ListRecords'], u'set': [u'sugoroku'],
u'metadataPrefix': [u'marcxml']})
@httpretty.activate
def testDCTERMS(self):
'''Test the OAI fetcher when the source data has exteneded dcterms in
it.
'''
DCTERMS = (
'abstract', 'accessRights', 'accrualMethod',
'accrualPeriodicity', 'accrualPolicy', 'alternative',
'audience', 'available', 'bibliographicCitation', 'conformsTo',
'contributor', 'coverage', 'created', 'creator', 'date',
'dateAccepted', 'dateCopyrighted', 'dateSubmitted',
'description', 'educationLevel', 'extent', 'format',
'hasFormat', 'hasPart', 'hasVersion', 'identifier',
'instructionalMethod', 'isFormatOf', 'isPartOf',
'isReferencedBy', 'isReplacedBy', 'isRequiredBy', 'issued',
'isVersionOf', 'language', 'license', 'mediator', 'medium',
'modified', 'provenance', 'publisher', 'references',
'relation', 'replaces', 'requires', 'rights', 'rightsHolder',
'source', 'spatial', 'subject', 'tableOfContents', 'temporal',
'title', 'type', 'valid')
httpretty.register_uri(
httpretty.GET,
'http://content.cdlib.org/oai',
body=open(DIR_FIXTURES+'/oai-with-dcterms.xml').read())
set_fetcher = fetcher.OAIFetcher('http://content.cdlib.org/oai',
'set=bogus')
self.assertEqual(set_fetcher._set, 'bogus')
rec = set_fetcher.next()
self.assertIsInstance(rec, dict)
self.assertIn('id', rec)
self.assertEqual(rec['id'],
'oai:digitalcollections.usfca.edu:p264101coll6/188')
for term in DCTERMS: # dependent on data fed to sickle
self.assertIn(term, rec.keys())
self.assertEqual(rec['created'], ['TEST dcterms:created'])
self.assertEqual(rec['date'], ['1927; ', 'TEST dcterms:date'])
@httpretty.activate
def test_getMetadataPrefix(self):
fmts = open(DIR_FIXTURES+'/oai-fmts.xml').read()
fmts_qdc = open(DIR_FIXTURES+'/oai-fmts-qdc.xml').read()
httpretty.register_uri(
httpretty.GET,
'http://xxxx.cdlib.org/oai?verb=ListMetadataFormats',
responses=[
httpretty.Response(body=fmts, status=200),
httpretty.Response(body=fmts, status=200),
httpretty.Response(body=fmts, status=200),
httpretty.Response(body=fmts_qdc, status=200),
])
set_fetcher = fetcher.OAIFetcher('http://xxxx.cdlib.org/oai',
'set=bogus')
self.assertEqual(set_fetcher._metadataPrefix, 'oai_dc')
prefix = set_fetcher.get_metadataPrefix('')
self.assertEqual(prefix, 'oai_dc')
prefix = set_fetcher.get_metadataPrefix('metadataPrefix=override')
self.assertEqual(prefix, 'override')
prefix = set_fetcher.get_metadataPrefix('')
self.assertEqual(prefix, 'oai_qdc')
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,075 | ucldc/harvester | refs/heads/master | /harvester/post_processing/couchdb_runner.py | import datetime
import time
from redis import Redis
from rq import Queue
from harvester.config import config
from harvester.couchdb_init import get_couchdb
from harvester.couchdb_pager import couchdb_pager
COUCHDB_VIEW = 'all_provider_docs/by_provider_name'
def get_collection_doc_ids(collection_id, url_couchdb_source=None):
'''Use the by_provider_name view to get doc ids for a given collection
'''
_couchdb = get_couchdb(url=url_couchdb_source)
v = CouchDBCollectionFilter(couchdb_obj=_couchdb,
collection_key=str(collection_id),
include_docs=False)
doc_ids = []
for r in v:
doc_ids.append(r.id)
return doc_ids
class CouchDBCollectionFilter(object):
'''Class for selecting collections from the UCLDC couchdb data store.
'''
def __init__(self,
collection_key=None,
couchdb_obj=None,
url_couchdb=None,
couchdb_name=None,
couch_view=COUCHDB_VIEW,
include_docs=True
):
if not collection_key:
collection_key = '{}'
if couchdb_obj is None:
if not url_couchdb or not couchdb_name:
raise ValueError('Need url and name to couch database')
self._couchdb = get_couchdb(url=url_couchdb, dbname=couchdb_name)
else:
self._couchdb = couchdb_obj
self._view = couch_view
self._view_iter = couchdb_pager(
self._couchdb, self._view,
key=collection_key,
include_docs='true' if include_docs else 'false')
def __iter__(self):
return self._view_iter.__iter__()
def next(self):
return self._view_iter.next()
class CouchDBWorker(object):
'''A class that can run functions on sets of couchdb documents
maybe become some sort of decorator?
Documents are mutable, so if the function mutates the document, it will
be picked up here.
????Add the "save" keyword argument to save the document to db???
functions should have call signature of (doc, *args, **kwargs)
'''
def __init__(self):
self._couchdb = get_couchdb()
def run_by_list_of_doc_ids(self, doc_ids, func, *args, **kwargs):
'''For a list of ids, harvest images'''
results = []
for doc_id in doc_ids:
doc = self._couchdb[doc_id]
results.append((doc_id, func(doc, *args, **kwargs)))
return results
def run_by_collection(self, collection_key, func, *args, **kwargs):
'''If collection_key is none, trying to grab all of the images. (Not
recommended)
'''
v = CouchDBCollectionFilter(couchdb_obj=self._couchdb,
collection_key=collection_key)
results = []
for r in v:
dt_start = dt_end = datetime.datetime.now()
result = func(r.doc, *args, **kwargs)
results.append((r.doc['_id'], result))
dt_end = datetime.datetime.now()
time.sleep((dt_end-dt_start).total_seconds())
return results
class CouchDBJobEnqueue(object):
'''A class that will put a job on the RQ worker queue for each document
selected. This should allow some parallelism.
Functions passed to this enqueuing object should take a CouchDB doc id
and should do whatever work & saving it needs to do on it.
'''
def __init__(self, rq_queue=None):
self._config = config()
self._couchdb = get_couchdb()
self._redis = Redis(
host=self._config['redis_host'],
port=self._config['redis_port'],
password=self._config['redis_password'],
socket_connect_timeout=self._config['redis_connect_timeout'])
self.rqname = self._config['rq_queue']
if rq_queue:
self.rqname = rq_queue
if not self.rqname:
raise ValueError(''.join(('Must set RQ_QUEUE env var',
' or pass in rq_queue to ',
'CouchDBJobEnqueue')))
self._rQ = Queue(self.rqname, connection=self._redis)
def queue_list_of_ids(self, id_list, job_timeout, func,
*args, **kwargs):
'''Enqueue jobs in the ingest infrastructure for a list of ids'''
results = []
for doc_id in id_list:
this_args = [doc_id]
if args:
this_args.extend(args)
this_args = tuple(this_args)
print('Enqueing doc {} args: {} kwargs:{}'.format(doc_id,
this_args,
kwargs))
result = self._rQ.enqueue_call(func=func,
args=this_args,
kwargs=kwargs,
timeout=job_timeout)
results.append(result)
return results
def queue_collection(self, collection_key, job_timeout, func,
*args, **kwargs):
'''Queue a job in the RQ queue for each document in the collection.
func is function to run and it must be accessible from the
rq worker's virtualenv.
func signature is func(doc_id, args, kwargs)
Can't pass the document in because it all gets converted to a string
and put into the RQ queue. Much easier to pass id and have worker deal
with couchdb directly.
'''
v = CouchDBCollectionFilter(couchdb_obj=self._couchdb,
collection_key=collection_key)
results = []
for r in v:
doc = r.doc
this_args = [doc['_id']]
if args:
this_args.extend(args)
this_args = tuple(this_args)
print('Enqueing doc {} args: {} kwargs:{}'.format(doc['_id'],
this_args,
kwargs))
result = self._rQ.enqueue_call(func=func,
args=this_args,
kwargs=kwargs,
timeout=job_timeout)
results.append(result)
if not results:
print "NO RESULTS FOR COLLECTION: {}".format(collection_key)
return results
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,076 | ucldc/harvester | refs/heads/master | /scripts/run_new_collection_all_docs.py | #! /bin/env python
'''run grabbing of new collection and updating in couch docs locally.
'''
import sys
import argparse
import Queue
import threading
import requests
import json
url_api_base = 'https://registry.cdlib.org/api/v1/collection/'
from harvester.post_processing.couchdb_runner import CouchDBWorker
from harvester.fetcher import HarvestController
from harvester.collection_registry_client import Collection
def fix_registry_data(doc, c_couch, _couchdb):
'''get the registry data for the collection,
use the HarvestControllers's _add_registry_data to update with @ids &
name.
Then for each doc in the collection, remove originalRecord campus &
repository. Replace originalRecord & sourceResource collection with
new collection object.
Save doc.
'''
#print "COLLECTION: {}".format(c_couch)
#print "REPO: {}".format(c_couch[0]['repository'])
#print "C@ID: {}".format(c_couch[0]['@id'])
#print "------COLL:{}\n----------------".format(c_couch[0])
#print "KEYS: {}".format(c_couch[0].keys())
#print 'KEYS COUCHDB ORIGREC lEN: {}'.format(len(doc['originalRecord'].keys()))
doc['originalRecord']['collection'] = c_couch
doc['sourceResource']['collection'] = c_couch
if 'repository' in doc['originalRecord']:
del(doc['originalRecord']['repository'])
if 'campus' in doc['originalRecord']:
del(doc['originalRecord']['campus'])
#print 'KEYS COUCHDB ORIGREC lEN: {}'.format(len(doc['originalRecord'].keys()))
#print 'Collection keys:{}'.format(doc['originalRecord']['collection'][0].keys())
print "UPDATING {}".format(doc.id)
# now save & get next one....
_couchdb[doc.id] = doc
def get_id_on_queue_and_run(queue):
cdbworker = CouchDBWorker()
cid = queue.get_nowait()
while cid:
c_reg = Collection(url_api_base+cid)
h = HarvestController('mark.redar@ucop.edu', c_reg)
c_couch = h._add_registry_data({})['collection']
del(h)
print "STARTING COLLECTION: {}".format(cid)
cdbworker.run_by_collection(cid, fix_registry_data, c_couch, cdbworker._couchdb)
print "FINISHED COLLECTION: {}".format(cid)
cid = queue.get_nowait()
if __name__=='__main__':
queue = Queue.Queue()
num_threads = 2
for l in open('collections-new-fix-stg.list'):
cid = l.strip()
#fill q, not parallel yet
queue.put(cid)
threads = [threading.Thread(target=get_id_on_queue_and_run,
args=(queue,)) for i in range(num_threads)]
print "THREADS:{} starting next".format(threads)
for t in threads:
t.start()
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,077 | ucldc/harvester | refs/heads/master | /scripts/remove_object_and_harvest_image_26094.py | #! /bin/env python
import sys
import os
from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
from harvester.post_processing.couchdb_runner import CouchDBWorker
from harvester.image_harvest import harvest_image_for_doc
from harvester.couchdb_init import get_couchdb
import couchdb #couchdb-python
from dplaingestion.selector import delprop
EMAIL_RETURN_ADDRESS = os.environ.get('EMAIL_RETURN_ADDRESS',
'example@example.com')
# csv delim email addresses
EMAIL_SYS_ADMIN = os.environ.get('EMAIL_SYS_ADMINS', None)
def delete_field_and_queue_image_harvest(doc, field, cdb, enq):
print 'Delete {} for {}'.format(field, doc['_id'])
delprop(doc, field, keyErrorAsNone=True)
cdb.save(doc)
timeout = 10000
results = enq.queue_list_of_ids([doc['_id']],
timeout,
harvest_image_for_doc,
)
def main(cid):
worker = CouchDBWorker()
enq = CouchDBJobEnqueue()
timeout = 100000
cdb = get_couchdb()
worker.run_by_collection(cid,
delete_field_and_queue_image_harvest,
'object',
cdb,
enq
)
if __name__ == '__main__':
main('26094')
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,078 | ucldc/harvester | refs/heads/master | /scripts/external-redirect-generate-URL-redirect-map.py | #! /bin/env python
# -*- coding: utf-8 -*-
# Use when Calisphere Object URLs for a collection change, to generate
# a redirect file mapping 'old' (on SOLR-PROD) to 'new' (on SOLR-TEST) URLs.
#
# This script takes the JSON file generated by
# external-redirect-get-solr_prod-id.py as input and queries SOLR-TEST to find
# matching records according to the 'match field' entered in
# external-redirect-get-solr_prod-id.py. It then generates a CSV file with a
# line for each match found, pairing the 'old' SOLR-PROD URLs with the
# corresponding 'new' SOLR-TEST URLs
import os
import argparse
import json
import requests
import solr
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# to get rid of ssl key warning
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# need to hardcode in SOLR-STAGE
SOLR_URL = "https://harvest-stg.cdlib.org/solr_api/"
SOLR_API_KEY = os.environ.get('SOLR_API_KEY', '')
def get_test_id(fullQuery, matchField, prod_id, matchVal, cid, exact_match):
solr_auth = { 'X-Authentication-Token': SOLR_API_KEY } if SOLR_API_KEY else None
if exact_match:
fullQuery = fullQuery.replace('*','"')
query = { 'q': fullQuery, 'rows':10, 'fl': 'id,{}'.format(matchField)}
solr_endpoint = SOLR_URL + 'query'
resp_obj = requests.get(solr_endpoint,
headers=solr_auth,
params=query,
verify=False)
results = resp_obj.json()
if results["response"]["numFound"] > 0:
if exact_match is True:
if results["response"]["numFound"] > 1:
matchVal = matchVal.replace("\ ","+")
new_id = '/collections/{}/?rq={}:"{}"'.format(cid,matchField,matchVal)
else:
for rec in results["response"]["docs"]:
found_id = rec["id"]
new_id = '/item/{}/'.format(found_id)
break
else:
for rec in results["response"]["docs"]:
found_id = rec["id"]
new_id = '/item/{}/'.format(found_id)
break
return prod_id,new_id
else:
new_id = "NOT FOUND"
return prod_id,new_id
def main(inFile, exact_match):
f = open(inFile, "r")
reCount = 0
try:
contents = json.load(f)
matchField = contents["responseHeader"]["params"]["fl"].split(',')[1]
queryVal = contents["responseHeader"]["params"]["q"].replace("collection_url:","")
cid = queryVal.replace("https://registry.cdlib.org/api/v1/collection/","")
cid = cid.replace("/","")
sQuery = 'collection_url:"{}"'.format(queryVal)
except:
print "Error, not valid JSON / SOLR output"
return None
print "Matching records in SOLR-TEST by {} for {}".format(
matchField,
sQuery)
z = open('CSPHERE_IDS.txt', "a+")
if contents["response"]["numFound"] is not 0:
z.write("\n# {}\n# match field: {}\n\n".format(queryVal, matchField))
for doc in contents["response"]["docs"]:
prodID = doc["id"]
matchVal = doc[matchField]
if isinstance(matchVal, list):
matchVal = matchVal[0]
matchVal = matchVal.replace(" ","\ ")
fullQuery = '{} AND {}:*{}*'.format(
sQuery,
matchField,
matchVal)
old_ID,new_ID = get_test_id(fullQuery,
matchField,
prodID,
matchVal,
cid,
exact_match)
if new_ID != "NOT FOUND":
reCount += 1
print "{} --> {}".format(old_ID, new_ID)
z.write("{} {}\n".format(old_ID, new_ID))
else:
print "{} -- {}".format(old_ID, new_ID)
print "{} matches found".format(reCount)
z.write("\n# {} matches found {}\n\n\n".format(reCount, queryVal))
z.close()
f.close()
if __name__=='__main__':
parser = argparse.ArgumentParser('This script takes as input the JSON ' \
'file generated by external-redirect-get-solr_prod-id.py and generates a ' \
'CSV pairing the old SOLR-PROD URLs with the corresponding new SOLR-TEST URLs' \
'\nUsage: external-redirect-generate-URL-redirect-map.py [JSON file]' )
parser.add_argument('inFile')
parser.add_argument(
'--exact_match',
action='store_true',
default=False,
help='No * wildcard matching, exact matching only. If more than'
' one match found in SOLR-TEST, redirect to SOLR query for'
' {match_field}:{match_value} (DEFAULT: false, add * wildcard'
' before and after {match_value}, return first SOLR query'
' result as match'
)
argv = parser.parse_args()
kwargs = {}
if not argv.inFile:
raise Exception(
"Please input valid JSON file")
if not argv.exact_match:
argv.exact_match = False
main(argv.inFile, argv.exact_match)
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,079 | ucldc/harvester | refs/heads/master | /scripts/queue_image_harvest.py | #! /bin/env python
""""
Usage:
$ python queue_image_harvest.py user-email url_collection_api
"""
import sys
import os
from harvester.config import config as config_harvest
from harvester.collection_registry_client import Collection
import logbook
from redis import Redis
from rq import Queue
EMAIL_RETURN_ADDRESS = os.environ.get('EMAIL_RETURN_ADDRESS',
'example@example.com')
# csv delim email addresses
EMAIL_SYS_ADMIN = os.environ.get('EMAIL_SYS_ADMINS', None)
IMAGE_HARVEST_TIMEOUT = 144000
def def_args():
import argparse
parser = argparse.ArgumentParser(description='Harvest a collection')
parser.add_argument('user_email', type=str, help='user email')
parser.add_argument('rq_queue', type=str, help='RQ Queue to put job in')
parser.add_argument(
'url_api_collection',
type=str,
help='URL for the collection Django tastypie api resource')
parser.add_argument(
'--object_auth',
nargs='?',
help='HTTP Auth needed to download images - username:password')
parser.add_argument(
'--url_couchdb', nargs='?', help='Override url to couchdb')
parser.add_argument(
'--timeout',
nargs='?',
help='set image harvest timeout in sec (14400 - 4hrs default)')
parser.add_argument(
'--get_if_object',
action='store_true',
default=False,
help='Should image harvester not get image if the object '
'field exists for the doc (default: False, always get)'
)
parser.add_argument(
'--ignore_content_type',
action='store_true',
default=False,
help='Should image harvester not check content type in URL '
'header if false or missing (default: False, always check)'
)
return parser
def queue_image_harvest(redis_host,
redis_port,
redis_password,
redis_timeout,
rq_queue,
collection_key,
url_couchdb=None,
object_auth=None,
get_if_object=False,
ignore_content_type=False,
harvest_timeout=IMAGE_HARVEST_TIMEOUT):
rQ = Queue(
rq_queue,
connection=Redis(
host=redis_host,
port=redis_port,
password=redis_password,
socket_connect_timeout=redis_timeout))
job = rQ.enqueue_call(
func='harvester.image_harvest.main',
kwargs=dict(
collection_key=collection_key,
url_couchdb=url_couchdb,
object_auth=object_auth,
get_if_object=get_if_object,
ignore_content_type=ignore_content_type),
timeout=harvest_timeout)
return job
def main(user_email,
url_api_collections,
log_handler=None,
mail_handler=None,
dir_profile='profiles',
profile_path=None,
config_file='akara.ini',
rq_queue=None,
**kwargs):
'''Runs a UCLDC ingest process for the given collection'''
emails = [user_email]
if EMAIL_SYS_ADMIN:
emails.extend([u for u in EMAIL_SYS_ADMIN.split(',')])
if not mail_handler:
mail_handler = logbook.MailHandler(
EMAIL_RETURN_ADDRESS, emails, level='ERROR', bubble=True)
mail_handler.push_application()
config = config_harvest(config_file=config_file)
if not log_handler:
log_handler = logbook.StderrHandler(level='DEBUG')
log_handler.push_application()
for url_api_collection in [x for x in url_api_collections.split(';')]:
try:
collection = Collection(url_api_collection)
except Exception, e:
msg = 'Exception in Collection {}, init {}'.format(
url_api_collection,
str(e))
logbook.error(msg)
raise e
queue_image_harvest(
config['redis_host'],
config['redis_port'],
config['redis_password'],
config['redis_connect_timeout'],
rq_queue=rq_queue,
collection_key=collection.id,
object_auth=collection.auth,
**kwargs)
log_handler.pop_application()
mail_handler.pop_application()
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args(sys.argv[1:])
if not args.user_email or not args.url_api_collection:
parser.print_help()
sys.exit(27)
kwargs = {}
if args.object_auth:
kwargs['object_auth'] = args.object_auth
if args.timeout:
kwargs['harvest_timeout'] = int(args.timeout)
if args.get_if_object:
kwargs['get_if_object'] = args.get_if_object
if args.ignore_content_type:
kwargs['ignore_content_type'] = args.ignore_content_type
main(
args.user_email,
args.url_api_collection,
rq_queue=args.rq_queue,
**kwargs)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,080 | ucldc/harvester | refs/heads/master | /harvester/fetcher/preservica_api_fetcher.py | # -*- coding: utf-8 -*-
import requests
import json
from requests.auth import HTTPBasicAuth
from xml.etree import ElementTree as ET
from xmljson import badgerfish
from .fetcher import Fetcher
class PreservicaFetcher(Fetcher):
'''Harvest from Preservica API
https://demo.preservica.com/api/entity/documentation.html
NOTE API calls may need updating in future:
https://developers.preservica.com/blog/api-versioning-in-preservica-6-2
'''
def __init__(self, url_harvest, extra_data, **kwargs):
super(PreservicaFetcher, self).__init__(url_harvest, extra_data)
# parse extra data for username, password
self.uname, self.pswd = extra_data.split(',')
# build API Collection URL from url_harvest
urlOne, urlTwo = url_harvest.split('SO_')
collectionID = urlTwo.replace('/','')
self.url_API = '/'.join(('https://us.preservica.com/api/entity/v6.0/structural-objects',
collectionID, 'children'))
self.doc_total = 0
self.doc_current = 0
def _dochits_to_objset(self, docHits):
objset = []
#iterate through docHits
for d in docHits:
# need to descend two layers in API for object metadata
url_object = d.text
obj_resp = requests.get(url_object,
auth=HTTPBasicAuth(self.uname.strip(), self.pswd.strip()))
objTree = ET.fromstring(obj_resp.content)
for mdataRef in objTree.findall('{http://preservica.com/EntityAPI/v6.0}'
'AdditionalInformation/{http://preservica.com/'
'EntityAPI/v6.0}Metadata/{http://preservica.com/'
'EntityAPI/v6.0}Fragment[@schema="http://www.open'
'archives.org/OAI/2.0/oai_dc/"]'):
url_mdata = mdataRef.text
mdata_resp = requests.get(url_mdata,
auth=HTTPBasicAuth(self.uname.strip(), self.pswd.strip()))
mdataTree = ET.fromstring(mdata_resp.content)
object = [
# strip namespace from JSON
json.dumps(badgerfish.data(x)).replace('{http://purl.org/dc/elements/1.1/}','')
for x in mdataTree.findall('{http://preservica.com/XIP/v6.0}MetadataContainer/'
'{http://preservica.com/XIP/v6.0}Content/'
'{http://www.openarchives.org/OAI/2.0/oai_dc/}dc')
]
# need to inject Preservica ID into json for isShownAt/isShownBy
preservica_id = url_object.split('information-objects/')[1]
jRecord = json.loads(object[0])
jRecord.update({"preservica_id": { "$": preservica_id } })
objset.append(jRecord)
self.doc_current += len(docHits)
if self.url_next:
self.url_API = self.url_next
return objset
def next(self):
resp = requests.get(self.url_API,
auth=HTTPBasicAuth(self.uname.strip(), self.pswd.strip()))
tree = ET.fromstring(resp.content)
TotalResults = tree.find('{http://preservica.com/EntityAPI/v6.0}'
'Paging/{http://preservica.com/'
'EntityAPI/v6.0}TotalResults')
self.doc_total = int(TotalResults.text)
if self.doc_current >= self.doc_total:
if self.doc_current != self.doc_total:
raise ValueError(
"Number of documents fetched ({0}) doesn't match \
total reported by server ({1})".format(
self.doc_current, self.doc_total))
else:
raise StopIteration
next_url = tree.find('{http://preservica.com/EntityAPI/v6.0}'
'Paging/{http://preservica.com/'
'EntityAPI/v6.0}Next')
if next_url is not None:
self.url_next = next_url.text
else:
self.url_next = None
hits = tree.findall('{http://preservica.com/EntityAPI/v6.0}'
'Children/{http://preservica.com/'
'EntityAPI/v6.0}Child')
return self._dochits_to_objset(hits)
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,081 | ucldc/harvester | refs/heads/master | /harvester/run_ingest.py | """
Script to run the ingest process.
Usage:
$ python run_ingest.py user-email url_collection_api
"""
import sys
import os
from dplaingestion.scripts import enrich_records
from dplaingestion.scripts import save_records
from dplaingestion.scripts import remove_deleted_records
from dplaingestion.scripts import dashboard_cleanup
from dplaingestion.scripts import check_ingestion_counts
import logbook
from harvester import fetcher
from harvester.config import config as config_harvest
from harvester.collection_registry_client import Collection
from harvester.sns_message import publish_to_harvesting
from harvester.sns_message import format_results_subject
from redis import Redis
from rq import Queue
import harvester.image_harvest
from harvester.cleanup_dir import cleanup_work_dir
EMAIL_RETURN_ADDRESS = os.environ.get('EMAIL_RETURN_ADDRESS',
'example@example.com')
# csv delim email addresses
EMAIL_SYS_ADMIN = os.environ.get('EMAIL_SYS_ADMINS', None)
IMAGE_HARVEST_TIMEOUT = 259200 # 3 days
def def_args():
import argparse
parser = argparse.ArgumentParser(description='Harvest a collection')
parser.add_argument('user_email', type=str, help='user email')
parser.add_argument('rq_queue', type=str, help='RQ queue to put job on')
parser.add_argument(
'url_api_collection',
type=str,
help='URL for the collection Django tastypie api resource')
return parser
def queue_image_harvest(redis_host,
redis_port,
redis_pswd,
redis_timeout,
url_couchdb,
collection_key,
rq_queue,
object_auth=None):
rQ = Queue(
rq_queue,
connection=Redis(
host=redis_host,
port=redis_port,
password=redis_pswd,
socket_connect_timeout=redis_timeout))
job = rQ.enqueue_call(
func=harvester.image_harvest.main,
kwargs=dict(
collection_key=collection_key,
url_couchdb=url_couchdb,
object_auth=object_auth,
get_if_object=False),
# default to no harvesting image
# if object field has data
timeout=IMAGE_HARVEST_TIMEOUT, )
return job
def main(user_email,
url_api_collection,
log_handler=None,
mail_handler=None,
dir_profile='profiles',
profile_path=None,
config_file=None,
redis_host=None,
redis_port=None,
redis_pswd=None,
redis_timeout=600,
rq_queue=None,
run_image_harvest=False,
**kwargs):
'''Runs a UCLDC ingest process for the given collection'''
cleanup_work_dir() # remove files from /tmp
emails = [user_email]
if EMAIL_SYS_ADMIN:
emails.extend([u for u in EMAIL_SYS_ADMIN.split(',')])
if not mail_handler:
mail_handler = logbook.MailHandler(
EMAIL_RETURN_ADDRESS, emails, level='ERROR', bubble=True)
mail_handler.push_application()
if not config_file:
config_file = os.environ.get('DPLA_CONFIG_FILE', 'akara.ini')
if not (redis_host and redis_port and redis_pswd):
config = config_harvest(config_file=config_file)
try:
collection = Collection(url_api_collection)
except Exception as e:
msg = 'Exception in Collection {}, init {}'.format(url_api_collection,
str(e))
logbook.error(msg)
raise e
if not log_handler:
log_handler = logbook.StderrHandler(level='DEBUG')
log_handler.push_application()
logger = logbook.Logger('run_ingest')
ingest_doc_id, num_recs, dir_save, harvester = fetcher.main(
emails,
url_api_collection,
log_handler=log_handler,
mail_handler=mail_handler,
**kwargs)
if 'prod' in os.environ['DATA_BRANCH'].lower():
if not collection.ready_for_publication:
raise Exception(''.join(
('Collection {} is not ready for publication.',
' Run on stage and QA first, then set',
' ready_for_publication')).format(collection.id))
logger.info("INGEST DOC ID:{0}".format(ingest_doc_id))
logger.info('HARVESTED {0} RECORDS'.format(num_recs))
logger.info('IN DIR:{0}'.format(dir_save))
resp = enrich_records.main([None, ingest_doc_id])
if not resp == 0:
logger.error("Error enriching records {0}".format(resp))
raise Exception('Failed during enrichment process: {0}'.format(resp))
logger.info('Enriched records')
resp = save_records.main([None, ingest_doc_id])
if not resp >= 0:
logger.error("Error saving records {0}".format(str(resp)))
raise Exception("Error saving records {0}".format(str(resp)))
num_saved = resp
logger.info("SAVED RECS : {}".format(num_saved))
resp = remove_deleted_records.main([None, ingest_doc_id])
if not resp == 0:
logger.error("Error deleting records {0}".format(resp))
raise Exception("Error deleting records {0}".format(resp))
resp = check_ingestion_counts.main([None, ingest_doc_id])
if not resp == 0:
logger.error("Error checking counts {0}".format(resp))
raise Exception("Error checking counts {0}".format(resp))
resp = dashboard_cleanup.main([None, ingest_doc_id])
if not resp == 0:
logger.error("Error cleaning up dashboard {0}".format(resp))
raise Exception("Error cleaning up dashboard {0}".format(resp))
subject = format_results_subject(collection.id,
'Harvest to CouchDB {env} ')
publish_to_harvesting(subject,
'Finished metadata harvest for CID: {}\n'
'Fetched: {}\nSaved: {}'.format(
collection.id,
num_recs,
num_saved))
log_handler.pop_application()
mail_handler.pop_application()
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args(sys.argv[1:])
if not args.user_email or not args.url_api_collection or not args.rq_queue:
parser.print_help()
sys.exit(27)
conf = config_harvest()
main(
args.user_email,
args.url_api_collection,
redis_host=conf['redis_host'],
redis_port=conf['redis_port'],
redis_pswd=conf['redis_password'],
redis_timeout=conf['redis_connect_timeout'],
rq_queue=args.rq_queue)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,082 | ucldc/harvester | refs/heads/master | /test/test_preservica_api_fetcher.py | # -*- coding: utf-8 -*-
from unittest import TestCase
from mypretty import httpretty
# import httpretty
import harvester.fetcher as fetcher
from test.utils import LogOverrideMixin
from test.utils import DIR_FIXTURES
class PreservicaFetcherTestCase(LogOverrideMixin, TestCase):
@httpretty.activate
def testPreservicaFetch(self):
httpretty.register_uri(
httpretty.GET,
'https://us.preservica.com/api/entity/v6.0/structural-objects/eb2416ec-ac1e-4e5e-baee-84e3371c03e9/children',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/preservica-page-1.xml').read())
])
httpretty.register_uri(
httpretty.GET,
'https://us.preservica.com/api/entity/v6.0/structural-objects/eb2416ec-ac1e-4e5e-baee-84e3371c03e9/children/?start=100&max=100',
match_querystring=True,
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/preservica-page-2.xml').read())
])
httpretty.register_uri(
httpretty.GET,
'https://us.preservica.com/api/entity/v6.0/information-objects/8c81f065-b6e4-457e-8b76-d18176f74bee',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/preservica-child-1.xml').read())
])
httpretty.register_uri(
httpretty.GET,
'https://us.preservica.com/api/entity/v6.0/information-objects/8c81f065-b6e4-457e-8b76-d18176f74bee/metadata/37db4583-8e8e-4778-ac90-ad443664c5cb',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/preservica-child-2.xml').read())
])
httpretty.register_uri(
httpretty.GET,
'https://us.preservica.com/api/entity/v6.0/information-objects/9501e09f-1ae8-4abc-a9ec-6c705ff8fdbe',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/preservica-child-3.xml').read())
])
httpretty.register_uri(
httpretty.GET,
'https://us.preservica.com/api/entity/v6.0/information-objects/9501e09f-1ae8-4abc-a9ec-6c705ff8fdbe/metadata/ec5c46e5-443e-4b6d-81b9-ec2a5252a50c',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/preservica-child-4.xml').read())
])
h = fetcher.PreservicaFetcher(
'https://oakland.access.preservica.com/v6.0/uncategorized/SO_eb2416ec-ac1e-4e5e-baee-84e3371c03e9/',
'usr, pwd')
docs = []
d = h.next()
docs.extend(d)
logger.error(docs[0])
for d in h:
docs.extend(d)
self.assertEqual(len(docs), 17)
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,083 | ucldc/harvester | refs/heads/master | /scripts/harvest_ready_for_publication.py | import requests
from harvester.config import config
from harvester.scripts.queue_harvest import main as queue_harvest
env=config()
c_prod=[]
c_harvest=[]
url_reg = "https://registry.cdlib.org"
url_reg_api = '{}{}'.format(url_reg, "/api/v1/collection/")
url='{}{}'.format(url_reg_api, "?format=json&limit=1000")
resp=requests.get(url)
api=resp.json()
nextpage=api['meta']['next']
print "NEXTPAGE:{}".format(nextpage)
while nextpage:
for o in api['objects']:
if o['ready_for_publication']:
c_prod.append(o)
url_api_collection = '{}{}/'.format(url_reg_api, o['id'])
print url_api_collection
queue_harvest('mredar@gmail.com', url_api_collection,
redis_host=env['redis_host'],
redis_port=env['redis_port'],
redis_pswd=env['redis_password'],
rq_queue='normal-production')
if o['url_harvest']:
c_harvest.append(o)
resp = requests.get(''.join(('https://registry.cdlib.org', nextpage)))
api = resp.json()
nextpage=api['meta']['next']
print "NEXTPAGE:{}".format(nextpage)
print "READY FOR PUB:{}".format(len(c_prod))
print "READY FOR HARVEST:{}".format(len(c_harvest))
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,084 | ucldc/harvester | refs/heads/master | /scripts/harvest_all_images.py | #! /bin/env python
# harvest images for the given collection
# by this point the isShownBy value for the doc should be filled in.
# this should point at the highest fidelity object file available
# from the source.
# use brian's content md5s3stash to store the resulting image.
# should just be a call to md5s3stash
import datetime
import time
from md5s3stash import md5s3stash
import couchdb
from harvester.couchdb_pager import couchdb_pager
from harvester.image_harvest import stash_image
BUCKET_BASE = 'ucldc' #old virginia
BUCKET_BASE = 'static.ucldc.cdlib.org/harvested_images' #new oregon
BUCKET_BASE = 'static-ucldc-cdlib-org/harvested_images' #new oregon
SERVER_COUCHDB = 'https://54.84.142.143/couchdb'
DB_COUCHDB = 'ucldc'
COUCH_VIEW = 'all_provider_docs/by_provider_name'
def get_isShownBy(doc):
best_image = None
x = 0
thumb = doc['originalRecord'].get('thumbnail', None)
if thumb:
x = thumb['X']
best_image = thumb
ref_images = doc['originalRecord'].get('reference-image', [])
if type(ref_images) == dict:
ref_images = [ref_images]
for obj in ref_images:
if int(obj['X']) > x:
x = int(obj['X'])
best_image = obj
if not best_image:
raise KeyError('No image reference fields found')
return best_image
#Need to make each download a separate job.
def main(collection_key=None, url_couchdb=SERVER_COUCHDB):
'''If collection_key is none, trying to grab all of the images. (Not
recommended)
'''
s = couchdb.Server(url=url_couchdb)
db = s[DB_COUCHDB]
#v = db.view(COUCH_VIEW, include_docs='true', key=collection_key) if collection_key else db.view(COUCH_VIEW, include_docs='true')
v = couchdb_pager(db, view_name=COUCH_VIEW, include_docs='true', key=collection_key) if collection_key else couchdb_pager(db, view_name=COUCH_VIEW, include_docs='true')
for r in v:
doc = r.doc
msg = doc['_id']
if 's3://' in doc.get('object', ''): #already downloaded
msg = ' '.join((msg, 'already fetched image'))
continue
try:
doc['isShownBy'] = doc.get('isShownBy', get_isShownBy(doc))
except Exception, e:
print("ERROR: Can't get isShownBy for {} : {}".format(doc['_id'], e))
continue #next doc
try:
url_image = doc['isShownBy']['src']
dt_start = dt_end = datetime.datetime.now()
report = md5s3stash(url_image, bucket_base=BUCKET_BASE)
dt_end = datetime.datetime.now()
doc['object'] = report.s3_url
db.save(doc)
msg = ' '.join((msg, doc['object']))
except KeyError, e:
msg = ' '.join((msg, "ERROR: No isShownBy field"))
except TypeError, e:
msg = ' '.join((msg, "ERROR: {}".format(e)))
except IOError, e:
msg = ' '.join((msg, "ERROR: {}".format(e)))
time.sleep((dt_end-dt_start).total_seconds())
print msg
if __name__=='__main__':
main()
#main(collection_key='1934-international-longshoremens-association-and-g')
#main(collection_key='uchida-yoshiko-photograph-collection')
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,085 | ucldc/harvester | refs/heads/master | /harvester/fetcher/cmis_atom_feed_fetcher.py | # -*- coding: utf-8 -*-
import requests
from requests.auth import HTTPBasicAuth
from xml.etree import ElementTree as ET
from xmljson import badgerfish
from .fetcher import Fetcher
class CMISAtomFeedFetcher(Fetcher):
'''harvest a CMIS Atom Feed. Don't know how generic this is, just working
with Oakland Public Library Preservica implementation.
Right now this uses the "descendants" page for collections, this gets all
the data for one collection from one http request then parses the resulting
data. This might not work if we get collections much bigger than the
current ones (~1000 objects max)
'''
def __init__(self, url_harvest, extra_data, **kwargs):
'''Grab file and copy to local temp file'''
super(CMISAtomFeedFetcher, self).__init__(url_harvest, extra_data)
# parse extra data for username,password
uname, pswd = extra_data.split(',')
resp = requests.get(url_harvest,
auth=HTTPBasicAuth(uname.strip(), pswd.strip()))
self.tree = ET.fromstring(resp.content)
self.objects = [
badgerfish.data(x)
for x in self.tree.findall('./{http://www.w3.org/2005/Atom}'
'entry/{http://docs.oasis-open.org/'
'ns/cmis/restatom/200908/}children//'
'{http://www.w3.org/2005/Atom}entry')
]
self.objects_iter = iter(self.objects)
def next(self):
return self.objects_iter.next()
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,086 | ucldc/harvester | refs/heads/master | /scripts/queue_collection_reenrich.py | '''Enqueue a collection's docuemnts for re-enriching.
'''
import sys
import argparse
from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
from harvester.config import parse_env
import harvester.post_processing.enrich_existing_couch_doc
def main(args):
parser = argparse.ArgumentParser(
description='run an Akara enrichment chain on documents in a \
collection.')
parser.add_argument('collection_id',
help='Registry id for the collection')
parser.add_argument('enrichment', help='File of enrichment chain to run')
parser.add_argument('--rq_queue',
help='Override queue for jobs, normal-stage is default')
args = parser.parse_args(args)
print "CID:{}".format(args.collection_id)
print "ENRICH FILE:{}".format(args.enrichment)
with open(args.enrichment) as enrichfoo:
enrichments = enrichfoo.read()
Q = 'normal-stage'
if args.rq_queue:
Q = args.rq_queue
enq = CouchDBJobEnqueue(Q)
timeout = 10000
enq.queue_collection(args.collection_id, timeout,
harvester.post_processing.enrich_existing_couch_doc.main,
enrichments
)
if __name__=='__main__':
main(sys.argv[1:])
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,087 | ucldc/harvester | refs/heads/master | /test/test_collection_registry_client.py | from unittest import TestCase
import json
import StringIO
from mypretty import httpretty
# import httpretty
from mock import patch
from harvester.collection_registry_client import Registry, Collection
from test.utils import DIR_FIXTURES
class RegistryApiTestCase(TestCase):
'''Test that the registry api works for our purposes'''
@httpretty.activate
def setUp(self):
httpretty.register_uri(httpretty.GET,
'https://registry.cdlib.org/api/v1/',
body='''{"campus": {"list_endpoint": "/api/v1/campus/", "schema": "/api/v1/campus/schema/"}, "collection": {"list_endpoint": "/api/v1/collection/", "schema": "/api/v1/collection/schema/"}, "repository": {"list_endpoint": "/api/v1/repository/", "schema": "/api/v1/repository/schema/"}}''')
self.registry = Registry()
def testRegistryListEndpoints(self):
# use set so order independent
self.assertEqual(set(self.registry.endpoints.keys()),
set(['collection', 'repository', 'campus']))
self.assertRaises(ValueError, self.registry.resource_iter, 'x')
@httpretty.activate
def testResourceIteratorOnePage(self):
'''Test when less than one page worth of objects fetched'''
httpretty.register_uri(httpretty.GET,
'https://registry.cdlib.org/api/v1/campus/',
body=open(DIR_FIXTURES+'/registry_api_campus.json').read())
l = []
for c in self.registry.resource_iter('campus'):
l.append(c)
self.assertEqual(len(l), 10)
self.assertEqual(l[0]['slug'], 'UCB')
@httpretty.activate
def testResourceIteratoreMultiPage(self):
'''Test when less than one page worth of objects fetched'''
httpretty.register_uri(httpretty.GET,
'https://registry.cdlib.org/api/v1/repository/?limit=20&offset=20',
body=open(DIR_FIXTURES+'/registry_api_repository-page-2.json').read())
httpretty.register_uri(httpretty.GET,
'https://registry.cdlib.org/api/v1/repository/',
body=open(DIR_FIXTURES+'/registry_api_repository.json').read())
riter = self.registry.resource_iter('repository')
self.assertEqual(riter.url, 'https://registry.cdlib.org/api/v1/repository/')
self.assertEqual(riter.path_next, '/api/v1/repository/?limit=20&offset=20')
r = ''
for x in range(0, 38):
r = riter.next()
self.assertFalse(isinstance(r, Collection))
self.assertEqual(r['resource_uri'], '/api/v1/repository/42/')
self.assertEqual(riter.url, 'https://registry.cdlib.org/api/v1/repository/?limit=20&offset=20')
self.assertEqual(riter.path_next, None)
self.assertRaises(StopIteration, riter.next)
@httpretty.activate
def testResourceIteratorReturnsCollection(self):
'''Test that the resource iterator returns a Collection object
for library collection resources'''
httpretty.register_uri(httpretty.GET,
'https://registry.cdlib.org/api/v1/collection/',
body=open(DIR_FIXTURES+'/registry_api_collection.json').read())
riter = self.registry.resource_iter('collection')
c = riter.next()
self.assertTrue(isinstance(c, Collection))
self.assertTrue(hasattr(c, 'auth'))
self.assertEqual(c.auth, None)
@httpretty.activate
def testNuxeoCollectionAuth(self):
'''Test that a Nuxeo harvest collection returns an
authentication tuple, not None
'''
httpretty.register_uri(httpretty.GET,
'https://registry.cdlib.org/api/v1/collection/19',
body=open(DIR_FIXTURES+'/registry_api_collection_nuxeo.json').read())
c = Collection('https://registry.cdlib.org/api/v1/collection/19')
self.assertTrue(c.harvest_type, 'NUX')
defaultrc = """\
[nuxeo_account]
user = TestUser
password = TestPass
[platform_importer]
base = http://localhost:8080/nuxeo/site/fileImporter
"""
with patch('__builtin__.open') as fakeopen:
fakeopen.return_value = StringIO.StringIO(defaultrc)
self.assertEqual(c.auth[0], 'TestUser')
self.assertEqual(c.auth[1], 'TestPass')
class ApiCollectionTestCase(TestCase):
'''Test that the Collection object is complete from the api
'''
@httpretty.activate
def testOAICollectionAPI(self):
httpretty.register_uri(httpretty.GET,
'https://registry.cdlib.org/api/v1/collection/197',
body=open(DIR_FIXTURES+'/collection_api_test.json').read())
c = Collection('https://registry.cdlib.org/api/v1/collection/197')
self.assertEqual(c['harvest_type'], 'OAI')
self.assertEqual(c.harvest_type, 'OAI')
self.assertEqual(c['name'], 'Calisphere - Santa Clara University: Digital Objects')
self.assertEqual(c.name, 'Calisphere - Santa Clara University: Digital Objects')
self.assertEqual(c['url_oai'], 'fixtures/testOAI-128-records.xml')
self.assertEqual(c.url_oai, 'fixtures/testOAI-128-records.xml')
self.assertEqual(c.campus[0]['resource_uri'], '/api/v1/campus/12/')
self.assertEqual(c.campus[0]['slug'], 'UCDL')
@httpretty.activate
def testOACApiCollection(self):
httpretty.register_uri(httpretty.GET,
'https://registry.cdlib.org/api/v1/collection/178',
body=open(DIR_FIXTURES+'/collection_api_test_oac.json').read())
c = Collection('https://registry.cdlib.org/api/v1/collection/178')
self.assertEqual(c['harvest_type'], 'OAJ')
self.assertEqual(c.harvest_type, 'OAJ')
self.assertEqual(c['name'], 'Harry Crosby Collection')
self.assertEqual(c.name, 'Harry Crosby Collection')
self.assertEqual(c['url_oac'], 'fixtures/testOAC.json')
self.assertEqual(c.url_oac, 'fixtures/testOAC.json')
self.assertEqual(c.campus[0]['resource_uri'], '/api/v1/campus/6/')
self.assertEqual(c.campus[0]['slug'], 'UCSD')
self.assertEqual(c.dcmi_type, 'I')
self.assertEqual(c.rights_statement, "a sample rights statement")
self.assertEqual(c.rights_status, "PD")
@httpretty.activate
def testCreateProfile(self):
'''Test the creation of a DPLA style proflie file'''
httpretty.register_uri(httpretty.GET,
'https://registry.cdlib.org/api/v1/collection/178',
body=open(DIR_FIXTURES+'/collection_api_test_oac.json').read())
c = Collection('https://registry.cdlib.org/api/v1/collection/178')
self.assertTrue(hasattr(c, 'dpla_profile'))
self.assertIsInstance(c.dpla_profile, str)
j = json.loads(c.dpla_profile)
self.assertEqual(j['name'], '178')
self.assertEqual(j['enrichments_coll'], ['/compare_with_schema'])
self.assertTrue('enrichments_item' in j)
self.assertIsInstance(j['enrichments_item'], list)
self.assertEqual(len(j['enrichments_item']), 30)
self.assertIn('contributor', j)
self.assertIsInstance(j['contributor'], list)
self.assertEqual(len(j['contributor']), 4)
self.assertEqual(j['contributor'][1], {u'@id': u'/api/v1/campus/1/', u'name': u'UCB'})
self.assertTrue(hasattr(c, 'dpla_profile_obj'))
self.assertIsInstance(c.dpla_profile_obj, dict)
self.assertIsInstance(c.dpla_profile_obj['enrichments_item'], list)
e = c.dpla_profile_obj['enrichments_item']
self.assertEqual(e[0], '/oai-to-dpla')
self.assertEqual(e[1], '/shred?prop=sourceResource/contributor%2CsourceResource/creator%2CsourceResource/date')
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,088 | ucldc/harvester | refs/heads/master | /harvester/post_processing/batch_update_couchdb_by_collection.py | #! /bin/env python
import sys
from harvester.couchdb_init import get_couchdb
from harvester.post_processing.couchdb_runner import CouchDBCollectionFilter
from harvester.sns_message import publish_to_harvesting
from harvester.sns_message import format_results_subject
PATH_DELIM = '/'
def setprop(obj, path, val, substring, keyErrorAsNone=False):
"""
Sets the value of the key identified by interpreting
the path as a delimited hierarchy of keys. Enumerate
if object is list.
"""
if '/' not in path:
if type(obj[path]) == list:
values = []
for t in obj[path]:
if substring:
values.append(t.replace(substring,val))
else:
values.append(val)
obj[path] = values
return
else:
if path not in obj:
if not keyErrorAsNone:
raise KeyError('Path not found in object: %s' % (path))
else:
return None
else:
if substring:
obj[path] = obj[path].replace(substring,val)
else:
obj[path] = val
return
if type(obj) == list:
obj = obj[0]
pp, pn = tuple(path.lstrip(PATH_DELIM).split(PATH_DELIM, 1))
if pp not in obj:
if not keyErrorAsNone:
raise KeyError('Path not found in object: %s (%s)' % (path, pp))
else:
return None
return setprop(obj[pp], pn, val, substring, keyErrorAsNone)
def update_by_id_list(ids, fieldName, newValue, substring, _couchdb=None):
'''For a list of couchdb ids, given field name and new value, update the doc[fieldname] with "new value"'''
updated = []
num_updated = 0
print >> sys.stderr, "SUBSTRING 1: {}".format(substring)
for did in ids:
doc = _couchdb.get(did)
if not doc:
continue
setprop(doc, fieldName, newValue, substring)
_couchdb.save(doc)
updated.append(did)
print >> sys.stderr, "UPDATED: {0}".format(did)
num_updated += 1
return num_updated, updated
def update_couch_docs_by_collection(cid, fieldName, newValue, substring):
print >> sys.stderr, "UPDATING DOCS FOR COLLECTION: {}".format(cid)
_couchdb = get_couchdb()
rows = CouchDBCollectionFilter(collection_key=cid, couchdb_obj=_couchdb)
ids = [row['id'] for row in rows]
num_updated, updated_docs = update_by_id_list(
ids, fieldName, newValue, substring, _couchdb=_couchdb)
subject = format_results_subject(cid,
'Updated documents from CouchDB {env} ')
publish_to_harvesting(
subject, 'Updated {} documents from CouchDB collection CID: {}'.format(
num_updated, cid))
return num_updated, updated_docs
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,089 | ucldc/harvester | refs/heads/master | /test/test_image_harvest.py | import os
from unittest import TestCase
from collections import namedtuple
from mock import patch
from mock import MagicMock
from mypretty import httpretty
# import httpretty
from harvester import image_harvest
from harvester.image_harvest import FailsImageTest
from harvester.image_harvest import ImageHTTPError
from harvester.image_harvest import IsShownByError
from harvester.image_harvest import HasObject
from harvester.image_harvest import RestoreFromObjectCache
#TODO: make this importable from md5s3stash
StashReport = namedtuple('StashReport',
'url, md5, s3_url, mime_type, dimensions')
class ImageHarvestTestCase(TestCase):
'''Test the md5 s3 image harvesting calls.....
TODO: Increase test coverage
'''
def setUp(self):
self.old_url_couchdb = os.environ.get('COUCHDB_URL', None)
os.environ['COUCHDB_URL'] = 'http://example.edu/test'
def tearDown(self):
if self.old_url_couchdb:
os.environ['COUCHDB_URL'] = self.old_url_couchdb
@patch('boto.s3.connect_to_region', return_value='S3Conn to a region')
@patch('harvester.image_harvest.Redis', autospec=True)
@patch('couchdb.Server')
@patch(
'md5s3stash.md5s3stash',
autospec=True,
return_value=StashReport('test url', 'md5 test value', 's3 url object',
'mime_type', 'dimensions'))
@httpretty.activate
def test_stash_image(self, mock_stash, mock_couch, mock_redis,
mock_s3_connect):
'''Test the stash image calls are correct'''
doc = {'_id': 'TESTID'}
image_harvester = image_harvest.ImageHarvester(
url_cache={}, hash_cache={}, bucket_bases=['region:x'])
self.assertRaises(IsShownByError, image_harvester.stash_image, doc)
doc['isShownBy'] = None
self.assertRaises(IsShownByError, image_harvester.stash_image, doc)
doc['isShownBy'] = ['ark:/test_local_url_ark:']
url_test = 'http://content.cdlib.org/ark:/test_local_url_ark:'
httpretty.register_uri(
httpretty.HEAD,
url_test,
body='',
content_length='0',
content_type='image/jpeg;',
connection='close', )
ret = image_harvester.stash_image(doc)
mock_stash.assert_called_with(
url_test,
url_auth=None,
bucket_base='x',
conn='S3Conn to a region',
hash_cache={},
url_cache={})
self.assertEqual('s3 url object', ret[0].s3_url)
ret = image_harvester.stash_image(doc)
mock_stash.assert_called_with(
url_test,
url_auth=None,
bucket_base='x',
conn='S3Conn to a region',
hash_cache={},
url_cache={})
ret = image_harvest.ImageHarvester(
bucket_bases=['region:x'],
object_auth=('tstuser', 'tstpswd'),
url_cache={},
hash_cache={}).stash_image(doc)
mock_stash.assert_called_with(
url_test,
url_auth=('tstuser', 'tstpswd'),
bucket_base='x',
conn='S3Conn to a region',
hash_cache={},
url_cache={})
doc['isShownBy'] = ['not a url']
self.assertRaises(FailsImageTest, image_harvester.stash_image, doc)
def test_update_doc_object(self):
'''Test call to couchdb, right data'''
doc = {'_id': 'TESTID'}
r = StashReport('s3 test2 url', 'md5 test value', 's3 url',
'mime_type', 'dimensions-x:y')
db = MagicMock()
image_harvester = image_harvest.ImageHarvester(
cdb=db, url_cache={}, hash_cache={}, bucket_bases=['region:x'])
ret = image_harvester.update_doc_object(doc, r)
self.assertEqual('md5 test value', ret)
self.assertEqual('md5 test value', doc['object'])
self.assertEqual(doc['object_dimensions'], 'dimensions-x:y')
db.save.assert_called_with({
'_id': 'TESTID',
'object': 'md5 test value',
'object_dimensions': 'dimensions-x:y'
})
@httpretty.activate
def test_link_is_to_image(self):
'''Test the link_is_to_image function'''
url = 'http://getthisimage/notauthorized'
httpretty.register_uri(
httpretty.HEAD,
url,
body='',
content_length='0',
content_type='text/plain; charset=utf-8',
connection='close',
status=401)
httpretty.register_uri(
httpretty.GET,
url,
body='',
content_length='0',
content_type='text/html; charset=utf-8',
connection='close',
status=401)
self.assertRaises(ImageHTTPError, image_harvest.link_is_to_image,
'TESTID', url)
url = 'http://getthisimage/notanimage'
httpretty.register_uri(
httpretty.HEAD,
url,
body='',
content_length='0',
content_type='text/plain; charset=utf-8',
connection='close', )
httpretty.register_uri(
httpretty.GET,
url,
body='',
content_length='0',
content_type='text/html; charset=utf-8',
connection='close', )
self.assertFalse(image_harvest.link_is_to_image('TESTID', url))
url = 'http://getthisimage/isanimage'
httpretty.register_uri(
httpretty.HEAD,
url,
body='',
content_length='0',
content_type='image/jpeg; charset=utf-8',
connection='close', )
self.assertTrue(image_harvest.link_is_to_image('TESTID', url))
url_redirect = 'http://gethisimage/redirect'
httpretty.register_uri(
httpretty.HEAD, url, body='', status=301, location=url_redirect)
httpretty.register_uri(
httpretty.HEAD,
url_redirect,
body='',
content_length='0',
content_type='image/jpeg; charset=utf-8',
connection='close', )
self.assertTrue(image_harvest.link_is_to_image('TESTID', url))
httpretty.register_uri(
httpretty.HEAD,
url,
body='',
content_length='0',
content_type='text/html; charset=utf-8',
connection='close', )
httpretty.register_uri(
httpretty.GET,
url,
body='',
content_length='0',
content_type='image/jpeg; charset=utf-8',
connection='close', )
self.assertTrue(image_harvest.link_is_to_image('TESTID', url))
@patch('couchdb.Server')
@patch(
'md5s3stash.md5s3stash',
autospec=True,
return_value=StashReport('test url', 'md5 test value', 's3 url object',
'mime_type', 'dimensions'))
@httpretty.activate
def test_ignore_content_type(self, mock_stash, mock_couch):
'''Test that content type check is not called if --ignore_content_type parameter given'''
url = 'http://getthisimage/image'
doc = {'_id': 'IGNORE_CONTENT', 'isShownBy': url}
httpretty.register_uri(
httpretty.HEAD,
url,
body='',
content_length='0',
content_type='text/plain; charset=utf-8',
connection='close', )
httpretty.register_uri(
httpretty.GET,
url,
body='',
content_length='0',
content_type='text/html; charset=utf-8',
connection='close', )
image_harvester = image_harvest.ImageHarvester(
url_cache={}, hash_cache={}, bucket_bases=['region:x'], ignore_content_type=True)
r = StashReport('test url', 'md5 test value', 's3 url object',
'mime_type', 'dimensions')
ret = image_harvester.stash_image(doc)
self.assertEqual(ret, [r])
@patch('couchdb.Server')
@patch(
'md5s3stash.md5s3stash',
autospec=True,
return_value=StashReport('test url', 'md5 test value', 's3 url object',
'mime_type', 'dimensions'))
@httpretty.activate
def test_check_content_type(self, mock_stash, mock_couch):
'''Test that the check for content type correctly aborts if the
type is not a image
'''
url = 'http://getthisimage/notanimage'
doc = {'_id': 'TESTID', 'isShownBy': url}
httpretty.register_uri(
httpretty.HEAD,
url,
body='',
content_length='0',
content_type='text/plain; charset=utf-8',
connection='close', )
httpretty.register_uri(
httpretty.GET,
url,
body='',
content_length='0',
content_type='text/html; charset=utf-8',
connection='close', )
image_harvester = image_harvest.ImageHarvester(
url_cache={}, hash_cache={}, bucket_bases=['region:x'])
self.assertRaises(FailsImageTest, image_harvester.stash_image, doc)
httpretty.register_uri(
httpretty.HEAD,
url,
body='',
content_length='0',
content_type='image/plain; charset=utf-8',
connection='close', )
r = StashReport('test url', 'md5 test value', 's3 url object',
'mime_type', 'dimensions')
ret = image_harvester.stash_image(doc)
self.assertEqual(ret, [r])
@patch('boto.s3.connect_to_region', return_value='S3Conn to a region')
@patch('harvester.image_harvest.Redis', autospec=True)
@patch('couchdb.Server')
@patch(
'md5s3stash.md5s3stash',
autospec=True,
return_value=StashReport('test url', 'md5 test value', 's3 url object',
'mime_type', 'dimensions'))
@httpretty.activate
def test_harvest_image_for_doc(self, mock_stash, mock_couch, mock_redis,
mock_s3_connect):
image_harvester = image_harvest.ImageHarvester(
url_cache={},
hash_cache={},
bucket_bases=['region:x'],
harvested_object_cache={'xxx': 'yyy'})
doc = {
'_id': 'TESTID',
'object': 'hasobject',
'object_dimensions': 'x:y'
}
self.assertRaises(HasObject, image_harvester.harvest_image_for_doc,
doc)
doc = {'_id': 'xxx', }
self.assertRaises(RestoreFromObjectCache,
image_harvester.harvest_image_for_doc, doc)
doc = {'_id': 'TESTID', }
self.assertRaises(RestoreFromObjectCache,
image_harvester.harvest_image_for_doc, doc)
doc = {'_id': 'XXX-TESTID', }
self.assertRaises(IsShownByError,
image_harvester.harvest_image_for_doc, doc)
doc = {'_id': 'XXX-TESTID', 'isShownBy': 'bogus'}
self.assertRaises(FailsImageTest,
image_harvester.harvest_image_for_doc, doc)
url = 'http://example.edu/test.jpg'
doc = {'_id': 'XXX-TESTID', 'isShownBy': url}
httpretty.register_uri(
httpretty.HEAD,
url,
body='',
content_length='0',
content_type='image/plain; charset=utf-8',
connection='close', )
report = image_harvester.harvest_image_for_doc(doc)
print '++++++++ REPORT:{}'.format(report)
def test_url_missing_schema(self):
'''Test when the url is malformed and doesn't have a proper http
schema. The LAPL photo feed has URLs like this:
http:/jpg1.lapl.org/pics47/00043006.jpg
The code was choking complaining about a "MissingSchema"
exception.
'''
pass
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,090 | ucldc/harvester | refs/heads/master | /scripts/queue_deep_harvest_single_object_jobs.py | #! /bin/env python
# -*- coding: utf-8 -*-
import sys
import logbook
from rq import Queue
from redis import Redis
from harvester.config import parse_env
from harvester.collection_registry_client import Collection
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
JOB_TIMEOUT = 345600 # 96 hrs
def queue_deep_harvest_path(redis_host,
redis_port,
redis_password,
redis_timeout,
rq_queue,
path,
replace=False,
timeout=JOB_TIMEOUT):
'''Queue job onto RQ queue'''
rQ = Queue(
rq_queue,
connection=Redis(
host=redis_host,
port=redis_port,
password=redis_password,
socket_connect_timeout=redis_timeout))
job = rQ.enqueue_call(
func='s3stash.stash_single_rqworker.stash_file',
args=(path, ),
kwargs={'replace': replace},
timeout=timeout)
job = rQ.enqueue_call(
func='s3stash.stash_single_rqworker.stash_image',
args=(path,),
kwargs={'replace': replace},
timeout=timeout)
job = rQ.enqueue_call(
func='s3stash.stash_single_rqworker.stash_media_json',
args=(path,),
kwargs={'replace': replace},
timeout=timeout)
job = rQ.enqueue_call(
func='s3stash.stash_single_rqworker.stash_thumb',
args=(path,),
kwargs={'replace': replace},
timeout=timeout)
def main(collection_ids, rq_queue='dh-q', config=None, pynuxrc=None,
replace=False, timeout=JOB_TIMEOUT, log_handler=None):
''' Queue a deep harvest of a nuxeo object on a worker'''
if not log_handler:
log_handler = logbook.StderrHandler(level='DEBUG')
log_handler.push_application()
log = logbook.Logger('QDH')
for cid in [x for x in collection_ids.split(';')]:
url_api = ''.join(('https://registry.cdlib.org/api/v1/collection/',
cid, '/'))
coll = Collection(url_api)
dh = DeepHarvestNuxeo(coll.harvest_extra_data, '', pynuxrc=pynuxrc)
for obj in dh.fetch_objects():
log.info('Queueing TOPLEVEL {} :-: {}'.format(
obj['uid'],
obj['path']))
# deep harvest top level object
queue_deep_harvest_path(
config['redis_host'],
config['redis_port'],
config['redis_password'],
config['redis_connect_timeout'],
rq_queue=rq_queue,
path=obj['path'],
replace=replace,
timeout=timeout)
# deep harvest component sub-objects
for c in dh.fetch_components(obj):
log.info('Queueing {} :-: {}'.format(
c['uid'],
c['path']))
queue_deep_harvest_path(
config['redis_host'],
config['redis_port'],
config['redis_password'],
config['redis_connect_timeout'],
rq_queue=rq_queue,
path=c['path'],
replace=replace,
timeout=timeout)
log_handler.pop_application()
def def_args():
import argparse
parser = argparse.ArgumentParser(
description='Queue a Nuxeo deep harvesting job for a single object')
parser.add_argument('--rq_queue', type=str, help='RQ Queue to put job in',
default='dh-q')
parser.add_argument(
'collection_ids', type=str, help='Collection ids, ";" delimited')
#parser.add_argument(
# 'path', type=str, help='Nuxeo path to root folder')
parser.add_argument('--job_timeout', type=int, default=JOB_TIMEOUT,
help='Timeout for the RQ job')
parser.add_argument(
'--pynuxrc', default='~/.pynuxrc', help='rc file for use by pynux')
parser.add_argument(
'--replace',
action='store_true',
help='replace files on s3 if they already exist')
return parser
if __name__=='__main__':
parser = def_args()
args = parser.parse_args()
config = parse_env(None)
main(args.collection_ids, rq_queue=args.rq_queue, config=config,
replace=args.replace, timeout=args.job_timeout,
pynuxrc=args.pynuxrc)
# Copyright © 2017, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,091 | ucldc/harvester | refs/heads/master | /scripts/queue_image_harvest_by_doc.py | #! /bin/env python
import sys
import os
from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
from harvester.image_harvest import harvest_image_for_doc
EMAIL_RETURN_ADDRESS = os.environ.get('EMAIL_RETURN_ADDRESS',
'example@example.com')
# csv delim email addresses
EMAIL_SYS_ADMIN = os.environ.get('EMAIL_SYS_ADMINS', None)
IMAGE_HARVEST_TIMEOUT = 144000
def def_args():
import argparse
parser = argparse.ArgumentParser(description='Harvest a collection')
parser.add_argument('user_email', type=str, help='user email')
parser.add_argument('rq_queue', type=str, help='RQ Queue to put job in')
parser.add_argument('cid', type=str,
help='Collection ID')
parser.add_argument('--object_auth', nargs='?',
help='HTTP Auth needed to download images - username:password')
parser.add_argument('--url_couchdb', nargs='?',
help='Override url to couchdb')
parser.add_argument('--timeout', nargs='?',
help='set image harvest timeout in sec (14400 - 4hrs default)')
parser.add_argument('--get_if_object', action='store_true',
default=False,
help='Should image harvester not get image if the object field exists for the doc (default: False, always get)')
return parser
def main(user_email, cid, url_couchdb=None):
enq = CouchDBJobEnqueue()
timeout = 10000
enq.queue_collection(cid,
timeout,
harvest_image_for_doc,
url_couchdb=url_couchdb,
)
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args(sys.argv[1:])
if not args.user_email or not args.cid:
parser.print_help()
sys.exit(27)
kwargs = {}
if args.object_auth:
kwargs['object_auth'] = args.object_auth
if args.timeout:
kwargs['harvest_timeout'] = int(args.timeout)
if args.get_if_object:
kwargs['get_if_object'] = args.get_if_object
main(args.user_email,
args.cid,
**kwargs)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,092 | ucldc/harvester | refs/heads/master | /scripts/queue_image_harvest_for_doc_ids.py | # -*- coding: utf-8 -*-
#! /bin/env python
import sys
import os
from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
from harvester.image_harvest import harvest_image_for_doc
EMAIL_RETURN_ADDRESS = os.environ.get('EMAIL_RETURN_ADDRESS',
'example@example.com')
# csv delim email addresses
EMAIL_SYS_ADMIN = os.environ.get('EMAIL_SYS_ADMINS', None)
IMAGE_HARVEST_TIMEOUT = 144000
def def_args():
import argparse
parser = argparse.ArgumentParser(description='Harvest a collection')
parser.add_argument('user_email', type=str, help='user email')
parser.add_argument('rq_queue', type=str, help='RQ Queue to put job in')
parser.add_argument('--object_auth', nargs='?',
help='HTTP Auth needed to download images - username:password')
parser.add_argument('--url_couchdb', nargs='?',
help='Override url to couchdb')
parser.add_argument('--timeout', nargs='?',
help='set image harvest timeout in sec (14400 - 4hrs default)')
parser.add_argument('doc_ids', type=str,
help='Comma separated CouchDB document ids')
return parser
def main(doc_ids, **kwargs):
enq = CouchDBJobEnqueue(rq_queue=kwargs['rq_queue'])
timeout = 10000
if 'rq_queue' in kwargs:
del kwargs['rq_queue']
if 'timeout' in kwargs:
if type(kwargs['timeout']) == int:
timeout = kwargs['timeout']
del kwargs['timeout']
if 'object_auth' in kwargs:
kwargs['object_auth'] = (kwargs['object_auth'].split(':')[0],
kwargs['object_auth'].split(':')[1])
enq.queue_list_of_ids(doc_ids,
timeout,
harvest_image_for_doc,
force=True,
**kwargs
)
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args(sys.argv[1:])
if not args.rq_queue or not args.doc_ids:
parser.print_help()
sys.exit(27)
id_list = [s for s in args.doc_ids.split(',')]
kwargs = vars(args)
del kwargs['doc_ids']
main(id_list,
**kwargs)
# Copyright © 2017, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,093 | ucldc/harvester | refs/heads/master | /harvester/fetcher/flickr_fetcher.py | # -*- coding: utf-8 -*-
import os
import urllib
import re
from xml.etree import ElementTree as ET
from .fetcher import Fetcher
class Flickr_Fetcher(Fetcher):
'''A fetcher for the Flickr API.
NOTE: This fetcher DOES NOT use the url_harvest. The extra_data should
be a Flickr user id, such as 49487266@N07, or photoset id, such as 72157701798943531
User ID: takes a user id and grabs the flickr.people.getPublicPhotos
to get the list of all photos.
photoset ID: takes a photoset id and grabs the flickr.photosets.getPhotos
to get the list of all photos.
It then proceeds to use flickr.photos.getInfo to get metadata for the
photos
'''
url_get_user_photos_template = 'https://api.flickr.com/services/rest/' \
'?api_key={api_key}&user_id={user_id}&per_page={per_page}&method=' \
'flickr.people.getPublicPhotos&page={page}'
url_get_photoset_template = 'https://api.flickr.com/services/rest/' \
'?api_key={api_key}&photoset_id={user_id}&per_page={per_page}&method=' \
'flickr.photosets.getPhotos&page={page}'
url_get_photo_info_template = 'https://api.flickr.com/services/rest/' \
'?api_key={api_key}&method=flickr.photos.getInfo&photo_id={photo_id}'
def __init__(self,
url_harvest,
extra_data,
page_size=500,
page_range=None,
**kwargs):
self.url_base = url_harvest
self.user_id = extra_data
self.api_key = os.environ.get('FLICKR_API_KEY', 'boguskey')
self.page_size = page_size
self.page_current = 1
self.doc_current = 0
self.docs_fetched = 0
xml = urllib.urlopen(self.url_current).read()
total = re.search('total="(?P<total>\d+)"', xml)
self.docs_total = int(total.group('total'))
page_total = re.search('pages="(?P<page_total>\d+)"', xml)
self.page_total = int(page_total.group('page_total'))
if page_range:
start, end = page_range.split(',')
self.page_start = int(start)
self.page_end = int(end)
self.page_current = self.page_start
if self.page_end >= self.page_total:
self.page_end = self.page_total
docs_last_page = self.docs_total - \
((self.page_total - 1) * self.page_size)
self.docs_total = (self.page_end - self.page_start) * \
self.page_size + docs_last_page
else:
self.docs_total = (self.page_end - self.page_start + 1) * \
self.page_size
@property
def url_current(self):
'''If @N found in extra_data, it's a user ID. If not, it's a photoset'''
if "@N" in self.user_id:
return self.url_get_user_photos_template.format(
api_key=self.api_key,
user_id=self.user_id,
per_page=self.page_size,
page=self.page_current)
else:
return self.url_get_photoset_template.format(
api_key=self.api_key,
user_id=self.user_id,
per_page=self.page_size,
page=self.page_current)
def parse_tags_for_photo_info(self, info_tree):
'''Parse the sub tags of a photo info objects and add to the
photo dictionary.
see: https://www.flickr.com/services/api/flickr.photos.getInfo.html
for a description of the photo info xml
'''
tag_info = {}
for t in info_tree:
# need to handle tags, notes and urls as lists
if t.tag in ('tags', 'notes', 'urls'):
sub_list = []
for subt in t.getchildren():
sub_obj = subt.attrib
sub_obj['text'] = subt.text
sub_list.append(sub_obj)
tag_info[t.tag] = sub_list # should i have empty lists?
else:
tobj = t.attrib
tobj['text'] = t.text
tag_info[t.tag] = tobj
return tag_info
def next(self):
if self.doc_current >= self.docs_total:
if self.docs_fetched != self.docs_total:
raise ValueError(
"Number of documents fetched ({0}) doesn't match \
total reported by server ({1})"
.format(self.docs_fetched, self.docs_total))
else:
raise StopIteration
if hasattr(self, 'page_end') and self.page_current > self.page_end:
raise StopIteration
# for the given page of public photos results,
# for each <photo> tag, create an object with id, server & farm saved
# then get the info for the photo and add to object
# return the full list of objects to the harvest controller
tree = ET.fromstring(urllib.urlopen(self.url_current).read())
photo_list = tree.findall('.//photo')
objset = []
for photo in photo_list:
photo_obj = photo.attrib
url_photo_info = self.url_get_photo_info_template.format(
api_key=self.api_key, photo_id=photo_obj['id'])
ptree = ET.fromstring(urllib.urlopen(url_photo_info).read())
photo_info = ptree.find('.//photo')
photo_obj.update(photo_info.attrib)
photo_obj.update(
self.parse_tags_for_photo_info(photo_info.getchildren()))
self.docs_fetched += 1
objset.append(photo_obj)
self.page_current += 1
self.doc_current += len(objset)
return objset
# Copyright © 2017, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,094 | ucldc/harvester | refs/heads/master | /scripts/delete_couchdb_collection.py | #! /bin/env python
import sys
import argparse
from harvester.couchdb_sync_db_by_collection import delete_collection
def confirm_deletion(cid):
prompt = "Are you sure you want to delete all couchdb " + \
"documents for %s? yes to confirm\n" % cid
while True:
ans = raw_input(prompt).lower()
if ans == "yes":
return True
else:
return False
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Delete all documents in given collection')
parser.add_argument('collection_id', help='Registry id for the collection')
parser.add_argument(
'--yes',
action='store_true',
help="Don't prompt for deletion, just do it")
args = parser.parse_args(sys.argv[1:])
if args.yes or confirm_deletion(args.collection_id):
print 'DELETING COLLECTION {}'.format(args.collection_id)
num, deleted_ids = delete_collection(args.collection_id)
print "DELETED {} DOCS".format(num)
else:
print "Exiting without deleting"
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,095 | ucldc/harvester | refs/heads/master | /scripts/report_non_unicode_data.py | '''run grabbing of new collection and updating in couch docs locally.
'''
import sys
import argparse
import Queue
import threading
import requests
import json
url_api_base = 'https://registry.cdlib.org/api/v1/collection/'
from harvester.post_processing.couchdb_runner import CouchDBWorker
from harvester.fetcher import HarvestController
from harvester.collection_registry_client import Collection
def non_unicode_data(data, doc_id, key):
#if "kt4m3nc6r1" in doc_id:
# print "IN BASE FN for check {} {}".format(doc_id, key)
try:
d = unicode(data)#.decode('utf8', encoding='utf8')
except UnicodeEncodeError, e:
print "NON UNICODE DATA: DOC:{} key:{} value:{} {}".format(doc_id, key,
data.encode('utf8'), e)
def report_non_unicode_data(obj, doc_id=None, key=''):
'''Recurse the objument and report on any non-unicode data
'''
#print "IN REPORT id:{} key:{}".format( doc_id, key)
if not doc_id:
doc_id = obj['_id']
#jif "kt4m3nc6r1" in doc_id:
# h print "IN REPORT id:{} key:{}".format( doc_id, key)
if isinstance(obj, basestring):
# if "kt4m3nc6r1" in doc_id:
# print "Check key:{}".format(key)
return non_unicode_data(obj, doc_id, key)
elif isinstance(obj, list):
# if "kt4m3nc6r1" in doc_id:
# print "Check key:{}".format(key)
for value in obj:
report_non_unicode_data(value, doc_id=doc_id, key=key)
elif isinstance(obj, dict):
# if "kt4m3nc6r1" in doc_id:
# print "Check key:{}".format(key)
for subkey, value in obj.items():
fullkey = '/'.join((key, subkey))
report_non_unicode_data(value, doc_id=doc_id, key=fullkey)
return obj
def get_id_on_queue_and_run(queue):
cdbworker = CouchDBWorker()
cid = queue.get_nowait()
while cid:
print "STARTING COLLECTION: {}".format(cid)
cdbworker.run_by_collection(cid, report_non_unicode_data)
print "FINISHED COLLECTION: {}".format(cid)
cid = queue.get_nowait()
if __name__=='__main__':
queue = Queue.Queue()
num_threads = 2
for l in open('collections-check-unicode.list'):
cid = l.strip()
#fill q, not parallel yet
queue.put(cid)
threads = [threading.Thread(target=get_id_on_queue_and_run,
args=(queue,)) for i in range(num_threads)]
print "THREADS:{} starting next".format(threads)
for t in threads:
t.start()
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,096 | ucldc/harvester | refs/heads/master | /scripts/image_harvest_opl_preservica.py | # -*- coding: utf-8 -*-
import harvester.image_harvest
harvester.image_harvest.link_is_to_image = lambda x,y: True
from harvester.image_harvest import ImageHarvester
from harvester.image_harvest import COUCHDB_VIEW, BUCKET_BASES
class ImageHarvesterOPLPreservica(ImageHarvester):
def __init__(self, cdb=None,
url_couchdb=None,
couchdb_name=None,
couch_view=COUCHDB_VIEW,
bucket_bases=BUCKET_BASES,
object_auth=None,
get_if_object=False,
url_cache=None,
hash_cache=None,
harvested_object_cache=None,
auth_token=None):
super(ImageHarvesterOPLPreservica, self).__init__(cdb=cdb,
url_couchdb=url_couchdb,
couchdb_name=couchdb_name,
couch_view=couch_view,
bucket_bases=bucket_bases,
object_auth=object_auth,
get_if_object=get_if_object,
url_cache=url_cache,
hash_cache=hash_cache,
harvested_object_cache=harvested_object_cache)
self.auth_token = auth_token
def stash_image(self, doc):
if doc['sourceResource']['type'] == 'text':
return None
url_image_base = doc.get('isShownBy', None)
if url_image_base:
doc['isShownBy'] = url_image_base +'&token={}'.format(self.auth_token)
else:
return None
report = super(ImageHarvesterOPLPreservica, self).stash_image(doc)
doc['isShownBy'] = url_image_base
return report
def main(collection_key=None,
url_couchdb=None,
object_auth=None,
get_if_object=False,
auth_token=None):
ImageHarvesterOPLPreservica(url_couchdb=url_couchdb,
object_auth=object_auth,
get_if_object=get_if_object,
auth_token=auth_token).by_collection(collection_key)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description='Run the image harvesting on a collection')
parser.add_argument('collection_key', help='Registry collection id')
parser.add_argument('auth_token', help='Authentication token from preservica')
parser.add_argument('--object_auth', nargs='?',
help='HTTP Auth needed to download images - username:password')
parser.add_argument('--url_couchdb', nargs='?',
help='Override url to couchdb')
parser.add_argument('--get_if_object', action='store_true',
default=False,
help='Should image harvester not get image if the object field exists for the doc (default: False, always get)')
args = parser.parse_args()
print(args)
object_auth=None
if args.object_auth:
object_auth = (args.object_auth.split(':')[0],
args.object_auth.split(':')[1])
main(args.collection_key,
object_auth=object_auth,
url_couchdb=args.url_couchdb,
get_if_object=args.get_if_object,
auth_token=args.auth_token)
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,097 | ucldc/harvester | refs/heads/master | /test/test_nuxeo_fetcher.py | # -*- coding: utf-8 -*-
import os
from unittest import TestCase
import pickle
import json
import re
import shutil
from mock import patch
from mypretty import httpretty
# import httpretty
import pynux.utils
from harvester.collection_registry_client import Collection
from test.utils import DIR_FIXTURES
from test.utils import ConfigFileOverrideMixin, LogOverrideMixin
import harvester.fetcher as fetcher
class Bunch(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def deepharvest_mocker(mock_deepharvest):
''' mock deepharvest class '''
dh_instance = mock_deepharvest.return_value
with open(DIR_FIXTURES + '/nuxeo_doc_pickled', 'r') as f:
dh_instance.fetch_objects.return_value = pickle.load(f)
dh_instance.nx = Bunch(conf={'api': 'testapi'})
class NuxeoFetcherTestCase(LogOverrideMixin, TestCase):
'''Test Nuxeo fetching'''
# put httppretty here, have sample outputs.
@httpretty.activate
@patch('boto.connect_s3', autospec=True)
@patch('harvester.fetcher.nuxeo_fetcher.DeepHarvestNuxeo', autospec=True)
def testInit(self, mock_deepharvest, mock_boto):
'''Basic tdd start'''
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/path/path-to-asset/here/@children',
body=open(DIR_FIXTURES + '/nuxeo_folder.json').read())
deepharvest_mocker(mock_deepharvest)
h = fetcher.NuxeoFetcher('https://example.edu/api/v1/',
'path-to-asset/here')
mock_deepharvest.assert_called_with(
'path-to-asset/here',
'',
conf_pynux={'api': 'https://example.edu/api/v1/'})
self.assertTrue(hasattr(h, '_url')) # assert in called next repeatedly
self.assertEqual(h.url, 'https://example.edu/api/v1/')
self.assertTrue(hasattr(h, '_nx'))
self.assertIsInstance(h._nx, pynux.utils.Nuxeo)
self.assertTrue(hasattr(h, '_children'))
self.assertTrue(hasattr(h, 'next'))
self.assertTrue(hasattr(h, '_structmap_bucket'))
@patch('boto.connect_s3', autospec=True)
@patch('harvester.fetcher.nuxeo_fetcher.DeepHarvestNuxeo', autospec=True)
def test_get_structmap_text(self, mock_deepharvest, mock_boto):
'''Mock test s3 structmap_text getting'''
media_json = open(DIR_FIXTURES + '/nuxeo_media_structmap.json').read()
deepharvest_mocker(mock_deepharvest)
mock_boto.return_value.get_bucket.return_value.\
get_key.return_value.\
get_contents_as_string.return_value = media_json
h = fetcher.NuxeoFetcher('https://example.edu/api/v1/',
'path-to-asset/here')
mock_deepharvest.assert_called_with(
'path-to-asset/here',
'',
conf_pynux={'api': 'https://example.edu/api/v1/'})
structmap_text = h._get_structmap_text(
's3://static.ucldc.cdlib.org/media_json/'
'81249b9c-5a87-43af-877c-fb161325b1a0-media.json')
mock_boto.assert_called_with()
mock_boto().get_bucket.assert_called_with('static.ucldc.cdlib.org')
mock_boto().get_bucket().get_key.assert_called_with(
'/media_json/81249b9c-5a87-43af-877c-fb161325b1a0-media.json')
self.assertEqual(structmap_text, "Angela Davis socializing with "
"students at UC Irvine AS-061_A69-013_001.tif "
"AS-061_A69-013_002.tif AS-061_A69-013_003.tif "
"AS-061_A69-013_004.tif AS-061_A69-013_005.tif "
"AS-061_A69-013_006.tif AS-061_A69-013_007.tif")
@httpretty.activate
@patch('boto.connect_s3', autospec=True)
@patch('harvester.fetcher.nuxeo_fetcher.DeepHarvestNuxeo', autospec=True)
def testFetch(self, mock_deepharvest, mock_boto):
'''Test the httpretty mocked fetching of documents'''
media_json = open(DIR_FIXTURES + '/nuxeo_media_structmap.json').read()
deepharvest_mocker(mock_deepharvest)
mock_boto.return_value.get_bucket.return_value.\
get_key.return_value.\
get_contents_as_string.return_value = media_json
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/path/path-to-asset/here/@children',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/nuxeo_folder.json').read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/nuxeo_folder-1.json').read(),
status=200),
])
httpretty.register_uri(
httpretty.GET,
re.compile('https://example.edu/api/v1/id/.*'),
body=open(DIR_FIXTURES + '/nuxeo_doc.json').read())
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/path/asset-library/UCI/Cochems'
'/MS-R016_1092.tif/@children?currentPageIndex=0',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/nuxeo_no_children.json').read(),
status=200),
])
h = fetcher.NuxeoFetcher('https://example.edu/api/v1',
'path-to-asset/here')
mock_deepharvest.assert_called_with(
'path-to-asset/here',
'',
conf_pynux={'api': 'https://example.edu/api/v1'})
docs = []
for d in h:
docs.append(d)
self.assertEqual(3, len(docs))
self.assertIn('picture:views', docs[0]['properties'])
self.assertIn('dc:subjects', docs[0]['properties'])
self.assertIn('structmap_url', docs[0])
self.assertIn('structmap_text', docs[0])
self.assertEqual(docs[0]['structmap_text'],
"Angela Davis socializing with students at UC Irvine "
"AS-061_A69-013_001.tif AS-061_A69-013_002.tif "
"AS-061_A69-013_003.tif AS-061_A69-013_004.tif "
"AS-061_A69-013_005.tif AS-061_A69-013_006.tif "
"AS-061_A69-013_007.tif")
self.assertEqual(
docs[0]['isShownBy'],
'https://nuxeo.cdlib.org/Nuxeo/nxpicsfile/default/'
'40677ed1-f7c2-476f-886d-bf79c3fec8c4/Medium:content/')
@httpretty.activate
@patch('boto.connect_s3', autospec=True)
@patch('harvester.fetcher.nuxeo_fetcher.DeepHarvestNuxeo', autospec=True)
def testFetch_missing_media_json(self, mock_deepharvest, mock_boto):
'''Test the httpretty mocked fetching of documents'''
deepharvest_mocker(mock_deepharvest)
mock_boto.return_value.get_bucket.return_value.\
get_key.return_value = None
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/path/path-to-asset/here/@children',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/nuxeo_folder.json').read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/nuxeo_folder-1.json').read(),
status=200),
])
httpretty.register_uri(
httpretty.GET,
re.compile('https://example.edu/api/v1/id/.*'),
body=open(DIR_FIXTURES + '/nuxeo_doc.json').read())
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/path/asset-library/UCI/Cochems/'
'MS-R016_1092.tif/@children?currentPageIndex=0',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/nuxeo_no_children.json').read(),
status=200),
])
h = fetcher.NuxeoFetcher('https://example.edu/api/v1',
'path-to-asset/here')
mock_deepharvest.assert_called_with(
'path-to-asset/here',
'',
conf_pynux={'api': 'https://example.edu/api/v1'})
docs = []
for d in h:
docs.append(d)
self.assertEqual(docs[0]['structmap_text'], '')
self.assertEqual(docs[1]['structmap_text'], '')
self.assertEqual(docs[2]['structmap_text'], '')
@httpretty.activate
@patch('boto.connect_s3', autospec=True)
@patch('harvester.fetcher.nuxeo_fetcher.DeepHarvestNuxeo', autospec=True)
def test_get_isShownBy_component_image(self, mock_deepharvest, mock_boto):
''' test getting correct isShownBy value for Nuxeo doc
with no image at parent level, but an image at the component level
'''
deepharvest_mocker(mock_deepharvest)
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/path/@search?query='
'SELECT+%2A+FROM+Document+WHERE+ecm%3AparentId+%3D+'
'%27d400bb29-98d4-429c-a0b8-119acdb92006%27+ORDER+BY+'
'ecm%3Apos¤tPageIndex=0&pageSize=100',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/nuxeo_image_components.json')
.read(),
status=200),
])
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/id/'
'e8af2d74-0c8b-4d18-b86c-4067b9e16159',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES +
'/nuxeo_first_image_component.json').read(),
status=200),
])
h = fetcher.NuxeoFetcher('https://example.edu/api/v1',
'path-to-asset/here')
nuxeo_metadata = open(DIR_FIXTURES +
'/nuxeo_doc_imageless_parent.json').read()
nuxeo_metadata = json.loads(nuxeo_metadata)
isShownBy = h._get_isShownBy(nuxeo_metadata)
self.assertEqual(
isShownBy, 'https://nuxeo.cdlib.org/Nuxeo/nxpicsfile/default/'
'e8af2d74-0c8b-4d18-b86c-4067b9e16159/Medium:content/')
@httpretty.activate
@patch('boto.connect_s3', autospec=True)
@patch('harvester.fetcher.nuxeo_fetcher.DeepHarvestNuxeo', autospec=True)
def test_get_isShownBy_pdf(self, mock_deepharvest, mock_boto):
''' test getting correct isShownBy value for Nuxeo doc
with no images and PDF at parent level
'''
deepharvest_mocker(mock_deepharvest)
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/path/@search?query=SELECT+%2A+FROM+'
'Document+WHERE+ecm%3AparentId+%3D+'
'%2700d55837-01b6-4211-80d8-b966a15c257e%27+ORDER+BY+'
'ecm%3Apos¤tPageIndex=0&pageSize=100',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/nuxeo_no_children.json').read(),
status=200),
])
h = fetcher.NuxeoFetcher('https://example.edu/api/v1',
'path-to-asset/here')
nuxeo_metadata = open(DIR_FIXTURES +
'/nuxeo_doc_pdf_parent.json').read()
nuxeo_metadata = json.loads(nuxeo_metadata)
isShownBy = h._get_isShownBy(nuxeo_metadata)
self.assertEqual(
isShownBy, 'https://s3.amazonaws.com/static.ucldc.cdlib.org/'
'ucldc-nuxeo-thumb-media/00d55837-01b6-4211-80d8-b966a15c257e')
@httpretty.activate
@patch('boto.connect_s3', autospec=True)
@patch('harvester.fetcher.nuxeo_fetcher.DeepHarvestNuxeo', autospec=True)
def test_get_isShownBy_video(self, mock_deepharvest, mock_boto):
''' test getting correct isShownBy value for Nuxeo video object
'''
deepharvest_mocker(mock_deepharvest)
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/path/@search?query=SELECT+%2A+FROM+'
'Document+WHERE+ecm%3AparentId+%3D+'
'%274c80e254-6def-4230-9f28-bc48878568d4%27+'
'AND+ecm%3AisTrashed+%3D+0+ORDER+BY+'
'ecm%3Apos¤tPageIndex=0&pageSize=100',
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/nuxeo_no_children.json').read(),
status=200),
])
h = fetcher.NuxeoFetcher('https://example.edu/api/v1',
'path-to-asset/here')
nuxeo_metadata = open(DIR_FIXTURES + '/nuxeo_doc_video.json').read()
nuxeo_metadata = json.loads(nuxeo_metadata)
isShownBy = h._get_isShownBy(nuxeo_metadata)
self.assertEqual(
isShownBy, 'https://s3.amazonaws.com/static.ucldc.cdlib.org/'
'ucldc-nuxeo-thumb-media/4c80e254-6def-4230-9f28-bc48878568d4')
class UCLDCNuxeoFetcherTestCase(LogOverrideMixin, TestCase):
'''Test that the UCLDC Nuxeo Fetcher errors if necessary
Nuxeo document schema header property not set.
'''
@httpretty.activate
@patch('harvester.fetcher.nuxeo_fetcher.DeepHarvestNuxeo', autospec=True)
def testNuxeoPropHeader(self, mock_deepharvest):
'''Test that the Nuxeo document property header has necessary
settings. This will test the base UCLDC schemas
'''
deepharvest_mocker(mock_deepharvest)
httpretty.register_uri(
httpretty.GET,
'https://example.edu/api/v1/path/path-to-asset/here/@children',
body=open(DIR_FIXTURES + '/nuxeo_folder.json').read())
# can test adding a prop, but what if prop needed not there.
# need to remove ~/.pynuxrc
self.assertRaises(
AssertionError,
fetcher.UCLDCNuxeoFetcher,
'https://example.edu/api/v1/',
'path-to-asset/here',
conf_pynux={'X-NXDocumentProperties': ''})
self.assertRaises(
AssertionError,
fetcher.UCLDCNuxeoFetcher,
'https://example.edu/api/v1/',
'path-to-asset/here',
conf_pynux={'X-NXDocumentProperties': 'dublincore'})
self.assertRaises(
AssertionError,
fetcher.UCLDCNuxeoFetcher,
'https://example.edu/api/v1/',
'path-to-asset/here',
conf_pynux={'X-NXDocumentProperties': 'dublincore,ucldc_schema'})
h = fetcher.UCLDCNuxeoFetcher(
'https://example.edu/api/v1/',
'path-to-asset/here',
conf_pynux={
'X-NXDocumentProperties':
'dublincore,ucldc_schema,picture,file'
})
mock_deepharvest.assert_called_with(
'path-to-asset/here',
'',
conf_pynux={
'X-NXDocumentProperties':
'dublincore,ucldc_schema,picture,file',
'api': 'https://example.edu/api/v1/'
})
self.assertIn('dublincore', h._nx.conf['X-NXDocumentProperties'])
self.assertIn('ucldc_schema', h._nx.conf['X-NXDocumentProperties'])
self.assertIn('picture', h._nx.conf['X-NXDocumentProperties'])
class Harvest_UCLDCNuxeo_ControllerTestCase(ConfigFileOverrideMixin,
LogOverrideMixin, TestCase):
'''Test the function of an Nuxeo harvest controller'''
def setUp(self):
super(Harvest_UCLDCNuxeo_ControllerTestCase, self).setUp()
def tearDown(self):
super(Harvest_UCLDCNuxeo_ControllerTestCase, self).tearDown()
shutil.rmtree(self.controller.dir_save)
@httpretty.activate
@patch('boto3.resource', autospec=True)
@patch('boto.connect_s3', autospec=True)
@patch('harvester.fetcher.nuxeo_fetcher.DeepHarvestNuxeo', autospec=True)
def testNuxeoHarvest(self, mock_deepharvest, mock_boto, mock_boto3):
'''Test the function of the Nuxeo harvest'''
media_json = open(DIR_FIXTURES + '/nuxeo_media_structmap.json').read()
mock_boto.return_value.get_bucket.return_value.\
get_key.return_value.\
get_contents_as_string.return_value = media_json
httpretty.register_uri(
httpretty.GET,
'http://registry.cdlib.org/api/v1/collection/19/',
body=open(DIR_FIXTURES + '/collection_api_test_nuxeo.json').read())
mock_deepharvest.return_value.fetch_objects.return_value = json.load(
open(DIR_FIXTURES + '/nuxeo_object_list.json'))
httpretty.register_uri(
httpretty.GET,
re.compile('https://example.edu/Nuxeo/site/api/v1/id/.*'),
body=open(DIR_FIXTURES + '/nuxeo_doc.json').read())
self.collection = Collection(
'http://registry.cdlib.org/api/v1/collection/19/')
with patch(
'ConfigParser.SafeConfigParser',
autospec=True) as mock_configparser:
config_inst = mock_configparser.return_value
config_inst.get.return_value = 'dublincore,ucldc_schema,picture'
self.setUp_config(self.collection)
self.controller = fetcher.HarvestController(
'email@example.com',
self.collection,
config_file=self.config_file,
profile_path=self.profile_path)
self.assertTrue(hasattr(self.controller, 'harvest'))
num = self.controller.harvest()
self.assertEqual(num, 5)
self.tearDown_config()
# verify one record has collection and such filled in
fname = os.listdir(self.controller.dir_save)[0]
saved_objset = json.load(
open(os.path.join(self.controller.dir_save, fname)))
saved_obj = saved_objset[0]
self.assertEqual(saved_obj['collection'][0]['@id'],
u'http://registry.cdlib.org/api/v1/collection/19/')
self.assertEqual(saved_obj['collection'][0]['name'],
u'Cochems (Edward W.) Photographs')
self.assertEqual(saved_obj['collection'][0]['title'],
u'Cochems (Edward W.) Photographs')
self.assertEqual(saved_obj['collection'][0]['id'], u'19')
self.assertEqual(saved_obj['collection'][0]['dcmi_type'], 'I')
self.assertEqual(saved_obj['collection'][0]['rights_statement'],
'a sample rights statement')
self.assertEqual(saved_obj['collection'][0]['rights_status'], 'PD')
self.assertEqual(saved_obj['state'], 'project')
self.assertEqual(
saved_obj['title'],
'Adeline Cochems having her portrait taken by her father '
'Edward W, Cochems in Santa Ana, California: Photograph')
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,098 | ucldc/harvester | refs/heads/master | /harvester/couchdb_init.py | '''Return a couchdb Server object in a consistent way from the environment or
config file.
Preference the environment, fallback to ingest code akara.ini
'''
import couchdb
import os
import sys
from harvester.config import config
def parse_couchdb_url(url):
'''Return url, username , password for couchdb url'''
def get_couch_server(url=None, username=None, password=None):
'''Returns a couchdb library Server object'''
env = config()
if not url:
url = env['couchdb_url']
if username is None:
username = env.get('couchdb_username', None)
if password is None:
password = env.get('couchdb_password', None)
if username:
schema, uri = url.split("//")
url = "{0}//{1}:{2}@{3}".format(schema, username, password, uri)
py_version = sys.version_info
if py_version.major == 2 and py_version.minor == 7 and py_version.micro > 8:
#disable ssl verification
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
print "URL:{}".format(url)
return couchdb.Server(url)
def get_couchdb(url=None, dbname=None, username=None, password=None):
'''Get a couchdb library Server object
returns a
'''
env = config()
if not dbname:
dbname = env.get('couchdb_dbname', None)
if not dbname:
dbname = 'ucldc'
couchdb_server = get_couch_server(url, username, password)
return couchdb_server[dbname]
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,099 | ucldc/harvester | refs/heads/master | /harvester/collection_registry_client.py | '''Objects to wrap the avram collection api'''
import os
from os.path import expanduser
import json
import ConfigParser
import requests
api_host = os.environ.get('REGISTRY_HOST', 'registry.cdlib.org')
api_path = '/api/v1/'
url_base = os.environ.get('URL_REGISTRY_API', ''.join(('https://', api_host)))
class ResourceIterator(object):
'''An iterator over a registry api resource type'''
def __init__(self, url_base, path, object_type):
'''Assumes offset of 0 on first get'''
self.url_base = url_base
self.object_type = object_type
self._get_next(path)
self.total_returned = 0
def __iter__(self):
return self
def _parse_result(self, json):
'''parse the api json output'''
self.total_count = json['meta']['total_count']
self.limit = json['meta']['limit']
self.offset = json['meta']['offset']
self.page_end = self.offset + self.limit
self.path_previous = json['meta']['previous']
self.path_next = json['meta']['next']
self.objects = json['objects']
self.obj_list_index = -1 # this is current with set of objects
def _get_next(self, url_next):
'''get next result and parse'''
self.url = self.url_base + url_next
resp = requests.get(self.url).json()
self._parse_result(resp)
def next(self):
'''Iterate over objects, get one at a time'''
if self.total_returned > self.total_count:
raise StopIteration
self.obj_list_index += 1
if self.obj_list_index + self.offset >= self.total_count:
raise StopIteration
if self.obj_list_index + self.offset >= self.page_end:
if not self.path_next:
raise StopIteration
self._get_next(self.path_next)
self.total_returned += 1
self.obj_list_index += 1
else:
self.total_returned += 1
# TODO: smarter conversion here
return Collection(url_base=self.url_base, json_obj=self.objects[self.obj_list_index]) \
if self.object_type == 'collection' \
else self.objects[self.obj_list_index]
class Registry(object):
'''A class to obtain tastypie api sets of objects from our registry.
Objects can be a campus, respository or collection'''
def __init__(self, url_base=url_base,
url_api=''.join((url_base, api_path))):
self.url_base = url_base
self.url_api = url_api
resp = requests.get(url_api).json()
self.endpoints = {}
for obj_type, obj in resp.items():
self.endpoints[obj_type] = obj['list_endpoint']
def resource_iter(self, object_type, filter=None):
'''Get an iterator for the resource at the given endpoint.
'''
if object_type not in self.endpoints:
raise ValueError('Unknown type of resource {0}'.format(object_type))
path = self.endpoints[object_type] if not filter \
else self.endpoints[object_type] + '?' + filter
return ResourceIterator(url_base, path, object_type)
class Collection(dict):
'''A representation of the avram collection, as presented by the
tastypie api
'''
def __init__(self, url_api=None, url_base=None, json_obj=None):
if url_base and json_obj:
self.url = url_base + json_obj['resource_uri']
self.update(json_obj)
self.__dict__.update(json_obj)
elif url_api:
self.url = url_api
api_json = requests.get(url_api).json()
self.update(api_json)
self.__dict__.update(api_json)
else:
raise Exception(
'Must supply a url to collection api or json data and api base url')
# use the django id for "provider", maybe url translated eventually
self.id = self.provider = self['resource_uri'].strip('/').rsplit('/', 1)[1]
self._auth = None
def _build_contributor_list(self):
'''Build the dpla style contributor list from the campus and
repositories
This will need review
'''
clist = []
for campus in self.campus:
campus_dict = dict(name=campus['slug'])
campus_dict['@id'] = campus['resource_uri']
clist.append(campus_dict)
for repository in self.repository:
repository_dict = dict(name=repository['slug'])
repository_dict['@id'] = repository['resource_uri']
clist.append(repository_dict)
return clist
@property
def dpla_profile_obj(self):
'''Return a json string appropriate for creating a dpla ingest profile.
First create dictionary that is correct and then serialize'''
if not self.enrichments_item:
raise ValueError("NO ITEM ENRICHMENTS FOR COLLECTION, WILL FAIL!")
profile = {}
profile['name'] = self.provider
profile['contributor'] = self._build_contributor_list()
profile['enrichments_coll'] = ['/compare_with_schema', ]
profile['thresholds'] = {
"added": 100000,
"changed": 100000,
"deleted": 1000
}
profile['enrichments_item'] = [s.strip() for s in
self.enrichments_item.split(',')]
return profile
@property
def dpla_profile(self):
return json.dumps(self.dpla_profile_obj)
@property
def auth(self):
'''Return a username, password tuple suitable for authentication
if the remote objects require auth for access.
This is a bit of a hack, we know that the nuxeo style collections
require Basic auth which is stored in our pynuxrc.
If other types of collections require authentication to dowload
objects, we'll have to come up with a clever way of storing that
info in collection registry.
'''
if not self.harvest_type == 'NUX':
return None
if self._auth:
return self._auth
# return self.auth #ConfigParser doesn't like return trips
# for now just grab auth directly from pynux, could also
# have option for passing in.
config = ConfigParser.SafeConfigParser()
config.readfp(open(os.path.join(expanduser("~"), '.pynuxrc')))
self._auth = (config.get('nuxeo_account', 'user'),
config.get('nuxeo_account', 'password'))
return self._auth
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,100 | ucldc/harvester | refs/heads/master | /harvester/fetcher/oac_fetcher.py | # -*- coding: utf-8 -*-
import urllib
from collections import defaultdict
from xml.etree import ElementTree as ET
import time
import logbook
import requests
from requests.packages.urllib3.exceptions import DecodeError
from .fetcher import Fetcher
CONTENT_SERVER = 'http://content.cdlib.org/'
class BunchDict(dict):
def __init__(self, **kwds):
dict.__init__(self, kwds)
self.__dict__ = self
class OAC_XML_Fetcher(Fetcher):
'''Fetcher for the OAC
The results are returned in 3 groups, image, text and website.
Image and text are the ones we care about.
'''
def __init__(self, url_harvest, extra_data, docsPerPage=100, **kwargs):
super(OAC_XML_Fetcher, self).__init__(url_harvest, extra_data)
self.logger = logbook.Logger('FetcherOACXML')
self.docsPerPage = docsPerPage
self.url = self.url + '&docsPerPage=' + str(self.docsPerPage)
self._url_current = self.url
self.currentDoc = 0
self.currentGroup = ('image', 0)
# this will be used to track counts for the 3 groups
self.groups = dict(
image=BunchDict(), text=BunchDict(), website=BunchDict())
facet_type_tab = self._get_next_result_set()
# set total number of hits across the 3 groups
self.totalDocs = int(facet_type_tab.attrib['totalDocs'])
if self.totalDocs <= 0:
raise ValueError(self.url + ' yields no results')
self.totalGroups = int(facet_type_tab.attrib['totalGroups'])
self._update_groups(facet_type_tab.findall('group'))
# set initial group to image, if there are any
for key, hitgroup in self.groups.items():
hitgroup.end = 0
hitgroup.currentDoc = 1
if self.groups['image'].start != 0:
self.currentGroup = 'image'
elif self.groups['text'].start != 0:
self.currentGroup = 'text'
else:
self.currentGroup = None
def _get_doc_ark(self, docHit):
'''Return the object's ark from the xml etree docHit'''
ids = docHit.find('meta').findall('identifier')
ark = None
for i in ids:
if i.attrib.get('q', None) != 'local':
try:
split = i.text.split('ark:')
except AttributeError:
continue
if len(split) > 1:
ark = ''.join(('ark:', split[1]))
return ark
def _docHits_to_objset(self, docHits):
'''Transform the ElementTree docHits into a python object list
ready to be jsonfied
Any elements with sub-elements (just seem to be the snippets in the
relation field for the findaid ark) the innertext of the element +
subelements becomes the value of the output.
'''
objset = []
for d in docHits:
obj = defaultdict(list)
meta = d.find('meta')
ark = self._get_doc_ark(d)
for t in meta:
if t.tag == 'google_analytics_tracking_code':
continue
data = ''
if t.tag == 'reference-image':
# ref image & thumbnail have data in attribs
# return as dicts
try:
x = int(t.attrib['X'])
except ValueError:
x = 0
try:
y = int(t.attrib['Y'])
except ValueError:
y = 0
src = ''.join((CONTENT_SERVER, t.attrib['src']))
src = src.replace('//', '/').replace('/', '//', 1)
data = {
'X': x,
'Y': y,
'src': src,
}
obj[t.tag].append(data)
elif t.tag == 'thumbnail':
try:
x = int(t.attrib['X'])
except ValueError:
x = 0
try:
y = int(t.attrib['Y'])
except ValueError:
y = 0
src = ''.join((CONTENT_SERVER, '/', ark, '/thumbnail'))
src = src.replace('//', '/').replace('/', '//', 1)
data = {
'X': x,
'Y': y,
'src': src,
}
obj[t.tag] = data
elif len(list(t)) > 0:
# <snippet> tag breaks up text for findaid <relation>
for innertext in t.itertext():
data = ''.join((data, innertext.strip()))
if data:
obj[t.tag].append({'attrib': t.attrib, 'text': data})
else:
if t.text: # don't add blank ones
obj[t.tag].append({'attrib': t.attrib, 'text': t.text})
objset.append(obj)
return objset
def _update_groups(self, group_elements):
'''Update the internal data structure with the count from
the current ElementTree results for the search groups
'''
for g in group_elements:
v = g.attrib['value']
self.groups[v].total = int(g.attrib['totalDocs'])
self.groups[v].start = int(g.attrib['startDoc'])
self.groups[v].end = int(g.attrib['endDoc'])
def _get_next_result_set(self):
'''get the next result set
Return the facet element, only one were interested in'''
n_tries = 0
pause = 5
while True:
try:
resp = urllib.urlopen(self._url_current)
break
except DecodeError as e:
n_tries += 1
if n_tries > 5:
raise e
# backoff
time.sleep(pause)
pause = pause * 2
# resp.encoding = 'utf-8' # thinks it's ISO-8859-1
crossQueryResult = ET.fromstring(resp.read())
# crossQueryResult = ET.fromstring(resp.text.encode('utf-8'))
return crossQueryResult.find('facet')
def next(self):
'''Get the next page of search results
'''
if self.currentDoc >= self.totalDocs:
raise StopIteration
if self.currentGroup == 'image':
if self.groups['image']['end'] == self.groups['image']['total']:
self.currentGroup = 'text'
if self.groups['text']['total'] == 0:
raise StopIteration
self._url_current = ''.join(
(self.url, '&startDoc=',
str(self.groups[self.currentGroup]['currentDoc']), '&group=',
self.currentGroup))
facet_type_tab = self._get_next_result_set()
self._update_groups(facet_type_tab.findall('group'))
objset = self._docHits_to_objset(
facet_type_tab.findall('./group/docHit'))
self.currentDoc += len(objset)
self.groups[self.currentGroup]['currentDoc'] += len(objset)
return objset
class OAC_JSON_Fetcher(Fetcher):
'''Fetcher for oac, using the JSON objset interface
This is being deprecated in favor of the xml interface'''
def __init__(self, url_harvest, extra_data):
super(OAC_JSON_Fetcher, self).__init__(url_harvest, extra_data)
self.oac_findaid_ark = self._parse_oac_findaid_ark(self.url)
self.headers = {'content-type': 'application/json'}
self.objset_last = False
self.resp = requests.get(self.url, headers=self.headers)
api_resp = self.resp.json()
# for key in api_resp.keys():
# self.__dict__[key] = api_resp[key]
self.objset_total = api_resp[u'objset_total']
self.objset_start = api_resp['objset_start']
self.objset_end = api_resp['objset_end']
self.objset = api_resp['objset']
n_objset = []
for rec in self.objset:
rec_orig = rec
rec = rec['qdc']
rec['files'] = rec_orig['files']
n_objset.append(rec)
self.objset = n_objset
def _parse_oac_findaid_ark(self, url_findaid):
return ''.join(('ark:', url_findaid.split('ark:')[1]))
def next(self):
'''Point to which function we want as main'''
return self.next_objset()
def next_record(self):
'''Return the next record'''
while self.resp:
try:
rec = self.objset.pop()
return rec
except IndexError:
if self.objset_end == self.objset_total:
self.resp = None
raise StopIteration
url_next = ''.join((self.url, '&startDoc=',
unicode(self.objset_end + 1)))
self.resp = requests.get(url_next, headers=self.headers)
self.api_resp = self.resp.json()
# self.objset_total = api_resp['objset_total']
self.objset_start = self.api_resp['objset_start']
self.objset_end = self.api_resp['objset_end']
self.objset = self.api_resp['objset']
n_objset = []
for rec in self.objset:
rec_orig = rec
rec = rec['qdc']
rec['files'] = rec_orig['files']
n_objset.append(rec)
self.objset = n_objset
def next_objset(self):
'''Return records in objset batches. More efficient and makes
sense when storing to file in DPLA type ingest'''
if self.objset_last:
raise StopIteration
cur_objset = self.objset
if self.objset_end == self.objset_total:
self.objset_last = True
else:
url_next = ''.join((self.url, '&startDoc=',
unicode(self.objset_end + 1)))
self.resp = requests.get(url_next, headers=self.headers)
self.api_resp = self.resp.json()
self.objset_start = self.api_resp['objset_start']
self.objset_end = self.api_resp['objset_end']
self.objset = self.api_resp['objset']
n_objset = []
for rec in self.objset:
rec_orig = rec
rec = rec['qdc']
rec['files'] = rec_orig['files']
n_objset.append(rec)
self.objset = n_objset
return cur_objset
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,101 | ucldc/harvester | refs/heads/master | /scripts/delete_solr_collection.py | #! /bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import requests
from harvester.solr_updater import delete_solr_collection
def confirm_deletion(cid):
prompt = "Are you sure you want to delete all solr " + \
"documents for %s? yes to confirm\n" % cid
while True:
ans = raw_input(prompt).lower()
if ans == "yes":
return True
else:
return False
if __name__ == '__main__':
URL_SOLR = os.environ['URL_SOLR']
DATA_BRANCH = os.environ['DATA_BRANCH']
parser = argparse.ArgumentParser(
description='Delete all documents in given collection in solr '
'for {0}'.format(DATA_BRANCH))
parser.add_argument('collection_id', help='Registry id for the collection')
parser.add_argument(
'--yes',
action='store_true',
help="Don't prompt for deletion, just do it")
args = parser.parse_args()
if args.yes or confirm_deletion(args.collection_id):
print 'DELETING COLLECTION {}'.format(args.collection_id)
delete_solr_collection(URL_SOLR, args.collection_id)
else:
print "Exiting without deleting"
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,102 | ucldc/harvester | refs/heads/master | /scripts/copy_couchdb_fields.py | import sys
import os
from harvester.post_processing.couchdb_runner import CouchDBWorker
from harvester.image_harvest import harvest_image_for_doc
from harvester.couchdb_init import get_couchdb
import couchdb #couchdb-python
from dplaingestion.selector import getprop, setprop
EMAIL_RETURN_ADDRESS = os.environ.get('EMAIL_RETURN_ADDRESS',
'example@example.com')
# csv delim email addresses
EMAIL_SYS_ADMIN = os.environ.get('EMAIL_SYS_ADMINS', None)
def copy_fields_for_doc(doc, couchdb_src, field_list,
couchdb_dest):
doc_id = doc['_id']
doc_src = couchdb_src[doc_id]
for field in field_list:
value_src = getprop(doc_src, field, keyErrorAsNone=True)
print "SRC ID:{} FIELD {} VALUE:{}".format(doc_id, field, value_src)
if value_src:
setprop(doc, field, value_src)
couchdb_dest.save(doc)
else:
print 'SRC DOC {} missing {}'.format(doc_id, field)
def def_args():
import argparse
parser = argparse.ArgumentParser(
description='Copy fields from one couchdb to another')
parser.add_argument('user_email', type=str, help='user email')
#parser.add_argument('rq_queue', type=str, help='RQ Queue to put job in')
parser.add_argument('cid', type=str,
help='Collection ID')
parser.add_argument('url_couchdb_src', type=str,
help='Source couchdb')
parser.add_argument('field_list', type=str,
help='List of fields to copy over')
parser.add_argument('--url_couchdb_dest', type=str,
help='Destination couchdb (defaults to environment couch)')
return parser
def main(user_email, cid, url_couchdb_src, field_list, url_couchdb_dest=None):
worker = CouchDBWorker()
timeout = 100000
cdb_src = get_couchdb(url=url_couchdb_src, username=False, password=False)
if url_couchdb_dest:
cdb_dest= get_couchdb(url=url_couchdb_dest)
else:
cdb_dest= get_couchdb()
worker.run_by_collection(cid,
copy_fields_for_doc,
cdb_src,
field_list,
cdb_dest
)
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args(sys.argv[1:])
if not args.user_email or not args.cid:
parser.print_help()
sys.exit(27)
kwargs = {}
field_list = [ x for x in args.field_list.split(',')]
if args.url_couchdb_dest:
kwargs['url_couchdb_dest'] = args.url_couchdb_dest
main(args.user_email,
args.cid,
args.url_couchdb_src,
field_list,
**kwargs)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,103 | ucldc/harvester | refs/heads/master | /test/test_harvestcontroller.py | import os
from unittest import TestCase
from unittest import skip
import shutil
import re
import json
import datetime
from mypretty import httpretty
# import httpretty
from mock import patch
from test.utils import ConfigFileOverrideMixin, LogOverrideMixin
from test.utils import DIR_FIXTURES, TEST_COUCH_DASHBOARD, TEST_COUCH_DB
import harvester.fetcher as fetcher
from harvester.collection_registry_client import Collection
from harvester.fetcher.controller import HarvestController
class HarvestControllerTestCase(ConfigFileOverrideMixin, LogOverrideMixin,
TestCase):
'''Test the harvest controller class'''
@httpretty.activate
def setUp(self):
super(HarvestControllerTestCase, self).setUp()
httpretty.register_uri(
httpretty.GET,
"https://registry.cdlib.org/api/v1/collection/197/",
body=open(DIR_FIXTURES + '/collection_api_test.json').read())
httpretty.register_uri(
httpretty.GET,
re.compile("http://content.cdlib.org/oai?.*"),
body=open(DIR_FIXTURES + '/testOAI-128-records.xml').read())
self.collection = Collection(
'https://registry.cdlib.org/api/v1/collection/197/')
config_file, profile_path = self.setUp_config(self.collection)
self.controller_oai = fetcher.HarvestController(
'email@example.com',
self.collection,
profile_path=profile_path,
config_file=config_file)
self.objset_test_doc = json.load(
open(DIR_FIXTURES + '/objset_test_doc.json'))
class myNow(datetime.datetime):
@classmethod
def now(cls):
return cls(2017, 7, 14, 12, 1)
self.old_dt = datetime.datetime
datetime.datetime = myNow
def tearDown(self):
super(HarvestControllerTestCase, self).tearDown()
self.tearDown_config()
shutil.rmtree(self.controller_oai.dir_save)
datetime.datetime = self.old_dt
@httpretty.activate
def testHarvestControllerExists(self):
httpretty.register_uri(
httpretty.GET,
"https://registry.cdlib.org/api/v1/collection/197/",
body=open(DIR_FIXTURES + '/collection_api_test.json').read())
httpretty.register_uri(
httpretty.GET,
re.compile("http://content.cdlib.org/oai?.*"),
body=open(DIR_FIXTURES + '/testOAI-128-records.xml').read())
collection = Collection(
'https://registry.cdlib.org/api/v1/collection/197/')
controller = fetcher.HarvestController(
'email@example.com',
collection,
config_file=self.config_file,
profile_path=self.profile_path)
self.assertTrue(hasattr(controller, 'fetcher'))
self.assertIsInstance(controller.fetcher, fetcher.OAIFetcher)
self.assertTrue(hasattr(controller, 'campus_valid'))
self.assertTrue(hasattr(controller, 'dc_elements'))
self.assertTrue(hasattr(controller, 'datetime_start'))
print(controller.s3path)
self.assertEqual(controller.s3path,
'data-fetched/197/2017-07-14-1201/')
shutil.rmtree(controller.dir_save)
def test_jsonl(self):
objset = [
{'x': 'y'},
['z', 'a'],
[{'b': ['c', 'd']}, [{'e': 'f'}]],
]
self.assertEqual(
HarvestController.jsonl(objset),
'{"x": "y"}\n["z", "a"]\n[{"b": ["c", "d"]}, [{"e": "f"}]]\n')
objset = {'x':'y', 'z':'a', 'b': [1,2,3]}
self.assertEqual(
HarvestController.jsonl(objset),
'{"x": "y", "z": "a", "b": [1, 2, 3]}\n')
@httpretty.activate
@patch('boto3.resource', autospec=True)
def testSaveToS3(self, mock_boto3):
httpretty.register_uri(
httpretty.GET,
"https://registry.cdlib.org/api/v1/collection/197/",
body=open(DIR_FIXTURES + '/collection_api_test.json').read())
httpretty.register_uri(
httpretty.GET,
re.compile("http://content.cdlib.org/oai?.*"),
body=open(DIR_FIXTURES + '/testOAI-128-records.xml').read())
collection = Collection(
'https://registry.cdlib.org/api/v1/collection/197/')
controller = fetcher.HarvestController(
'email@example.com',
collection,
config_file=self.config_file,
profile_path=self.profile_path)
controller.save_objset_s3({"xxxx": "yyyy"})
mock_boto3.assert_called_with('s3')
mock_boto3().Bucket.assert_called_with('ucldc-ingest')
mock_boto3().Bucket().put_object.assert_called_with(
Body='{"xxxx": "yyyy"}\n',
Key='data-fetched/197/2017-07-14-1201/page-0.jsonl')
def testOAIFetcherType(self):
'''Check the correct object returned for type of harvest'''
self.assertIsInstance(self.controller_oai.fetcher, fetcher.OAIFetcher)
self.assertEqual(self.controller_oai.collection.campus[0]['slug'],
'UCDL')
def testUpdateIngestDoc(self):
'''Test that the update to the ingest doc in couch is called correctly
'''
self.assertTrue(hasattr(self.controller_oai, 'update_ingest_doc'))
self.assertRaises(TypeError, self.controller_oai.update_ingest_doc)
self.assertRaises(ValueError, self.controller_oai.update_ingest_doc,
'error')
with patch('dplaingestion.couch.Couch') as mock_couch:
instance = mock_couch.return_value
instance._create_ingestion_document.return_value = 'test-id'
foo = {}
with patch.dict(foo, {'test-id': 'test-ingest-doc'}):
instance.dashboard_db = foo
self.controller_oai.update_ingest_doc(
'error', error_msg="BOOM!")
call_args = unicode(instance.update_ingestion_doc.call_args)
self.assertIn('test-ingest-doc', call_args)
self.assertIn("fetch_process/error='BOOM!'", call_args)
self.assertIn("fetch_process/end_time", call_args)
self.assertIn("fetch_process/total_items=0", call_args)
self.assertIn("fetch_process/total_collections=None", call_args)
@patch('dplaingestion.couch.Couch')
def testCreateIngestCouch(self, mock_couch):
'''Test the integration of the DPLA couch lib'''
self.assertTrue(hasattr(self.controller_oai, 'ingest_doc_id'))
self.assertTrue(hasattr(self.controller_oai, 'create_ingest_doc'))
self.assertTrue(hasattr(self.controller_oai, '_config'))
self.controller_oai.create_ingest_doc()
mock_couch.assert_called_with(
config_file=self.config_file,
dashboard_db_name=TEST_COUCH_DASHBOARD,
dpla_db_name=TEST_COUCH_DB)
def testUpdateFailInCreateIngestDoc(self):
'''Test the failure of the update to the ingest doc'''
with patch('dplaingestion.couch.Couch') as mock_couch:
instance = mock_couch.return_value
instance._create_ingestion_document.return_value = 'test-id'
instance.update_ingestion_doc.side_effect = Exception('Boom!')
self.assertRaises(Exception, self.controller_oai.create_ingest_doc)
def testCreateIngestDoc(self):
'''Test the creation of the DPLA style ingest document in couch.
This will call _create_ingestion_document, dashboard_db and
update_ingestion_doc
'''
with patch('dplaingestion.couch.Couch') as mock_couch:
instance = mock_couch.return_value
instance._create_ingestion_document.return_value = 'test-id'
instance.update_ingestion_doc.return_value = None
foo = {}
with patch.dict(foo, {'test-id': 'test-ingest-doc'}):
instance.dashboard_db = foo
ingest_doc_id = self.controller_oai.create_ingest_doc()
self.assertIsNotNone(ingest_doc_id)
self.assertEqual(ingest_doc_id, 'test-id')
instance._create_ingestion_document.assert_called_with(
self.collection.provider, 'http://localhost:8889',
self.profile_path,
self.collection.dpla_profile_obj['thresholds'])
instance.update_ingestion_doc.assert_called()
self.assertEqual(instance.update_ingestion_doc.call_count, 1)
call_args = unicode(instance.update_ingestion_doc.call_args)
self.assertIn('test-ingest-doc', call_args)
self.assertIn("fetch_process/data_dir", call_args)
self.assertIn("santa-clara-university-digital-objects", call_args)
self.assertIn("fetch_process/end_time=None", call_args)
self.assertIn("fetch_process/status='running'", call_args)
self.assertIn("fetch_process/total_collections=None", call_args)
self.assertIn("fetch_process/start_time=", call_args)
self.assertIn("fetch_process/error=None", call_args)
self.assertIn("fetch_process/total_items=None", call_args)
def testNoTitleInRecord(self):
'''Test that the process continues if it finds a record with no "title"
THIS IS NOW HANDLED DOWNSTREAM'''
pass
def testFileSave(self):
'''Test saving objset to file'''
self.assertTrue(hasattr(self.controller_oai, 'dir_save'))
self.assertTrue(hasattr(self.controller_oai, 'save_objset'))
self.controller_oai.save_objset(self.objset_test_doc)
# did it save?
dir_list = os.listdir(self.controller_oai.dir_save)
self.assertEqual(len(dir_list), 1)
objset_saved = json.loads(
open(os.path.join(self.controller_oai.dir_save, dir_list[0])).read(
))
self.assertEqual(self.objset_test_doc, objset_saved)
@skip('Takes too long')
@httpretty.activate
def testLoggingMoreThan1000(self):
httpretty.register_uri(
httpretty.GET,
"https://registry.cdlib.org/api/v1/collection/198/",
body=open(DIR_FIXTURES + '/collection_api_big_test.json').read())
httpretty.register_uri(
httpretty.GET,
re.compile("http://content.cdlib.org/oai?.*"),
body=open(DIR_FIXTURES + '/testOAI-2400-records.xml').read())
collection = Collection(
'https://registry.cdlib.org/api/v1/collection/198/')
controller = fetcher.HarvestController(
'email@example.com',
collection,
config_file=self.config_file,
profile_path=self.profile_path)
controller.harvest()
self.assertEqual(len(self.test_log_handler.records), 13)
self.assertEqual(self.test_log_handler.formatted_records[1],
'[INFO] HarvestController: 100 records harvested')
shutil.rmtree(controller.dir_save)
self.assertEqual(self.test_log_handler.formatted_records[10],
'[INFO] HarvestController: 1000 records harvested')
self.assertEqual(self.test_log_handler.formatted_records[11],
'[INFO] HarvestController: 2000 records harvested')
self.assertEqual(self.test_log_handler.formatted_records[12],
'[INFO] HarvestController: 2400 records harvested')
@httpretty.activate
def testAddRegistryData(self):
'''Unittest the _add_registry_data function'''
httpretty.register_uri(
httpretty.GET,
"https://registry.cdlib.org/api/v1/collection/197/",
body=open(DIR_FIXTURES + '/collection_api_test.json').read())
httpretty.register_uri(
httpretty.GET,
re.compile("http://content.cdlib.org/oai?.*"),
body=open(DIR_FIXTURES + '/testOAI-128-records.xml').read())
collection = Collection(
'https://registry.cdlib.org/api/v1/collection/197/')
self.tearDown_config() # remove ones setup in setUp
self.setUp_config(collection)
controller = fetcher.HarvestController(
'email@example.com',
collection,
config_file=self.config_file,
profile_path=self.profile_path)
obj = {'id': 'fakey', 'otherdata': 'test'}
self.assertNotIn('collection', obj)
controller._add_registry_data(obj)
self.assertIn('collection', obj)
self.assertEqual(obj['collection'][0]['@id'],
'https://registry.cdlib.org/api/v1/collection/197/')
self.assertNotIn('campus', obj)
self.assertIn('campus', obj['collection'][0])
self.assertNotIn('repository', obj)
self.assertIn('repository', obj['collection'][0])
# need to test one without campus
self.assertEqual(obj['collection'][0]['campus'][0]['@id'],
'https://registry.cdlib.org/api/v1/campus/12/')
self.assertEqual(obj['collection'][0]['repository'][0]['@id'],
'https://registry.cdlib.org/api/v1/repository/37/')
@patch('boto3.resource', autospec=True)
def testObjectsHaveRegistryData(self, mock_boto3):
'''Test that the registry data is being attached to objects from
the harvest controller'''
self.controller_oai.harvest()
dir_list = os.listdir(self.controller_oai.dir_save)
self.assertEqual(len(dir_list), 128)
objset_saved = json.loads(
open(os.path.join(self.controller_oai.dir_save, dir_list[0])).read(
))
obj_saved = objset_saved[0]
self.assertIn('collection', obj_saved)
self.assertEqual(obj_saved['collection'][0]['@id'],
'https://registry.cdlib.org/api/v1/collection/197/')
self.assertEqual(
obj_saved['collection'][0]['title'],
'Calisphere - Santa Clara University: Digital Objects')
self.assertEqual(obj_saved['collection'][0]['ingestType'],
'collection')
self.assertNotIn('campus', obj_saved)
self.assertEqual(obj_saved['collection'][0]['campus'], [{
'@id': 'https://registry.cdlib.org/api/v1/campus/12/',
"slug": "UCDL",
"resource_uri": "/api/v1/campus/12/",
"position": 11,
"name": "California Digital Library"
}])
self.assertNotIn('repository', obj_saved)
self.assertEqual(obj_saved['collection'][0]['repository'], [{
'@id': 'https://registry.cdlib.org/api/v1/repository/37/',
"resource_uri": "/api/v1/repository/37/",
"name": "Calisphere",
"slug": "Calisphere",
"campus": [{
"slug": "UCDL",
"resource_uri": "/api/v1/campus/12/",
"position": 11,
"name": "California Digital Library"
}]
}])
@httpretty.activate
def testFailsIfNoRecords(self):
'''Test that the Controller throws an error if no records come back
from fetcher
'''
httpretty.register_uri(
httpretty.GET,
"https://registry.cdlib.org/api/v1/collection/101/",
body=open(DIR_FIXTURES + '/collection_api_test.json').read())
httpretty.register_uri(
httpretty.GET,
re.compile("http://content.cdlib.org/oai?.*"),
body=open(DIR_FIXTURES + '/testOAI-no-records.xml').read())
collection = Collection(
'https://registry.cdlib.org/api/v1/collection/101/')
controller = fetcher.HarvestController(
'email@example.com',
collection,
config_file=self.config_file,
profile_path=self.profile_path)
self.assertRaises(fetcher.NoRecordsFetchedException,
controller.harvest)
class FetcherClassTestCase(TestCase):
'''Test the abstract Fetcher class'''
def testClassExists(self):
h = fetcher.Fetcher
h = h('url_harvest', 'extra_data')
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,104 | ucldc/harvester | refs/heads/master | /harvester/rq_worker_sns_msgs.py | '''A custom rq worker class to add start & stop SNS messages to all jobs'''
import logging
import os
import re
from rq.worker import HerokuWorker
from harvester.sns_message import publish_to_harvesting
logger = logging.getLogger(__name__)
# need tuple of tuple pairs, regex string to msg template
# the regex needs to match the function called
# and parse out the collection id
message_match_list = (
("sync_couch_collection_to_solr\(collection_key='(?P<cid>\d+)'\)",
"{status}: Sync from Couchdb to Solr {env} on "
":worker: {worker} for CID: {cid}"),
("run_ingest.main.*/collection/(?P<cid>\d+)/",
"{status}: Metadata Harvest to Couchdb {env} on "
":worker: {worker} for CID: {cid}"),
("image_harvest.main\(collection_key=.*'(?P<cid>\d+)'",
"{status}: Image Harvest {env} on "
":worker: {worker} for CID: {cid}"),
("delete_solr_collection\(collection_key='(?P<cid>\d+)'\)",
"{status}: Delete from Solr {env} on "
":worker: {worker} for CID: {cid}"),
("s3stash.stash_collection.main\(registry_id=(?P<cid>\d+)",
"{status}: Nuxeo Deep Harvest on "
":worker: {env} {worker} for CID: {cid}"),
("delete_collection\((?P<cid>\d+)\)",
"{status}: Delete CouchDB {env} on "
":worker: {worker} for CID: {cid}"),
("couchdb_sync_db_by_collection.main\(url_api_collection="
"'https://registry.cdlib.org/api/v1/collection/(?P<cid>\d+)/'",
"{status}: Sync CouchDB to production on "
":worker: {env} {worker} for CID: {cid}"),
("<fn--name> -- parse out collection id as cid ",
"replacement template for message- needs cid env variables"))
re_object_auth = re.compile("object_auth=(\('\w+', '\S+'\))")
def create_execute_job_message(status, worker, job):
'''Create a formatted message for the job.
Searches for a match to function, then fills in values
'''
env = os.environ.get('DATA_BRANCH')
message_template = "{status}: {env} {worker} {job}"
message = message_template.format(
status=status, env=env, worker=worker, job=job.description)
subject = message
for regex, msg_template in message_match_list:
m = re.search(regex, job.description)
if m:
mdict = m.groupdict()
subject = msg_template.format(
status=status,
env=env,
worker=worker,
cid=mdict.get('cid', '?'))
message = ''.join((subject, '\n', job.description))
break
message = re_object_auth.sub('object_auth=<REDACTED>', message)
return subject, message
def exception_to_sns(job, *exc_info):
'''Make an exception handler to report exceptions to SNS msg queue'''
subject = 'FAILED: job {}'.format(job.description)
message = 'ERROR: job {} failed\n{}'.format(job.description, exc_info[1])
logging.error(message)
publish_to_harvesting(subject, message)
class SNSWorker(HerokuWorker):
def execute_job(self, job, queue):
"""Spawns a work horse to perform the actual work and passes it a job.
The worker will wait for the work horse and make sure it executes
within the given timeout bounds, or will end the work horse with
SIGALRM.
"""
worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0]
subject, msg = create_execute_job_message("Started", worker_name, job)
logging.info(msg)
publish_to_harvesting(subject, msg)
self.set_state('busy')
self.fork_work_horse(job, queue)
self.monitor_work_horse(job)
subject, msg = create_execute_job_message("Completed", worker_name,
job)
logging.info(msg)
publish_to_harvesting(subject, msg)
self.set_state('idle')
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,105 | ucldc/harvester | refs/heads/master | /test/test_couchdb_runner.py | import os
from unittest import TestCase
import re
from mypretty import httpretty
# import httpretty
from mock import patch
from test.utils import DIR_FIXTURES
from harvester.config import config
from harvester.post_processing.couchdb_runner import COUCHDB_VIEW
from harvester.post_processing.couchdb_runner import CouchDBWorker
from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
class CouchDBWorkerTestCase(TestCase):
'''Test the running of functions against sets of couchdb documents.
'''
@httpretty.activate
def setUp(self):
self.conf = config()
self.url_couch_base = self.conf['couchdb_url']
self.cdb = self.conf['couchdb_dbname']
url_head = os.path.join(self.url_couch_base, self.cdb)
httpretty.register_uri(httpretty.HEAD,
url_head,
body='',
content_length='0',
content_type='text/plain; charset=utf-8',
connection='close',
server='CouchDB/1.5.0 (Erlang OTP/R16B03)',
cache_control='must-revalidate',
date='Mon, 24 Nov 2014 21:30:38 GMT'
)
self._cdbworker = CouchDBWorker()
def func_for_test(doc, *args, **kwargs):
return doc, args, kwargs
self.function = func_for_test
@httpretty.activate
def testCollectionSlice(self):
'''Test that results are correct for a known couchdb result'''
url_to_pretty = os.path.join(self.url_couch_base, self.cdb,
'_design', COUCHDB_VIEW.split('/')[0],
'_view', COUCHDB_VIEW.split('/')[1])
httpretty.register_uri(httpretty.GET,
re.compile(url_to_pretty+".*$"),
body=open(DIR_FIXTURES+'/couchdb_by_provider_name-5112.json').read(),
etag="2U5BW2TDDX9EHZJOO0DNE29D1",
content_type='application/json',
)
results = self._cdbworker.run_by_collection('5112', self.function,
'arg1', 'arg2', kwarg1='1', kwarg2=2)
self.assertEqual(len(results), 3)
self.assertEqual(results[1][0], '5112--http://ark.cdlib.org/ark:/13030/kt7779r8zj')
self.assertEqual(results[1][1][1], ('arg1', 'arg2'))
self.assertEqual(results[1][1][2], {'kwarg1':'1', 'kwarg2':2})
doc = results[0][1][0]
self.assertEqual(doc['isShownAt'], 'http://www.coronado.ca.us/library/')
class CouchDBJobEnqueueTestCase(TestCase):
#@patch('redis.client.Redis', autospec=True)
@patch('harvester.post_processing.couchdb_runner.Redis')
@httpretty.activate
def setUp(self, mock_redis):
self.conf = config()
self.url_couch_base = self.conf['couchdb_url']
self.cdb = self.conf['couchdb_dbname']
print "+++++++++++++confg:{0}".format(self.conf)
url_head = os.path.join(self.url_couch_base, self.cdb)
httpretty.register_uri(httpretty.HEAD,
url_head,
body='',
content_length='0',
content_type='text/plain; charset=utf-8',
connection='close',
server='CouchDB/1.5.0 (Erlang OTP/R16B03)',
cache_control='must-revalidate',
date='Mon, 24 Nov 2014 21:30:38 GMT'
)
self._cdbrunner = CouchDBJobEnqueue(rq_queue='test-delete')
def func_for_test(doc, *args, **kwargs):
return doc, args, kwargs
self.function = func_for_test
@httpretty.activate
def testCollectionSlice(self):
'''Test that results are correct for a known couchdb result'''
url_to_pretty = os.path.join(self.url_couch_base, self.cdb,
'_design', COUCHDB_VIEW.split('/')[0],
'_view', COUCHDB_VIEW.split('/')[1])
httpretty.register_uri(httpretty.GET,
re.compile(url_to_pretty+".*$"),
body=open(DIR_FIXTURES+'/couchdb_by_provider_name-5112.json').read(),
etag="2U5BW2TDDX9EHZJOO0DNE29D1",
content_type='application/json',
)
#transfer_encoding='chunked', #NOTE: doesn't work with httpretty
results = self._cdbrunner.queue_collection('5112', 6000, self.function,
'arg1', 'arg2', kwarg1='1', kwarg2=2)
self.assertEqual(len(results), 3)
self.assertEqual(results[0].args, ('5112--http://ark.cdlib.org/ark:/13030/kt7580382j', 'arg1', 'arg2'))
self.assertEqual(results[0].kwargs, {'kwarg1': '1', 'kwarg2': 2})
self.assertEqual(results[0].func_name, 'test.test_couchdb_runner.func_for_test')
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,106 | ucldc/harvester | refs/heads/master | /harvester/sns_message.py | import os
import boto3
import botocore.exceptions
import logging
import requests
logger = logging.getLogger(__name__)
def format_results_subject(cid, registry_action):
'''Format the "subject" part of the harvesting message for
results from the various processes.
Results: [Action from Registry] on [Worker IP] for Collection ID [###]
'''
if '{env}' in registry_action:
registry_action = registry_action.format(
env=os.environ.get('DATA_BRANCH'))
resp = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4')
worker_ip = resp.text
worker_id = worker_ip.replace('.', '-')
return 'Results: {} on :worker: {} for CID: {}'.format(
registry_action,
worker_id,
cid)
def publish_to_harvesting(subject, message):
'''Publish a SNS message to the harvesting topic channel'''
client = boto3.client('sns')
# NOTE: this appears to raise exceptions if problem
try:
client.publish(
TopicArn=os.environ['ARN_TOPIC_HARVESTING_REPORT'],
Message=message[:100000],
Subject=subject[:100]
)
except botocore.exceptions.BotoCoreError, e:
logger.error('Exception in Boto SNS: {}'.format(e))
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,107 | ucldc/harvester | refs/heads/master | /harvester/ansible_run_pb.py | # execute a playbook from within python
# for use from an rqworker
# fullpath to playbook This is copied & modified from the
# ansible-playbook standalone script
import sys
import os
from ansible import errors
from ansible import utils
import ansible.playbook
import ansible.constants as C
from ansible import callbacks
def get_args(args): # create parser for CLI options
usage = "%prog playbook.yml"
parser = utils.base_parser(
constants=C,
usage=usage,
connect_opts=True,
runas_opts=True,
subset_opts=True,
check_opts=True,
diff_opts=True
)
return parser.parse_args(args)
def main(playbook, inventory, remote_user=None, private_key_file=None):
if not os.path.exists(playbook):
raise errors.AnsibleError("the playbook: %s could not be found" % playbook)
if not os.path.isfile(playbook):
raise errors.AnsibleError("the playbook: %s does not appear to be a file" % playbook)
if not os.path.exists(inventory):
raise errors.AnsibleError("the inventory: %s could not be found" % inventory)
if not os.path.isfile(inventory):
raise errors.AnsibleError("the inventory: %s does not appear to be a file" % inventory)
inventory = ansible.inventory.Inventory(inventory)
if len(inventory.list_hosts()) == 0:
raise errors.AnsibleError("provided hosts list is empty")
# let inventory know which playbooks are using so it can know the basedirs
inventory.set_playbook_basedir(os.path.dirname(playbook))
stats = callbacks.AggregateStats()
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
pb = ansible.playbook.PlayBook(
playbook=playbook,
inventory=inventory,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
stats=stats,
)
if remote_user:
pb.remote_user = remote_user
if private_key_file:
pb.private_key_file = private_key_file
pb.run()
if __name__ == '__main__':
options, args = get_args(sys.argv)
pb = args[1]
main(pb, options.inventory, remote_user=options.remote_user, private_key_file=options.private_key_file)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,108 | ucldc/harvester | refs/heads/master | /scripts/queue_delete_couchdb_collection.py | #! /bin/env python
# -*- coding: utf-8 -*-
import sys
import logbook
from harvester.config import config as config_harvest
from redis import Redis
from rq import Queue
JOB_TIMEOUT = 28800 # 8 hrs
def def_args():
import argparse
parser = argparse.ArgumentParser(description='Harvest a collection')
parser.add_argument('user_email', type=str, help='user email')
parser.add_argument('rq_queue', type=str, help='RQ queue to put job in')
parser.add_argument(
'collection_key',
type=str,
help='URL for the collection Django tastypie api resource')
return parser
def queue_delete_couchdb_collection(redis_host,
redis_port,
redis_password,
redis_timeout,
rq_queue,
collection_key,
timeout=JOB_TIMEOUT):
rQ = Queue(
rq_queue,
connection=Redis(
host=redis_host,
port=redis_port,
password=redis_password,
socket_connect_timeout=redis_timeout))
job = rQ.enqueue_call(
func='harvester.couchdb_sync_db_by_collection.delete_collection',
args=(collection_key,),
timeout=timeout)
return job
def main(collection_keys,
log_handler=None,
config_file='akara.ini',
rq_queue=None,
**kwargs):
'''Runs a UCLDC sync to solr for collection key'''
config = config_harvest(config_file=config_file)
if not log_handler:
log_handler = logbook.StderrHandler(level='DEBUG')
log_handler.push_application()
for collection_key in [x for x in collection_keys.split(';')]:
queue_delete_couchdb_collection(
config['redis_host'],
config['redis_port'],
config['redis_password'],
config['redis_connect_timeout'],
rq_queue=rq_queue,
collection_key=collection_key,
**kwargs)
log_handler.pop_application()
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args(sys.argv[1:])
if not args.collection_key:
parser.print_help()
sys.exit(27)
kwargs = {}
main(args.collection_key, rq_queue=args.rq_queue, **kwargs)
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,109 | ucldc/harvester | refs/heads/master | /scripts/remove_field_list_from_collection_docs.py | #! /bin/env python
import sys
import os
from harvester.post_processing.couchdb_runner import CouchDBWorker
from harvester.image_harvest import harvest_image_for_doc
from harvester.couchdb_init import get_couchdb
import couchdb #couchdb-python
from dplaingestion.selector import delprop
EMAIL_RETURN_ADDRESS = os.environ.get('EMAIL_RETURN_ADDRESS',
'example@example.com')
# csv delim email addresses
EMAIL_SYS_ADMIN = os.environ.get('EMAIL_SYS_ADMINS', None)
def delete_field(doc, field):
delprop(doc, field, keyErrorAsNone=True)
def delete_field_list(doc, field_list, cdb):
for field in field_list:
delete_field(doc, field)
doc.save()
def def_args():
import argparse
parser = argparse.ArgumentParser(
description='Delete fields from couchdb docs for a collection')
parser.add_argument('user_email', type=str, help='user email')
#parser.add_argument('rq_queue', type=str, help='RQ Queue to put job in')
parser.add_argument('cid', type=str,
help='Collection ID')
parser.add_argument('field_list', type=str,
help='List of fields to delete over')
return parser
def main(user_email, cid, field_list):
worker = CouchDBWorker()
timeout = 100000
cdb = get_couchdb()
worker.run_by_collection(cid,
delete_field_list,
field_list,
cdb
)
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args(sys.argv[1:])
if not args.user_email or not args.cid:
parser.print_help()
sys.exit(27)
kwargs = {}
field_list = [ x for x in args.field_list.split(',')]
main(args.user_email,
args.cid,
args.url_couchdb_src,
field_list,
**kwargs)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,110 | ucldc/harvester | refs/heads/master | /scripts/rollback_couchdb.py | # -*- coding: utf-8 -*-
'''Rollback docs to previous rev for given collection'''
import os
import json
import couchdb
from harvester.post_processing.couchdb_runner import get_collection_doc_ids
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
couch_stg = 'https://{}harvest-stg.cdlib.org/couchdb'
couch_prd = 'https://{}harvest-prd.cdlib.org/couchdb'
def rollback_collection_docs(collection_key, dry_run=False, auth=''):
dids = get_collection_doc_ids(collection_key, couch_stg.format(''))
url = couch_stg.format(auth)
cserver_stg = couchdb.Server(url)
cdb_stg = cserver_stg['ucldc']
i = 0
try:
os.mkdir(collection_key)
except OSError:
pass
for did in dids:
print did
doc = cdb_stg[did]
revs = cdb_stg.revisions(doc['_id'])
rlist = []
for i, x in enumerate(revs):
print x['_rev']
rlist.append(x)
if i > 1:
break
rev_doc = rlist[2]
rev_doc['_rev'] = rlist[0]['_rev']
with open('{}/{}_old.json'.format(collection_key, doc['id']),
'w') as foo:
json.dump(rlist[0], foo)
# revert by updating
if not dry_run:
pass
cdb_stg[did] = rev_doc
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description='Compare stage to production couchdb collection')
parser.add_argument('collection_key', type=str,
help='Numeric ID for collection')
args = parser.parse_args()
auth = ''
if os.environ.get('COUCHDB_USER'):
auth = '{}:{}@'.format(
os.environ['COUCHDB_USER'],
os.environ.get('COUCHDB_PASSWORD'))
print "AUTH:{}".format(auth)
results = rollback_collection_docs(args.collection_key, auth=auth)
print results
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,111 | ucldc/harvester | refs/heads/master | /test/test_cmisatomfeed_fetcher.py | # -*- coding: utf-8 -*-
from unittest import TestCase
from mypretty import httpretty
# import httpretty
import harvester.fetcher as fetcher
from test.utils import LogOverrideMixin
from test.utils import DIR_FIXTURES
class CMISAtomFeedFetcherTestCase(LogOverrideMixin, TestCase):
@httpretty.activate
def testCMISFetch(self):
httpretty.register_uri(
httpretty.GET,
'http://cmis-atom-endpoint/descendants',
body=open(DIR_FIXTURES+'/cmis-atom-descendants.xml').read())
h = fetcher.CMISAtomFeedFetcher(
'http://cmis-atom-endpoint/descendants',
'uname, pswd')
self.assertTrue(hasattr(h, 'objects'))
self.assertEqual(42, len(h.objects))
@httpretty.activate
def testFetching(self):
httpretty.register_uri(
httpretty.GET,
'http://cmis-atom-endpoint/descendants',
body=open(DIR_FIXTURES+'/cmis-atom-descendants.xml').read())
h = fetcher.CMISAtomFeedFetcher(
'http://cmis-atom-endpoint/descendants',
'uname, pswd')
num_fetched = 0
for obj in h:
num_fetched += 1
self.assertEqual(num_fetched, 42)
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,112 | ucldc/harvester | refs/heads/master | /test/test_marc_fetcher.py | # -*- coding: utf-8 -*-
from unittest import TestCase
import shutil
from mock import patch
from harvester.collection_registry_client import Collection
from test.utils import ConfigFileOverrideMixin, LogOverrideMixin
from test.utils import DIR_FIXTURES
from mypretty import httpretty
# import httpretty
import harvester.fetcher as fetcher
import pprint
class MARCFetcherTestCase(LogOverrideMixin, TestCase):
'''Test MARC fetching'''
def testInit(self):
'''Basic tdd start'''
h = fetcher.MARCFetcher('file:' + DIR_FIXTURES + '/marc-test', None)
self.assertTrue(hasattr(h, 'url_marc_file'))
self.assertTrue(hasattr(h, 'marc_file'))
self.assertIsInstance(h.marc_file, file)
self.assertTrue(hasattr(h, 'marc_reader'))
self.assertEqual(
str(type(h.marc_reader)), "<class 'pymarc.reader.MARCReader'>")
def testLocalFileLoad(self):
h = fetcher.MARCFetcher('file:' + DIR_FIXTURES + '/marc-test', None)
for n, rec in enumerate(h): # enum starts at 0
pass
# print("NUM->{}:{}".format(n,rec))
self.assertEqual(n, 9)
self.assertIsInstance(rec, dict)
self.assertEqual(rec['leader'], '01914nkm a2200277ia 4500')
self.assertEqual(len(rec['fields']), 21)
class AlephMARCXMLFetcherTestCase(LogOverrideMixin, TestCase):
@httpretty.activate
def testInit(self):
httpretty.register_uri(
httpretty.GET,
'http://ucsb-fake-aleph/endpoint&maximumRecords=3&startRecord=1',
body=open(DIR_FIXTURES + '/ucsb-aleph-resp-1-3.xml').read())
h = fetcher.AlephMARCXMLFetcher(
'http://ucsb-fake-aleph/endpoint', None, page_size=3)
self.assertTrue(hasattr(h, 'ns'))
self.assertTrue(hasattr(h, 'url_base'))
self.assertEqual(h.page_size, 3)
self.assertEqual(h.num_records, 8)
@httpretty.activate
def testFetching(self):
httpretty.register_uri(
httpretty.GET,
'http://ucsb-fake-aleph/endpoint&maximumRecords=3&startRecord=1',
body=open(DIR_FIXTURES + '/ucsb-aleph-resp-1-3.xml').read())
httpretty.register_uri(
httpretty.GET,
'http://ucsb-fake-aleph/endpoint&maximumRecords=3&startRecord=4',
body=open(DIR_FIXTURES + '/ucsb-aleph-resp-4-6.xml').read())
httpretty.register_uri(
httpretty.GET,
'http://ucsb-fake-aleph/endpoint&maximumRecords=3&startRecord=7',
body=open(DIR_FIXTURES + '/ucsb-aleph-resp-7-8.xml').read())
h = fetcher.AlephMARCXMLFetcher(
'http://ucsb-fake-aleph/endpoint', None, page_size=3)
num_fetched = 0
for objset in h:
num_fetched += len(objset)
self.assertEqual(num_fetched, 8)
class Harvest_MARC_ControllerTestCase(ConfigFileOverrideMixin,
LogOverrideMixin, TestCase):
'''Test the function of an MARC harvest controller'''
def setUp(self):
super(Harvest_MARC_ControllerTestCase, self).setUp()
def tearDown(self):
super(Harvest_MARC_ControllerTestCase, self).tearDown()
shutil.rmtree(self.controller.dir_save)
@httpretty.activate
@patch('boto3.resource', autospec=True)
def testMARCHarvest(self, mock_boto3):
'''Test the function of the MARC harvest'''
httpretty.register_uri(
httpretty.GET,
'http://registry.cdlib.org/api/v1/collection/',
body=open(DIR_FIXTURES + '/collection_api_test_marc.json').read())
self.collection = Collection(
'http://registry.cdlib.org/api/v1/collection/')
self.collection.url_harvest = 'file:' + DIR_FIXTURES + '/marc-test'
self.setUp_config(self.collection)
self.controller = fetcher.HarvestController(
'email@example.com',
self.collection,
config_file=self.config_file,
profile_path=self.profile_path)
self.assertTrue(hasattr(self.controller, 'harvest'))
num = self.controller.harvest()
self.assertEqual(num, 10)
self.tearDown_config()
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,113 | ucldc/harvester | refs/heads/master | /scripts/redis_delete_harvested_images_script.py | #! /bin/env python
'''create a script to feed to the redis-cli to delete cached
harvested images information'''
import sys
import os
from harvester.post_processing.couchdb_runner import get_collection_doc_ids
redis_hash_key = 'ucldc:harvester:harvested-images'
def create_redis_deletion_script(url_remote_couchdb, collection_id):
doc_ids = get_collection_doc_ids(collection_id, url_remote_couchdb)
redis_cmd_base = 'HDEL {}'.format(redis_hash_key)
# for every 100 ids create a new line
with open('delete_image_cache-{}'.format(collection_id), 'w') as foo:
for doc_id in doc_ids:
redis_cmd = ' '.join((redis_cmd_base, doc_id, '\n'))
foo.write(redis_cmd)
def main(url_remote_couchdb, collection_id):
'''Update to the current environment's couchdb a remote couchdb collection
'''
create_redis_deletion_script(url_remote_couchdb, collection_id)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description='Create script to delete harvested images cache '
'for collection'
)
parser.add_argument(
'--url_remote_couchdb', help='URL to the remote (source) couchdb')
parser.add_argument('collection_id', help='collection id')
args = parser.parse_args(sys.argv[1:])
url_remote_couchdb = args.url_remote_couchdb
if not url_remote_couchdb:
url_remote_couchdb = os.environ.get('COUCHDB_URL', None)
if not url_remote_couchdb:
raise Exception(
"Need to pass in url_remote_couchdb or have $COUCHDB_URL set")
main(url_remote_couchdb, args.collection_id)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,114 | ucldc/harvester | refs/heads/master | /scripts/queue_document_reenrich.py | '''Enqueue a docuement for re-enriching.
'''
import sys
import argparse
from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
import harvester.post_processing.enrich_existing_couch_doc
def main(args):
parser = argparse.ArgumentParser(
description='run an Akara enrichment chain on documents in a \
collection.')
parser.add_argument('document_id',
help='Registry id for the collection')
parser.add_argument('enrichment', help='enrichment chain to run')
args = parser.parse_args(args)
print(args.collection_id)
print(args.enrichment)
enq = CouchDBJobEnqueue()
timeout = 10000
enq.queue_collection(args.collection_id, timeout,
harvester.post_processing.enrich_existing_couch_doc.main,
args.enrichment
)
if __name__=='__main__':
main(sys.argv)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,115 | ucldc/harvester | refs/heads/master | /harvester/post_processing/dedupe_sourceresource.py | from harvester.post_processing.run_transform_on_couchdb_docs import run_on_couchdb_by_collection
# pass in a Couchdb doc, get back one with de-duplicated sourceResource values
def dedupe_sourceresource(doc):
''' Look for duplicate values in the doc['sourceResource'] and
remove.
Values must be *exactly* the same
'''
for key, value in doc['sourceResource'].items():
if isinstance(value, list):
# can't use set() because of dict values (non-hashable)
new_list = []
for item in value:
if item not in new_list:
new_list.append(item)
doc['sourceResource'][key] = new_list
return doc
if __name__=='__main__':
doc_ids = run_on_couchdb_by_collection(dedup_sourceresource)
print "NUMBER OF DOCS DEDUPED:{}".format(len(doc_ids))
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,116 | ucldc/harvester | refs/heads/master | /scripts/fix_lapl_isShownBy.py | import sys
from harvester.post_processing.run_transform_on_couchdb_docs import run_on_couchdb_by_collection
def fix_lapl_isShownBy(doc):
'''Some urls are broken but fixable.'''
if 'sola1' in doc.get('isShownBy', ''):
print 'Fixing {}'.format(doc['_id'])
doc['isShownBy'] = doc['isShownBy'].replace('sola1', '00000')
return doc
else:
return None
run_on_couchdb_by_collection(fix_lapl_isShownBy,
collection_key="26094")
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,117 | ucldc/harvester | refs/heads/master | /scripts/queue_reenrich_26094.py | from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
from harvester.post_processing.enrich_existing_couch_doc import main as reenrich
enrichments = '''/lapl-marc-id,
/dpla_mapper?mapper_type=lapl_marc,
/strip_html,
/set_context,
/cleanup_value,
/move_date_values?prop=sourceResource%2Fsubject,
/move_date_values?prop=sourceResource%2Fspatial,
/shred?prop=sourceResource%2Fspatial&delim=--,
/capitalize_value?exclude=sourceResource%2Frelation,
/enrich-subject,
/enrich_earliest_date,
/enrich_date,
/enrich-type,
/enrich-format,
/enrich_location,
/copy_prop?prop=sourceResource%2Fpublisher&to_prop=dataProvider,
/enrich_language,
/lookup?prop=sourceResource%2Flanguage%2Fname&target=sourceResource%2Flanguage%2Fname&substitution=iso639_3,
/lookup?prop=sourceResource%2Flanguage%2Fname&target=sourceResource%2Flanguage%2Fiso639_3&substitution=iso639_3&inverse=True,
/copy_prop?prop=provider%2Fname&to_prop=dataProvider&skip_if_exists=True,
/set_prop?prop=sourceResource%2FstateLocatedIn&value=California,
/enrich_location?prop=sourceResource%2FstateLocatedIn,
/dedupe-sourceresource,
/validate_mapv3'''
enrichments = enrichments.replace('\n','').replace(' ','')
print enrichments
results = CouchDBJobEnqueue().queue_collection("26094",
30000,
reenrich,
enrichments
)
print results
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,118 | ucldc/harvester | refs/heads/master | /harvester/fetcher/controller.py | # -*- coding: utf-8 -*-
import os
import tempfile
import urlparse
import datetime
import uuid
import json
import codecs
import boto3
from email.mime.text import MIMEText
import logbook
from logbook import FileHandler
import dplaingestion.couch
from ..collection_registry_client import Collection
from .. import config
from .fetcher import Fetcher
from .fetcher import NoRecordsFetchedException
from .oai_fetcher import OAIFetcher
from .solr_fetcher import SolrFetcher
from .solr_fetcher import PySolrQueryFetcher
from .solr_fetcher import RequestsSolrFetcher
from .marc_fetcher import MARCFetcher
from .marc_fetcher import AlephMARCXMLFetcher
from .nuxeo_fetcher import UCLDCNuxeoFetcher
from .oac_fetcher import OAC_XML_Fetcher
from .oac_fetcher import OAC_JSON_Fetcher
from .cmis_atom_feed_fetcher import CMISAtomFeedFetcher
from .flickr_fetcher import Flickr_Fetcher
from .youtube_fetcher import YouTube_Fetcher
from .xml_fetcher import XML_Fetcher
from .emuseum_fetcher import eMuseum_Fetcher
from .ucd_json_fetcher import UCD_JSON_Fetcher
from .ia_fetcher import IA_Fetcher
from .preservica_api_fetcher import PreservicaFetcher
EMAIL_RETURN_ADDRESS = os.environ.get('EMAIL_RETURN_ADDRESS',
'example@example.com')
HARVEST_TYPES = {
'OAI': OAIFetcher,
'OAJ': OAC_JSON_Fetcher,
'OAC': OAC_XML_Fetcher,
'SLR': SolrFetcher,
'MRC': MARCFetcher,
'NUX': UCLDCNuxeoFetcher,
'ALX': AlephMARCXMLFetcher,
'SFX': PySolrQueryFetcher,
'UCB': RequestsSolrFetcher, # Now points to more generic
# class, accepts parameters
# from extra data field
'PRE': CMISAtomFeedFetcher, # 'Preservica CMIS Atom Feed'),
'FLK': Flickr_Fetcher, # All public photos fetcher
'YTB': YouTube_Fetcher, # by playlist id, use "uploads" list
'XML': XML_Fetcher,
'EMS': eMuseum_Fetcher,
'UCD': UCD_JSON_Fetcher,
'IAR': IA_Fetcher,
'PRA': PreservicaFetcher
}
class HarvestController(object):
'''Controller for the harvesting. Selects correct Fetcher for the given
collection, then retrieves records for the given collection and saves to
disk.
TODO: produce profile file
'''
campus_valid = [
'UCB', 'UCD', 'UCI', 'UCLA', 'UCM', 'UCR', 'UCSB', 'UCSC', 'UCSD',
'UCSF', 'UCDL'
]
dc_elements = [
'title', 'creator', 'subject', 'description', 'publisher',
'contributor', 'date', 'type', 'format', 'identifier', 'source',
'language', 'relation', 'coverage', 'rights'
]
bucket = 'ucldc-ingest'
tmpl_s3path = 'data-fetched/{cid}/{datetime_start}/'
def __init__(self,
user_email,
collection,
profile_path=None,
config_file=None,
**kwargs):
self.user_email = user_email # single or list
self.collection = collection
self.profile_path = profile_path
self.config_file = config_file
self._config = config.config(config_file)
self.couch_db_name = self._config.get('couchdb_dbname', None)
if not self.couch_db_name:
self.couch_db_name = 'ucldc'
self.couch_dashboard_name = self._config.get('couchdb_dashboard')
if not self.couch_dashboard_name:
self.couch_dashboard_name = 'dashboard'
cls_fetcher = HARVEST_TYPES.get(self.collection.harvest_type, None)
self.fetcher = cls_fetcher(self.collection.url_harvest,
self.collection.harvest_extra_data,
**kwargs)
self.logger = logbook.Logger('HarvestController')
self.dir_save = tempfile.mkdtemp('_' + self.collection.slug)
self.ingest_doc_id = None
self.ingestion_doc = None
self.couch = None
self.num_records = 0
self.datetime_start = datetime.datetime.now()
self.objset_page = 0
@property
def s3path(self):
return self.tmpl_s3path.format(
cid=self.collection.id,
datetime_start=self.datetime_start.strftime('%Y-%m-%d-%H%M'))
@staticmethod
def dt_json_handler(obj):
'''The json package cannot deal with datetimes.
Provide this serializer for datetimes.
'''
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
return json.JSONEncoder.default(obj)
@staticmethod
def jsonl(objset):
'''Return a JSONL string for a given set of python objects
'''
jsonl = ''
if isinstance(objset, dict):
objset = [objset]
for obj in objset:
jsonl += ''.join((json.dumps(
obj, default=HarvestController.dt_json_handler), '\n'))
return jsonl
def save_objset_s3(self, objset):
'''Save the objset to a bucket'''
if not hasattr(self, 's3'):
self.s3 = boto3.resource('s3')
body = HarvestController.jsonl(objset)
bucket = self.s3.Bucket('ucldc-ingest')
key = ''.join((self.s3path, 'page-{}.jsonl'.format(self.objset_page)))
self.objset_page += 1
bucket.put_object(Body=body, Key=key)
def save_objset(self, objset):
'''Save an object set to disk. If it is a single object, wrap in a
list to be uniform'''
filename = os.path.join(self.dir_save, str(uuid.uuid4()))
if not type(objset) == list:
objset = [objset]
with open(filename, 'w') as foo:
foo.write(
json.dumps(
objset, default=HarvestController.dt_json_handler))
def create_ingest_doc(self):
'''Create the DPLA style ingest doc in couch for this harvest session.
Update with the current information. Status is running'''
self.couch = dplaingestion.couch.Couch(
config_file=self.config_file,
dpla_db_name=self.couch_db_name,
dashboard_db_name=self.couch_dashboard_name)
uri_base = "http://localhost:" + self._config['akara_port']
self.ingest_doc_id = self.couch._create_ingestion_document(
self.collection.provider, uri_base, self.profile_path,
self.collection.dpla_profile_obj['thresholds'])
self.ingestion_doc = self.couch.dashboard_db[self.ingest_doc_id]
kwargs = {
"fetch_process/status": "running",
"fetch_process/data_dir": self.dir_save,
"fetch_process/start_time": datetime.datetime.now().isoformat(),
"fetch_process/end_time": None,
"fetch_process/error": None,
"fetch_process/total_items": None,
"fetch_process/total_collections": None
}
try:
self.couch.update_ingestion_doc(self.ingestion_doc, **kwargs)
except Exception as e:
self.logger.error("Error updating ingestion doc %s in %s" %
(self.ingestion_doc["_id"], __name__))
raise e
return self.ingest_doc_id
def update_ingest_doc(self,
status,
error_msg=None,
items=None,
num_coll=None):
'''Update the ingest doc with status'''
if not items:
items = self.num_records
if status == 'error' and not error_msg:
raise ValueError('If status is error please add an error_msg')
kwargs = {
"fetch_process/status": status,
"fetch_process/error": error_msg,
"fetch_process/end_time": datetime.datetime.now().isoformat(),
"fetch_process/total_items": items,
"fetch_process/total_collections": num_coll
}
if not self.ingestion_doc:
self.create_ingest_doc()
try:
self.couch.update_ingestion_doc(self.ingestion_doc, **kwargs)
except Exception as e:
self.logger.error("Error updating ingestion doc %s in %s" %
(self.ingestion_doc["_id"], __name__))
raise e
def _add_registry_data(self, obj):
'''Add the registry based data to the harvested object.
'''
# get base registry URL
url_tuple = urlparse.urlparse(self.collection.url)
base_url = ''.join((url_tuple.scheme, '://', url_tuple.netloc))
self.collection['@id'] = self.collection.url
self.collection['id'] = self.collection.url.strip('/').rsplit('/',
1)[1]
self.collection['ingestType'] = 'collection'
self.collection['title'] = self.collection.name
if 'collection' in obj:
# save before hammering
obj['source_collection_name'] = obj['collection']
obj['collection'] = dict(self.collection)
campus = []
for c in self.collection.get('campus', []):
c.update({'@id': ''.join((base_url, c['resource_uri']))})
campus.append(c)
obj['collection']['campus'] = campus
repository = []
for r in self.collection['repository']:
r.update({'@id': ''.join((base_url, r['resource_uri']))})
repository.append(r)
obj['collection']['repository'] = repository
# in future may be more than one
obj['collection'] = [obj['collection']]
return obj
def harvest(self):
'''Harvest the collection'''
self.logger.info(' '.join((
'Starting harvest for:',
str(self.user_email),
self.collection.url,
str(self.collection['campus']),
str(self.collection['repository']))))
self.num_records = 0
next_log_n = interval = 100
for objset in self.fetcher:
if isinstance(objset, list):
self.num_records += len(objset)
# TODO: use map here
for obj in objset:
self._add_registry_data(obj)
else:
self.num_records += 1
self._add_registry_data(objset)
self.save_objset(objset)
self.save_objset_s3(objset)
if self.num_records >= next_log_n:
self.logger.info(' '.join((str(self.num_records),
'records harvested')))
if self.num_records < 10000 and \
self.num_records >= 10 * interval:
interval = 10 * interval
next_log_n += interval
if self.num_records == 0:
raise NoRecordsFetchedException
msg = ' '.join((str(self.num_records), 'records harvested'))
self.logger.info(msg)
return self.num_records
def parse_args():
import argparse
parser = argparse.ArgumentParser(description='Harvest a collection')
parser.add_argument('user_email', type=str, nargs='?', help='user email')
parser.add_argument(
'url_api_collection',
type=str,
nargs='?',
help='URL for the collection Django tastypie api resource')
return parser.parse_args()
def get_log_file_path(collection_slug):
'''Get the log file name for the given collection, start time and
environment
'''
log_file_dir = os.environ.get('DIR_HARVESTER_LOG',
os.path.join(
os.environ.get('HOME', '.'), 'log'))
log_file_name = '-'.join(
('harvester', collection_slug,
datetime.datetime.now().strftime('%Y%m%d-%H%M%S'), '.log'))
return os.path.join(log_file_dir, log_file_name)
def create_mimetext_msg(mail_from, mail_to, subject, message):
msg = MIMEText(message)
msg['Subject'] = str(subject)
msg['From'] = mail_from
msg['To'] = mail_to if type(mail_to) == str else ', '.join(mail_to)
return msg
def main(user_email,
url_api_collection,
log_handler=None,
mail_handler=None,
dir_profile='profiles',
profile_path=None,
config_file=None,
**kwargs):
'''Executes a harvest with given parameters.
Returns the ingest_doc_id, directory harvest saved to and number of
records.
'''
if not config_file:
config_file = os.environ.get('DPLA_CONFIG_FILE', 'akara.ini')
num_recs = -1
my_mail_handler = None
if not mail_handler:
my_mail_handler = logbook.MailHandler(
EMAIL_RETURN_ADDRESS, user_email, level='ERROR', bubble=True)
my_mail_handler.push_application()
mail_handler = my_mail_handler
try:
collection = Collection(url_api_collection)
except Exception as e:
msg = 'Exception in Collection {}, init {}'.format(url_api_collection,
str(e))
logbook.error(msg)
raise e
if not (collection['harvest_type'] in HARVEST_TYPES):
msg = 'Collection {} wrong type {} for harvesting. Harvest type {} \
is not in {}'.format(url_api_collection,
collection['harvest_type'],
collection['harvest_type'],
HARVEST_TYPES.keys())
logbook.error(msg)
raise ValueError(msg)
mail_handler.subject = "Error during harvest of " + collection.url
my_log_handler = None
if not log_handler: # can't init until have collection
my_log_handler = FileHandler(get_log_file_path(collection.slug))
my_log_handler.push_application()
logger = logbook.Logger('HarvestMain')
msg = 'Init harvester next. Collection:{}'.format(collection.url)
logger.info(msg)
# email directly
mimetext = create_mimetext_msg(EMAIL_RETURN_ADDRESS, user_email, ' '.join(
('Starting harvest for ', collection.slug)), msg)
try: # TODO: request more emails from AWS
mail_handler.deliver(mimetext, 'mredar@gmail.com')
except:
pass
logger.info('Create DPLA profile document')
if not profile_path:
profile_path = os.path.abspath(
os.path.join(dir_profile, collection.id + '.pjs'))
with codecs.open(profile_path, 'w', 'utf8') as pfoo:
pfoo.write(collection.dpla_profile)
logger.info('DPLA profile document : ' + profile_path)
harvester = None
try:
harvester = HarvestController(
user_email,
collection,
profile_path=profile_path,
config_file=config_file,
**kwargs)
except Exception as e:
import traceback
msg = 'Exception in harvester init: type: {} TRACE:\n{}'.format(
type(e), traceback.format_exc())
logger.error(msg)
raise e
logger.info('Create ingest doc in couch')
ingest_doc_id = harvester.create_ingest_doc()
logger.info('Ingest DOC ID: ' + ingest_doc_id)
logger.info('Start harvesting next')
num_recs = harvester.harvest()
msg = ''.join(('Finished harvest of ', collection.slug, '. ',
str(num_recs), ' records harvested.'))
logger.info(msg)
logger.debug('-- get a new harvester --')
harvester = HarvestController(
user_email,
collection,
profile_path=profile_path,
config_file=config_file,
**kwargs)
harvester.ingest_doc_id = ingest_doc_id
harvester.couch = dplaingestion.couch.Couch(
config_file=harvester.config_file,
dpla_db_name=harvester.couch_db_name,
dashboard_db_name=harvester.couch_dashboard_name)
harvester.ingestion_doc = harvester.couch.dashboard_db[ingest_doc_id]
try:
harvester.update_ingest_doc('complete', items=num_recs, num_coll=1)
logger.debug('updated ingest doc!')
except Exception as e:
import traceback
error_msg = ''.join(("Error while harvesting: type-> ", str(type(e)),
" TRACE:\n" + str(traceback.format_exc())))
logger.error(error_msg)
harvester.update_ingest_doc(
'error', error_msg=error_msg, items=num_recs)
raise e
if my_log_handler:
my_log_handler.pop_application()
if my_mail_handler:
my_mail_handler.pop_application()
return ingest_doc_id, num_recs, harvester.dir_save, harvester
__all__ = (Fetcher, NoRecordsFetchedException, HARVEST_TYPES)
if __name__ == '__main__':
args = parse_args()
main(args.user_email, args.url_api_collection)
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,119 | ucldc/harvester | refs/heads/master | /setup.py | import os
import sys
import subprocess
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='UCLDC Harvester',
version='0.8.1',
packages=['harvester', 'harvester.fetcher', 'harvester.post_processing'],
include_package_data=True,
license='BSD License - see LICENSE file',
description='harvester code for the UCLDC project',
long_description=read('README.md'),
author='Mark Redar',
author_email='mark.redar@ucop.edu',
classifiers=[
'Environment :: Web Environment',
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
dependency_links=[
'https://github.com/zepheira/amara/archive/master.zip#egg=amara',
'https://github.com/zepheira/akara/archive/master.zip#egg=akara',
'https://github.com/ucldc/md5s3stash/archive/legacy_harvester.zip#egg=md5s3stash',
'https://github.com/ucldc/pynux/archive/master.zip#egg=pynux',
'https://raw.githubusercontent.com/ucldc/facet_decade/master/facet_decade.py#egg=facet_decade-2.0',
'https://pypi.python.org/packages/source/p/pilbox/pilbox-1.0.3.tar.gz#egg=pilbox',
'https://github.com/mredar/redis-collections/archive/master.zip#egg=redis-collections',
'https://github.com/mredar/nuxeo-calisphere/archive/master.zip#egg=UCLDC-Deep-Harvester',
'https://github.com/tingletech/mediajson/archive/master.zip#egg=mediajson',
# 'https://github.com/mredar/sickle/archive/master.zip#egg=Sickle',
# 'https://github.com/nvie/rq/archive/4875331b60ddf8ddfe5b374ec75c938eb9749602.zip#egg=rq',
],
install_requires=[
'Sickle==0.6.3',
'argparse==1.2.1',
'lxml==3.3.5',
'requests==2.20.0',
'solrpy==0.9.7',
'pysolr==3.3.0',
'pilbox==1.0.3',
'wsgiref==0.1.2',
'Logbook==0.6.0',
'amara==2.0.0',
'akara==2.0.0a4',
'python-dateutil==2.2',
'CouchDB==0.9',
'redis>=2.10.1',
'rq==0.13.0',
'boto==2.49.0',
'md5s3stash',
'pymarc==3.0.4',
'facet_decade==2.0',
'redis_collections==0.1.7',
'rdflib==4.2.2',
'xmljson==0.2.0',
'UCLDC-Deep-Harvester',
'boto3==1.9.160',
'pynux',
'mediajson'
],
test_suite='test',
tests_require=['mock>=1.0.1', 'httpretty==0.9.5', ],
)
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'ansible'])
#pip_main(['install', 'ansible'])
#pip_main(['install',
#'git+https://github.com/ucldc/pynux.git@b539959ac11caa6fec06f59a0b3768d97bec2693'])
###pip_main(['install',
### 'git+ssh://git@bitbucket.org/mredar/dpla-ingestion.git@ucldc'])
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,120 | ucldc/harvester | refs/heads/master | /test/test_flickr_fetcher.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from unittest import TestCase
import harvester.fetcher as fetcher
from test.utils import DIR_FIXTURES
from test.utils import LogOverrideMixin
from mypretty import httpretty
# import httpretty
class FlickrFetcherTestCase(LogOverrideMixin, TestCase):
'''Test the fetcher for the Flickr API.'''
@httpretty.activate
def testInit(self):
'''Basic tdd start'''
url = 'https://example.edu'
user_id = 'test@Nuser'
page_size = 10
url_first = fetcher.Flickr_Fetcher.url_get_user_photos_template.format(
api_key='boguskey', user_id=user_id, per_page=page_size, page=1)
httpretty.register_uri(
httpretty.GET,
url_first,
body=open(DIR_FIXTURES + '/flickr-public-photos-1.xml').read())
h = fetcher.Flickr_Fetcher(url, user_id, page_size=page_size)
self.assertEqual(h.url_base, url)
self.assertEqual(h.user_id, user_id)
self.assertEqual(h.page_size, 10)
self.assertEqual(h.page_current, 1)
self.assertEqual(h.doc_current, 0)
self.assertEqual(h.docs_fetched, 0)
self.assertEqual(h.url_get_user_photos_template,
'https://api.flickr.com/services/rest/'
'?api_key={api_key}&user_id={user_id}&per_page'
'={per_page}&method='
'flickr.people.getPublicPhotos&page={page}')
self.assertEqual(h.api_key, 'boguskey')
self.assertEqual(h.url_current, url_first)
self.assertEqual(h.docs_total, 10)
self.assertEqual(h.url_get_photo_info_template,
'https://api.flickr.com/services/rest/'
'?api_key={api_key}&method='
'flickr.photos.getInfo&photo_id={photo_id}')
@httpretty.activate
def test_page_range(self):
'''Need to break this up into pages, to run as different jobs.'''
url = 'https://example.edu'
user_id = 'testuser'
page_size = 3
page_range = '2,3'
url_first = fetcher.Flickr_Fetcher.url_get_user_photos_template.format(
api_key='boguskey', user_id=user_id, per_page=page_size, page=1)
httpretty.register_uri(
httpretty.GET,
url_first,
body=open(DIR_FIXTURES + '/flickr-public-photos-1.xml').read())
h = fetcher.Flickr_Fetcher(url, user_id, page_size=page_size,
page_range=page_range)
self.assertEqual(h.page_start, 2)
self.assertEqual(h.page_end, 3)
self.assertEqual(h.page_current, 2)
self.assertEqual(h.docs_total, 6)
h = fetcher.Flickr_Fetcher(url, user_id, page_size=page_size,
page_range='3,5')
self.assertEqual(h.page_start, 3)
self.assertEqual(h.page_end, 4)
self.assertEqual(h.page_current, 3)
self.assertEqual(h.docs_total, 4)
@httpretty.activate
def test_fetching_range(self):
url = 'https://example.edu'
user_id = 'testuser'
page_size = 3
url_first = fetcher.Flickr_Fetcher.url_get_user_photos_template.format(
api_key='boguskey', user_id=user_id, per_page=page_size, page=1)
# Ugly but works
httpretty.register_uri(
httpretty.GET,
url_first,
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-public-photos-1.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-public-photos-1.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-public-photos-1.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
]
)
h = fetcher.Flickr_Fetcher(url, user_id, page_size=page_size,
page_range='3,5')
h.doc_current = 10
self.assertRaises(ValueError, h.next)
h.docs_fetched = 4
h.doc_current = 4
self.assertRaises(StopIteration, h.next)
h.docs_fetched = 2
h.doc_current = 2
h.page_current = 5
self.assertRaises(StopIteration, h.next)
h = fetcher.Flickr_Fetcher(url, user_id, page_size=page_size,
page_range='3,5')
total = 0
all_objs = []
for objs in h:
total += len(objs)
all_objs.extend(objs)
self.assertEqual(total, 4)
self.assertEqual(len(all_objs), 4)
@httpretty.activate
def test_fetching(self):
url = 'https://example.edu'
user_id = 'testuser'
page_size = 10
url_first = fetcher.Flickr_Fetcher.url_get_user_photos_template.format(
api_key='boguskey', user_id=user_id, per_page=page_size, page=1)
# Ugly but works
httpretty.register_uri(
httpretty.GET,
url_first,
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-public-photos-1.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-public-photos-1.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-public-photos-2.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-public-photos-3.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-public-photos-4.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
])
h = fetcher.Flickr_Fetcher(url, user_id, page_size=page_size)
h.doc_current = 10
self.assertRaises(ValueError, h.next)
h.docs_fetched = 10
self.assertRaises(StopIteration, h.next)
h = fetcher.Flickr_Fetcher(url, user_id, page_size=page_size)
total = 0
all_objs = []
for objs in h:
total += len(objs)
all_objs.extend(objs)
self.assertEqual(total, 10)
self.assertEqual(len(all_objs), 10)
photo_obj = all_objs[0]
key_list_values = {
'description': {
'text':
'PictionID:56100666 - Catalog:C87-047-040.tif - '
'Title:Ryan Aeronautical Negative Collection Image - '
'Filename:C87-047-040.tif - - Image from the Teledyne Ryan '
'Archives, donated to SDASM in the 1990s. Many of these '
'images are from Ryan\'s UAV program-----Please Tag these '
'images so that the information can be permanently stored '
'with the digital file.---Repository: <a href='
'"http://www.sandiegoairandspace.org/library/stillimages.'
'html" rel="nofollow">San Diego Air and Space Museum </a>'
},
'isfavorite': '0',
'views': '499',
'farm': '5',
'people': {
'haspeople': '0',
'text': None
},
'visibility': {
'text': None,
'isfamily': '0',
'isfriend': '0',
'ispublic': '1'
},
'originalformat': 'jpg',
'owner': {
'text': None,
'nsid': "49487266@N07",
'username': "San Diego Air & Space Museum Archives",
'realname': "SDASM Archives",
'location': "",
'iconserver': "4070",
'iconfarm': "5",
'path_alias': "sdasmarchives",
},
'rotation': '0',
'id': '34394586825',
'dates': {
'text': None,
'lastupdate': '1493683351',
'posted': '1493683350',
'taken': '2017-05-01 17:02:30',
'takengranularity': '0',
'takenunknown': '1',
},
'originalsecret': 'd46e9b19cc',
'license': '7',
'title': {
'text': 'Ryan Aeronautical Image'
},
'media': 'photo',
'notes': [{
'x': '10',
'authorname': 'Bees',
'text': 'foo',
'w': '50',
'author': '12037949754@N01',
'y': '10',
'h': '50',
'id': '313'
}],
'tags': [{
'raw': 'woo yay',
'text': 'wooyay',
'id': '1234',
'author': '12037949754@N01'
}, {
'raw': 'hoopla',
'text': 'hoopla',
'id': '1235',
'author': '12037949754@N01'
}],
'publiceditability': {
'text': None,
'cancomment': '1',
'canaddmeta': '1'
},
'comments': {
'text': '0'
},
'server': '4169',
'dateuploaded': '1493683350',
'secret': '375e0b1706',
'safety_level': '0',
'urls': [{
'text':
'https://www.flickr.com/photos/sdasmarchives/34394586825/',
'type': 'photopage'
}],
'usage': {
'text': None,
'canblog': '0',
'candownload': '1',
'canprint': '0',
'canshare': '1'
},
'editability': {
'text': None,
'cancomment': '0',
'canaddmeta': '0'
},
}
self.assertEqual(len(photo_obj.keys()), len(key_list_values.keys()))
for k, v in key_list_values.items():
self.assertEqual(photo_obj[k], v)
@httpretty.activate
def test_photoset_fetching(self):
url = 'https://example.edu'
user_id = 'testphotoset'
page_size = 6
url_first = fetcher.Flickr_Fetcher.url_get_photoset_template.format(
api_key='boguskey', user_id=user_id, per_page=page_size, page=1)
# Ugly but works
httpretty.register_uri(
httpretty.GET,
url_first,
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photoset-1.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photoset-1.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photoset-2.xml')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/flickr-photo-info-0.xml').read(
),
status=200),
])
h = fetcher.Flickr_Fetcher(url, user_id, page_size=page_size)
h.doc_current = 6
self.assertRaises(ValueError, h.next)
h.docs_fetched = 6
self.assertRaises(StopIteration, h.next)
h = fetcher.Flickr_Fetcher(url, user_id, page_size=page_size)
total = 0
all_objs = []
for objs in h:
total += len(objs)
all_objs.extend(objs)
self.assertEqual(total, 6)
self.assertEqual(len(all_objs), 6)
photo_obj = all_objs[0]
key_list_values = {
'description': {
'text':
'PictionID:56100666 - Catalog:C87-047-040.tif - '
'Title:Ryan Aeronautical Negative Collection Image - '
'Filename:C87-047-040.tif - - Image from the Teledyne Ryan '
'Archives, donated to SDASM in the 1990s. Many of these '
'images are from Ryan\'s UAV program-----Please Tag these '
'images so that the information can be permanently stored '
'with the digital file.---Repository: <a href='
'"http://www.sandiegoairandspace.org/library/stillimages.'
'html" rel="nofollow">San Diego Air and Space Museum </a>'
},
'isfavorite': '0',
'views': '499',
'farm': '5',
'people': {
'haspeople': '0',
'text': None
},
'visibility': {
'text': None,
'isfamily': '0',
'isfriend': '0',
'ispublic': '1'
},
'originalformat': 'jpg',
'owner': {
'text': None,
'nsid': "49487266@N07",
'username': "San Diego Air & Space Museum Archives",
'realname': "SDASM Archives",
'location': "",
'iconserver': "4070",
'iconfarm': "5",
'path_alias': "sdasmarchives",
},
'rotation': '0',
'id': '34394586825',
'dates': {
'text': None,
'lastupdate': '1493683351',
'posted': '1493683350',
'taken': '2017-05-01 17:02:30',
'takengranularity': '0',
'takenunknown': '1',
},
'originalsecret': 'd46e9b19cc',
'license': '7',
'title': {
'text': 'Ryan Aeronautical Image'
},
'media': 'photo',
'notes': [{
'x': '10',
'authorname': 'Bees',
'text': 'foo',
'w': '50',
'author': '12037949754@N01',
'y': '10',
'h': '50',
'id': '313'
}],
'tags': [{
'raw': 'woo yay',
'text': 'wooyay',
'id': '1234',
'author': '12037949754@N01'
}, {
'raw': 'hoopla',
'text': 'hoopla',
'id': '1235',
'author': '12037949754@N01'
}],
'publiceditability': {
'text': None,
'cancomment': '1',
'canaddmeta': '1'
},
'comments': {
'text': '0'
},
'server': '4169',
'dateuploaded': '1493683350',
'secret': '375e0b1706',
'safety_level': '0',
'urls': [{
'text':
'https://www.flickr.com/photos/sdasmarchives/34394586825/',
'type': 'photopage'
}],
'usage': {
'text': None,
'canblog': '0',
'candownload': '1',
'canprint': '0',
'canshare': '1'
},
'editability': {
'text': None,
'cancomment': '0',
'canaddmeta': '0'
},
}
self.assertEqual(len(photo_obj.keys()), len(key_list_values.keys()))
for k, v in key_list_values.items():
self.assertEqual(photo_obj[k], v)
# Copyright © 2017, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,121 | ucldc/harvester | refs/heads/master | /scripts/queue_collections_from_file_reenrich.py | '''For collection ids in the file, queue the passed in enrichments
'''
import sys
import argparse
import Queue
import threading
from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
import harvester.post_processing.enrich_existing_couch_doc
def q_collection(collection_id, enrichment):
timeout = 10000
print "ENRICH {} with {}".format(collection_id, enrichment)
ENQ = CouchDBJobEnqueue()
ENQ.queue_collection(collection_id, timeout,
harvester.post_processing.enrich_existing_couch_doc.main,
enrichment
)
def get_id_on_queue_and_run(queue, enrichment):
'''Pulls cid from queue and runs q_collection on the id'''
cid = queue.get_nowait()
while cid:
q_collection(cid, enrichment)
cid = queue.get_nowait()
def main(cid_file, enrichment, num_threads):
queue = Queue.Queue()
for l in open(args.collection_id_file):
cid = l.strip()
#fill q, not parallel yet
queue.put(cid)
# setup threads, run on objects in queue....
# need wrapper callable that takes queue, consumes and call q_collection
threads = [threading.Thread(target=get_id_on_queue_and_run,
args=(queue, enrichment)) for i in range(num_threads)]
print "THREADS:{} starting next".format(threads)
for t in threads:
t.start()
if __name__=='__main__':
parser = argparse.ArgumentParser(
description='run an Akara enrichment chain on documents in a \
collection.')
parser.add_argument('collection_id_file',
help='File with registry ids for enrichment')
parser.add_argument('enrichment', help='enrichment chain to run')
parser.add_argument('--threads', nargs='?', default=1, type=int,
help='number of threads to run on (default:1)')
parser.add_argument('--rq_queue',
help='Override queue for jobs, normal-stage is default')
args = parser.parse_args()
print(args.collection_id_file)
print "ENRICH FILE:{}".format(args.enrichment)
with open(args.enrichment) as enrichfoo:
enrichments = enrichfoo.read()
main(args.collection_id_file, enrichments, args.threads)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,122 | ucldc/harvester | refs/heads/master | /scripts/report_harvested_to_solr.py | import sys, os
import argparse
import solr
from harvester.collection_registry_client import Collection
import csv
import codecs
import cStringIO
import datetime
from harvester.couchdb_init import get_couchdb
from harvester.fetcher import OAC_XML_Fetcher
py_version = sys.version_info
if py_version.major == 2 and py_version.minor == 7 and py_version.micro > 8:
#disable ssl verification
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
SOLR_URL = os.getenv('UCLDC_SOLR_URL',
'https://ucldc-solr-stage.elasticbeanstalk.com/solr/')
COUCHDB_URL = os.getenv('COUCHDB_URL',
'https://51.10.100.133/couchdb')
'https://ucldc-solr-stage.elasticbeanstalk.com/solr/query?q=*:*&rows=0&facet=true&facet.field=collection_url&facet.limit=1000'
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
Needed for unicode input, sure hope they fixed this in py 3
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
def get_indexed_collection_list(SOLR):
'''Use the facet query to extract the collection urls for
collections in index.
Returns list of tuples (collection_url, #in coll)
'''
query_results = SOLR(q='*:*',
rows=0,
facet='true',
facet_limit='-1',
facet_field=['collection_url'],
)
collection_urls = query_results.facet_counts['facet_fields']['collection_url']
return [(c_url, num) for c_url, num in collection_urls.items()]
def get_couch_count(cdb, cid):
view_name='_design/all_provider_docs/_view/by_provider_name_count'
results = cdb.view(view_name,
key=c.id)
for row in results:
return row.value
if __name__=="__main__":
parser = argparse.ArgumentParser(
description='Make csv report of indexed collections')
parser.add_argument('auth_token', help='Authentication token')
parser.add_argument('--solr_url', help='Solr index url')
parser.add_argument('--couchdb_url', help='CouchDB url')
args = parser.parse_args()
solr_url = args.solr_url if args.solr_url else SOLR_URL
print "SOLR_URL:{}".format(solr_url)
SOLR = solr.SearchHandler(
solr.Solr(
solr_url,
post_headers = {
'X-Authentication-Token': args.auth_token,
},
),
"/query"
)
if args.couchdb_url:
cdb = get_couchdb(url_couchdb=couchdb_url, dbname='ucldc')
else:
cdb = get_couchdb(dbname='ucldc')
collections = get_indexed_collection_list(SOLR)
date_to_minute = datetime.datetime.now().strftime('%Y%m%d-%H%M')
fname = 'indexed_collections-{}.csv'.format(date_to_minute)
with open(fname, 'wb') as csvfile:
csvwriter = UnicodeWriter(csvfile)
csvwriter.writerow(('Collection Name', 'Collection URL',
'Number in index', 'Number in couchdb', 'Number in OAC',
'Couch missing in solr', 'OAC missing in couch',
'Repository Name', 'Repository URL',
'Campus'))
for c_url, num in collections:
try:
c = Collection(c_url)
except ValueError, e:
print "NO COLLECTION FOR :{}".format(c_url)
continue
couch_count = get_couch_count(cdb, c.id)
solr_equal_couch = False
if couch_count == num:
solr_equal_couch = True
oac_num = None
couch_equal_oac = None
if c.harvest_type == 'OAC':
fetcher = OAC_XML_Fetcher(c.url_harvest, c.harvest_extra_data)
oac_num = fetcher.totalDocs
if couch_count == oac_num:
couch_equal_oac = True
else:
couch_equal_oac = False
csvwriter.writerow((c['name'], c_url, str(num), str(couch_count),
str(oac_num), str(solr_equal_couch), str(couch_equal_oac),
c.repository[0]['name'] if len(c.repository) else '',
c.repository[0]['resource_uri']if len(c.repository) else '',
c.campus[0]['name'] if len(c.campus) else ''))
print 'Created {}'.format(fname)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,123 | ucldc/harvester | refs/heads/master | /test/test_copy_couchdb_fields.py | # test copying from one couchdb to another
# specify list of field names in "/" path style
# specify doc id
# specify source & dest couchdb
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,124 | ucldc/harvester | refs/heads/master | /scripts/queue_deep_harvest_single_object_with_components.py | #! /bin/env python
# -*- coding: utf-8 -*-
import sys
import logbook
from rq import Queue
from redis import Redis
from harvester.config import parse_env
JOB_TIMEOUT = 345600 # 96 hrs
def queue_deep_harvest(redis_host,
redis_port,
redis_password,
redis_timeout,
rq_queue,
path,
replace=False,
timeout=JOB_TIMEOUT):
'''Queue job onto RQ queue'''
rQ = Queue(
rq_queue,
connection=Redis(
host=redis_host,
port=redis_port,
password=redis_password,
socket_connect_timeout=redis_timeout))
job = rQ.enqueue_call(
func='s3stash.stash_single_object.main',
kwargs=dict(path=path, replace=replace),
timeout=timeout)
return job
def main(path, log_handler=None, rq_queue='normal-stage',
timeout=JOB_TIMEOUT, replace=False):
''' Queue a deep harvest of a nuxeo object including any components on a worker'''
if not log_handler:
log_handler = logbook.StderrHandler(level='DEBUG')
log_handler.push_application()
queue_deep_harvest(
config['redis_host'],
config['redis_port'],
config['redis_password'],
config['redis_connect_timeout'],
rq_queue=rq_queue,
path=path,
replace=replace,
timeout=timeout)
log_handler.pop_application()
def def_args():
import argparse
parser = argparse.ArgumentParser(
description='Queue a Nuxeo deep harvesting job for a single object including components')
parser.add_argument('user_email', type=str, help='user email')
parser.add_argument('rq_queue', type=str, help='RQ Queue to put job in')
parser.add_argument('path', type=str, help='Nuxeo path')
parser.add_argument(
'--replace',
action='store_true',
help='replace files on s3 if they already exist')
parser.add_argument('--job_timeout', type=int, default=JOB_TIMEOUT,
help='Timeout for the RQ job')
return parser
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args()
config = parse_env(None)
if not args.path or not args.rq_queue:
parser.print_help()
sys.exit(27)
if args.job_timeout:
job_timeout = args.job_timeout
else:
job_timeout = JOB_TIMEOUT
main(args.path, rq_queue=args.rq_queue, replace=args.replace,
timeout=job_timeout)
# Copyright © 2017, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,125 | ucldc/harvester | refs/heads/master | /harvester/grab_solr_index.py | # Use the ansible runnner to run the specific playbook
import os
import ansible_run_pb
def main():
dir_code = os.environ['DIR_CODE'] if 'DIR_CODE' in os.environ \
else \
os.path.join(os.path.join(os.environ.get('HOME', '~'),
'code/harvester'))
dir_code = os.path.abspath(dir_code)
dir_pb = os.path.join(dir_code, 'harvester')
playbook = os.path.join(dir_pb, 'grab-solr-index-playbook.yml')
inventory = os.path.join(dir_pb, 'host_inventory')
ansible_run_pb.main(playbook, inventory)
if __name__ == '__main__':
main()
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,126 | ucldc/harvester | refs/heads/master | /harvester/fetcher/ia_fetcher.py | # -*- coding: utf-8 -*-
import urllib
import json
from .fetcher import Fetcher
class IA_Fetcher(Fetcher):
'''A fetcher for the Internet Archive.
Put a dummy URL in harvesturl field such as 'https://example.edu'
In the 'extra_data' field, put in the Lucene-formatted search parameters
to return whatever body of records you want to constitute the Calisphere
collection. For example:
collection:environmentaldesignarchive AND subject:"edith heath"
Will return all content with subject "edith heath" from the Environmental
Design Archives collection. 'collection' is almost always a required field,
as it should correspond to the institution/library we are harvesting from.
All other metadata field searches are optional but available.
More search query help and example queries here:
https://archive.org/advancedsearch.php
'''
url_advsearch = 'https://archive.org/advancedsearch.php?' \
'q={search_query}&rows=500&page={page_current}&output=json'
def __init__(self, url_harvest, extra_data, **kwargs):
self.url_base = url_harvest
self.search_query = extra_data
self.page_current = 1
self.doc_current = 0
def next(self):
self.url_current = self.url_advsearch.format(
page_current=self.page_current, search_query=self.search_query)
search = urllib.urlopen(self.url_current).read()
results = json.loads(search)
self.doc_total = results["response"]["numFound"]
if self.doc_current >= self.doc_total:
if self.doc_current != self.doc_total:
raise ValueError(
"Number of documents fetched ({0}) doesn't match \
total reported by server ({1})".format(
self.doc_current, self.doc_total))
else:
raise StopIteration
docList = results['response']['docs']
if len(docList) == 0:
raise ValueError(
"No results for URL ({0}) -- Check search syntax".format(
self.searchURL))
else:
objset = []
for g in docList:
objset.append(g)
self.page_current += 1
self.doc_current += len(objset)
return objset
# Copyright © 2017, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,127 | ucldc/harvester | refs/heads/master | /test/fixtures/get-a-doc-from-couchdb-and-pickle.py | # OUT: Python shell history and tab completion are enabled.
from couchdb import Server
s=Server('https://54.84.142.143/couchdb/')
db=s['ucldc']
resp=db.changes(since=288000)
results=resp['results']
doc=db.get(results[0]['id'])
dir(doc)
# OUT: ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'id', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'rev', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
doc.keys()
# OUT: [u'_id', u'@id', u'_rev', u'ingestDate', u'ingestionSequence', u'isShownAt', u'sourceResource', u'@context', u'ingestType', u'dataProvider', u'originalRecord', u'id']
import pickle
pickled_doc=pickle.dumps(doc)
f=open('pickled_couchdb_doc','w')
pickle.dump(doc, f)
f.close()
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,128 | ucldc/harvester | refs/heads/master | /harvester/post_processing/run_transform_on_couchdb_docs.py | '''This allows running a bit of code on couchdb docs.
code should take a json python object, modify it and hand back to the code
Not quite that slick yet, need way to pass in code or make this a decorator
'''
import importlib
from harvester.collection_registry_client import Collection
from harvester.couchdb_init import get_couchdb
COUCHDB_VIEW = 'all_provider_docs/by_provider_name'
def run_on_couchdb_by_collection(func, collection_key=None):
'''If collection_key is none, trying to grab all of docs and modify
func is a function that takes a couchdb doc in and returns it modified.
(can take long time - not recommended)
Function should return new document or None if no changes made
'''
_couchdb = get_couchdb()
v = _couchdb.view(COUCHDB_VIEW, include_docs='true', key=collection_key) \
if collection_key else _couchdb.view(COUCHDB_VIEW,
include_docs='true')
doc_ids = []
n = 0
for r in v:
n += 1
doc_new = func(r.doc)
if doc_new and doc_new != doc:
_couchdb.save(doc_new)
doc_ids.append(r.doc['_id'])
if n % 100 == 0:
print '{} docs ran. Last doc:{}\n'.format(n, r.doc['_id'])
return doc_ids
def run_on_couchdb_doc(docid, func):
'''Run on a doc, by doc id'''
_couchdb = get_couchdb()
doc = _couchdb[docid]
mod_name, func_name = func.rsplit('.', 1)
fmod = importlib.import_module(mod_name)
ffunc = getattr(fmod, func_name)
doc_new = ffunc(doc)
if doc_new and doc_new != doc:
_couchdb.save(doc_new)
return True
return False
C_CACHE = {}
def update_collection_description(doc):
cjson = doc['originalRecord']['collection'][0]
# get collection description
if 'description' not in cjson:
if cjson['@id'] in C_CACHE:
c = C_CACHE[cjson['@id']]
else:
c = Collection(url_api=cjson['@id'])
C_CACHE[cjson['@id']] = c
description = c['description'] if c['description'] else c['name']
print('DOC: {} DESCRIP: {}'.format(
doc['_id'], c['description'].encode('utf8')))
doc['originalRecord']['collection'][0]['description'] = description
doc['sourceResource']['collection'][0]['description'] = description
return doc
def add_rights_and_type_to_collection(doc):
cjson = doc['originalRecord']['collection'][0]
# get collection description
if cjson['@id'] in C_CACHE:
c = C_CACHE[cjson['@id']]
else:
c = Collection(url_api=cjson['@id'])
C_CACHE[cjson['@id']] = c
doc['originalRecord']['collection'][0]['rights_status'] = c['rights_status']
doc['originalRecord']['collection'][0]['rights_statement'] = c['rights_statement']
doc['originalRecord']['collection'][0]['dcmi_type']=c['dcmi_type']
if 'collection' in doc['sourceResource']:
doc['sourceResource']['collection'][0]['rights_status'] = c['rights_status']
doc['sourceResource']['collection'][0]['rights_statement'] = c['rights_statement']
doc['sourceResource']['collection'][0]['dcmi_type'] = c['dcmi_type']
else:
doc['sourceResource']['collection'] = doc['originalRecord']['collection']
return doc
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,129 | ucldc/harvester | refs/heads/master | /harvester/fetcher/youtube_fetcher.py | # -*- coding: utf-8 -*-
import os
import urllib
import json
from .fetcher import Fetcher
class YouTube_Fetcher(Fetcher):
'''A fetcher for the youtube API.
Find and put one of the IDs in the 'extra_data' field, depending on the type of harvest you want:
PLAYLIST ID (for harvesting from a single playlist): Put a dummy URL in harvest url field. Navigate to the YouTube user’s home page and click “playlists”. Find the playlist you wish to harvest and click “Play All”. The URL of the resulting page will include the Playlist ID following the “list=” parameter, beginning with PL. Example: https://www.youtube.com/watch?v=CNCmIMeASk0&list=PLiCFxUIHgTjXT_tJGE-h8V1PIMcr6FLXI
USER UPLOAD ID (for harvesting all videos from a user’s account): Put a dummy URL in harvest url field. Navigate to the video page for any video uploaded by the user. Beneath the video, click the hyperlinked username. DO NOT click the round image for the user, as this will take you to a separate user page. Clicking the hyperlinked username will take you to a URL with the user’s Channel ID after “/channel”, beginning with UC. Example: https://www.youtube.com/channel/UC4iOlcoyvdpGKda86Ih9M1w . To turn this into the user upload ID, replace the second letter “C” with a “U”--for the above example, you get UU4iOlcoyvdpGKda86Ih9M1w
VIDEO ID (for harvesting a single YouTube video): Put "http://single.edu" in the harvest url field to indicate single video harvesting, as this field requires a URL. Navigate to the video page; the URL will include the video ID following the "v=" parameter. Example:
https://www.youtube.com/watch?v=GCqS7DhJrzA
'''
url_playlistitems = 'https://www.googleapis.com/youtube/v3/playlistItems' \
'?key={api_key}&maxResults={page_size}&part=contentDetails&' \
'playlistId={playlist_id}&pageToken={page_token}'
url_video = 'https://www.googleapis.com/youtube/v3/videos?' \
'key={api_key}&part=snippet&id={video_ids}'
def __init__(self, url_harvest, extra_data, page_size=50, **kwargs):
self.url_base = url_harvest
self.playlist_id = extra_data
self.api_key = os.environ.get('YOUTUBE_API_KEY', 'boguskey')
self.page_size = page_size
self.playlistitems = {'nextPageToken': ''}
def next(self):
try:
nextPageToken = self.playlistitems['nextPageToken']
except KeyError as err:
raise StopIteration
# Single video harvesting, don't need playlist page
if self.url_base.lower() == 'http://single.edu':
video_items = json.loads(
urllib.urlopen(self.url_video.format(
api_key=self.api_key, video_ids=self.playlist_id)).read())['items']
# Delete nextPageToken to stop iteration
del self.playlistitems['nextPageToken']
return video_items
else:
self.playlistitems = json.loads(
urllib.urlopen(
self.url_playlistitems.format(
api_key=self.api_key,
page_size=self.page_size,
playlist_id=self.playlist_id,
page_token=nextPageToken)).read())
video_ids = [
i['contentDetails']['videoId'] for i in self.playlistitems['items']
]
video_items = json.loads(
urllib.urlopen(self.url_video.format(
api_key=self.api_key, video_ids=','.join(video_ids))).read())['items']
return video_items
# Copyright © 2017, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,130 | ucldc/harvester | refs/heads/master | /scripts/enq_date_fix.py | from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
from harvester.post_processing.run_transform_on_couchdb_docs import run_on_couchdb_doc
from harvester.post_processing.fix_repeated_displayDate import fix_repeated_date
import harvester
import sys
fname = sys.argv[1]
cid_list = [ x.strip() for x in open(fname).readlines()]
for cid in cid_list:
results = CouchDBJobEnqueue().queue_collection(
cid,
300,
run_on_couchdb_doc,
'harvester.post_processing.fix_repeated_displayDate.fix_repeated_date')
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,131 | ucldc/harvester | refs/heads/master | /test/test_youtube_fetcher.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from unittest import TestCase
import harvester.fetcher as fetcher
from test.utils import DIR_FIXTURES
from test.utils import LogOverrideMixin
from mypretty import httpretty
# import httpretty
class YouTubeFetcherTestCase(LogOverrideMixin, TestCase):
'''Test the fetcher for the youtube API.'''
@httpretty.activate
def testInit(self):
'''Basic tdd start'''
url = 'https://example.edu'
playlist_id = 'testplaylist'
page_size = 3
url_first = fetcher.YouTube_Fetcher.url_playlistitems.format(
api_key='boguskey',
page_size=page_size,
playlist_id=playlist_id,
page_token='')
httpretty.register_uri(
httpretty.GET,
url_first,
body=open(DIR_FIXTURES + '/flickr-public-photos-1.xml').read())
h = fetcher.YouTube_Fetcher(url, playlist_id, page_size=page_size)
self.assertEqual(h.url_base, url)
self.assertEqual(h.playlist_id, playlist_id)
self.assertEqual(h.api_key, 'boguskey')
self.assertEqual(h.page_size, page_size)
self.assertEqual(h.playlistitems, {'nextPageToken': ''})
self.assertEqual(
h.url_playlistitems,
'https://www.googleapis.com/youtube/v3/playlistItems'
'?key={api_key}&maxResults={page_size}&part=contentDetails&'
'playlistId={playlist_id}&pageToken={page_token}')
self.assertEqual(
h.url_video,
'https://www.googleapis.com/youtube/v3/videos?'
'key={api_key}&part=snippet&id={video_ids}'
)
@httpretty.activate
def test_fetching(self):
url = 'https://example.edu'
playlist_id = 'testplaylist'
page_size = 3
url_first = fetcher.YouTube_Fetcher.url_playlistitems.format(
api_key='boguskey',
page_size=page_size,
playlist_id=playlist_id,
page_token='')
url_vids = fetcher.YouTube_Fetcher.url_video
# Ugly but works
httpretty.register_uri(
httpretty.GET,
url_first,
responses=[
httpretty.Response(
body=open(DIR_FIXTURES +
'/youtube_playlist_with_next.json')
.read(),
status=200),
httpretty.Response(
body=open(DIR_FIXTURES + '/youtube_playlist_no_next.json')
.read(),
status=200),
])
httpretty.register_uri(
httpretty.GET,
url_vids,
body=open(DIR_FIXTURES + '/youtube_video.json').read(),
status=200)
h = fetcher.YouTube_Fetcher(url, playlist_id, page_size=page_size)
vids = []
for v in h:
vids.extend(v)
self.assertEqual(len(vids), 6)
self.assertEqual(vids[0], {
u'contentDetails': {
u'definition': u'sd',
u'projection': u'rectangular',
u'caption': u'false',
u'duration': u'PT19M35S',
u'licensedContent': True,
u'dimension': u'2d'
},
u'kind': u'youtube#video',
u'etag':
u'"m2yskBQFythfE4irbTIeOgYYfBU/-3AtVAYcRLEynWZprpf0OGaY8zo"',
u'id': u'0Yx8zrbsUu8'
})
@httpretty.activate
def test_single_fetching(self):
url = 'http://single.edu'
playlist_id = 'PLwtrWl_IBMJtjP5zMk6dVR-BRjzKqCPOM'
url_vids = fetcher.YouTube_Fetcher.url_video
httpretty.register_uri(
httpretty.GET,
url_vids,
responses=[
httpretty.Response(
body=open(DIR_FIXTURES + '/youtube_single_video.json').read(),
status=200)
])
h = fetcher.YouTube_Fetcher(url, playlist_id)
vids = []
for v in h:
vids.extend(v)
self.assertEqual(len(vids), 1)
self.assertEqual(vids[0], {
u'contentDetails': {
u'definition': u'sd',
u'projection': u'rectangular',
u'caption': u'false',
u'duration': u'PT19M35S',
u'licensedContent': True,
u'dimension': u'2d'
},
u'kind': u'youtube#video',
u'etag':
u'"m2yskBQFythfE4irbTIeOgYYfBU/-3AtVAYcRLEynWZprpf0OGaY8zo"',
u'id': u'0Yx8zrbsUu8'
})
# Copyright © 2017, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,132 | ucldc/harvester | refs/heads/master | /test/test_enrich_existing_couch_doc.py | import os
from unittest import TestCase
import json
import re
from mypretty import httpretty
# import httpretty
from mock import patch
from test.utils import DIR_FIXTURES
from harvester.config import config
from harvester.post_processing.enrich_existing_couch_doc import akara_enrich_doc
from harvester.post_processing.enrich_existing_couch_doc import main
class EnrichExistingCouchDocTestCase(TestCase):
'''Test the enrichment of a single couchdb document.
Want to make sure that the updated document is correct.
'''
@httpretty.activate
def testEnrichDoc(self):
httpretty.register_uri(httpretty.POST,
'http://localhost:8889/enrich',
body=open(DIR_FIXTURES+'/akara_response.json').read(),
)
indoc = json.load(open(DIR_FIXTURES+'/couchdb_doc.json'))
doc = akara_enrich_doc(indoc, '/select-oac-id,/dpla_mapper?mapper_type=oac_dc')
self.assertIn('added-key', doc['sourceResource'])
self.assertEqual(doc['sourceResource']['title'], 'changed title')
@patch('harvester.post_processing.enrich_existing_couch_doc.akara_enrich_doc')
@httpretty.activate
def testMain(self, mock_enrich_doc):
''' main in enrich_existing_couchd_doc takes a doc _id and
the enrichment chain to run. It then downloads the doc, submits it
for enrichment and then saves the resulting document.
'''
conf = config()
self.url_couch_base = conf['couchdb_url']
self.cdb = conf['couchdb_dbname']
url_couchdb = os.path.join(self.url_couch_base, self.cdb)
httpretty.register_uri(httpretty.HEAD,
url_couchdb,
body='',
content_length='0',
content_type='text/plain; charset=utf-8',
connection='close',
server='CouchDB/1.5.0 (Erlang OTP/R16B03)',
cache_control='must-revalidate',
date='Mon, 24 Nov 2014 21:30:38 GMT'
)
url_doc = os.path.join(url_couchdb,
'5112--http%3A%2F%2Fark.cdlib.org%2Fark%3A%2F13030%2Fkt7580382j')
doc_returned = open(DIR_FIXTURES+'/couchdb_doc.json').read()
httpretty.register_uri(httpretty.GET,
url_doc,
body=doc_returned,
etag="2U5BW2TDDX9EHZJOO0DNE29D1",
content_type='application/json',
connection='close',
)
httpretty.register_uri(httpretty.PUT,
url_doc,
status=201,
body='{"ok":true, "id":"5112--http://ark.cdlib.org/ark:/13030/kt7580382j", "rev":"123456789"}',
content_type='application/json',
etag="123456789",
connection='close',
)
httpretty.register_uri(httpretty.POST,
'http://localhost:8889/enrich',
body=open(DIR_FIXTURES+'/akara_response.json').read(),
)
mock_enrich_doc.return_value = json.loads(doc_returned)
main('5112--http://ark.cdlib.org/ark:/13030/kt7580382j',
'/select-oac-id,dpla_mapper?mapper_type=oac_dc')
mock_enrich_doc.assert_called_with(json.loads(doc_returned),
'/select-oac-id,dpla_mapper?mapper_type=oac_dc', 8889)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,133 | ucldc/harvester | refs/heads/master | /harvester/fetcher/marc_fetcher.py | # -*- coding: utf-8 -*-
import urllib
import tempfile
from xml.etree import ElementTree as ET
from pymarc import MARCReader
import pymarc
from .fetcher import Fetcher
class MARCFetcher(Fetcher):
'''Harvest a MARC FILE. Can be local or at a URL'''
def __init__(self, url_harvest, extra_data, **kwargs):
'''Grab file and copy to local temp file'''
super(MARCFetcher, self).__init__(url_harvest, extra_data, **kwargs)
self.url_marc_file = url_harvest
self.marc_file = tempfile.TemporaryFile()
self.marc_file.write(urllib.urlopen(self.url_marc_file).read())
self.marc_file.seek(0)
self.marc_reader = MARCReader(
self.marc_file, to_unicode=True, utf8_handling='replace')
def next(self):
'''Return MARC record by record to the controller'''
return self.marc_reader.next().as_dict()
class AlephMARCXMLFetcher(Fetcher):
'''Harvest a MARC XML feed from Aleph. Currently used for the
UCSB cylinders project'''
def __init__(self, url_harvest, extra_data, page_size=500, **kwargs):
'''Grab file and copy to local temp file'''
super(AlephMARCXMLFetcher, self).__init__(url_harvest, extra_data,
**kwargs)
self.ns = {'zs': "http://www.loc.gov/zing/srw/"}
self.page_size = page_size
self.url_base = url_harvest + '&maximumRecords=' + str(self.page_size)
self.current_record = 1
tree_current = self.get_current_xml_tree()
self.num_records = self.get_total_records(tree_current)
def get_url_current_chunk(self):
'''Set the next URL to retrieve according to page size and current
record'''
return ''.join((self.url_base, '&startRecord=',
str(self.current_record)))
def get_current_xml_tree(self):
'''Return an ElementTree for the next xml_page'''
url = self.get_url_current_chunk()
return ET.fromstring(urllib.urlopen(url).read())
def get_total_records(self, tree):
'''Return the total number of records from the etree passed in'''
return int(tree.find('.//zs:numberOfRecords', self.ns).text)
def next(self):
'''Return MARC records in sets to controller.
Break when last record position == num_records
'''
if self.current_record >= self.num_records:
raise StopIteration
# get chunk from self.current_record to self.current_record + page_size
tree = self.get_current_xml_tree()
recs_xml = tree.findall('.//zs:record', self.ns)
# advance current record to end of set
self.current_record = int(recs_xml[-1].find('.//zs:recordPosition',
self.ns).text)
self.current_record += 1
# translate to pymarc records & return
marc_xml_file = tempfile.TemporaryFile()
marc_xml_file.write(ET.tostring(tree))
marc_xml_file.seek(0)
recs = [
rec.as_dict() for rec in pymarc.parse_xml_to_array(marc_xml_file)
if rec is not None
]
return recs
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,134 | ucldc/harvester | refs/heads/master | /scripts/queue_harvest.py | #! /bin/env python
# queue a job on the rq queue
import sys
import datetime
import time
from redis import Redis
from redis.exceptions import ConnectionError as RedisConnectionError
from rq import Queue
from harvester.config import config
from harvester.config import RQ_Q_LIST
ID_EC2_INGEST = ''
ID_EC2_SOLR_BUILD = ''
TIMEOUT = 6000 # for machine start
JOB_TIMEOUT = 604800 # for jobs
def get_redis_connection(redis_host, redis_port, redis_pswd, redis_timeout=10):
return Redis(
host=redis_host,
port=redis_port,
password=redis_pswd,
socket_connect_timeout=redis_timeout)
def check_redis_queue(redis_host, redis_port, redis_pswd):
'''Check if the redis host db is up and running'''
r = get_redis_connection(redis_host, redis_port, redis_pswd)
try:
return r.ping()
except RedisConnectionError:
return False
def def_args():
'''For now only the required email for the user and url for collection api
object are parsed'''
import argparse
parser = argparse.ArgumentParser(description='Harvest a collection')
parser.add_argument('user_email', type=str, help='user email')
parser.add_argument('rq_queue', type=str, help='RQ queue to put job in')
parser.add_argument(
'url_api_collection',
type=str,
help='URL for the collection Django tastypie api resource')
parser.add_argument(
'--job_timeout',
type=int,
default=JOB_TIMEOUT,
help='Timeout for the RQ job')
parser.add_argument(
'--run_image_harvest',
type=bool,
default=True,
help='Run image harvest set: --run_image_harvest=False to skip')
parser.add_argument(
'--page_range',
type=str,
default=None,
help='The page range as a comma separated pair of numbers')
return parser
def main(
user_email,
url_api_collection,
redis_host=None,
redis_port=None,
redis_pswd=None,
timeout=None,
poll_interval=20,
job_timeout=86400, # 24 hrs
rq_queue=None,
run_image_harvest=False,
page_range=None):
timeout_dt = datetime.timedelta(seconds=timeout) if timeout else \
datetime.timedelta(seconds=TIMEOUT)
start_time = datetime.datetime.now()
while not check_redis_queue(redis_host, redis_port, redis_pswd):
time.sleep(poll_interval)
if datetime.datetime.now() - start_time > timeout_dt:
# TODO: email user
raise Exception('TIMEOUT ({0}s) WAITING FOR QUEUE.'.format(
timeout))
if rq_queue not in RQ_Q_LIST:
raise ValueError('{0} is not a valid RQ worker queue'.format(rq_queue))
rQ = Queue(
rq_queue,
connection=get_redis_connection(redis_host, redis_port, redis_pswd))
url_api_collection = [u.strip() for u in url_api_collection.split(';')]
results = []
for url in url_api_collection:
result = rQ.enqueue_call(
func='harvester.run_ingest.main',
args=(user_email, url),
kwargs={
'run_image_harvest': run_image_harvest,
'rq_queue': rq_queue,
'page_range': page_range
},
timeout=job_timeout, )
results.append(result)
return results
if __name__ == '__main__':
parser = def_args()
args = parser.parse_args(sys.argv[1:])
if not args.user_email or not args.url_api_collection or not args.rq_queue:
parser.print_help()
raise Exception('Missing required parameters')
env = config()
main(
args.user_email,
args.url_api_collection.strip(),
redis_host=env['redis_host'],
redis_port=env['redis_port'],
redis_pswd=env['redis_password'],
rq_queue=args.rq_queue,
job_timeout=args.job_timeout,
run_image_harvest=args.run_image_harvest,
page_range=args.page_range)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,135 | ucldc/harvester | refs/heads/master | /scripts/fix_rights_status.py | import sys
from harvester.post_processing.run_transform_on_couchdb_docs import run_on_couchdb_by_collection
RIGHTS_STATEMENT_DEFAULT = 'Please contact the contributing institution for more information regarding the copyright status of this object'
RIGHTS_STATEMENT_DEFAULT = 'Please contact the contributing institution for the copyright status of this object'
#RIGHTS_STATEMENT_DEFAULT = 'Please contact the contributing institution for more information regarding the copyright status of this object. Its presence on this site does not necessarily mean it is free from copyright restrictions.'
def fix_rights_status(doc):
if len(doc['sourceResource']['rights']) == 2:
if doc['sourceResource']['rights'][0] == 'copyright unknown' and \
doc['sourceResource']['rights'][1] == RIGHTS_STATEMENT_DEFAULT:
print "FIXING FOR:{}".format(doc['_id'])
doc['sourceResource']['rights'] = [doc['sourceResource']['rights'][1]]
return doc
collection_ids = [
"11073",
"11075",
"11076",
"11084",
"11134",
"11167",
"11439",
"11575",
"11582",
"1161",
"11705",
]
###"10046",
###"10059",
###"10063",
###"10067",
###"10126",
###"10130",
###"1021",
###"10246",
###"10318",
###"10328",
###"10343",
###"10363",
###"10387",
###"10422",
###"10425",
###"10616",
###"10632",
###"10664",
###"10671",
###"10710",
###"10722",
###"10732",
###"108",
###"10885",
###"10935",
###"11",
###"11010",
###"11068",
###"11073",
###"11075",
###"11076",
###"11084",
###"11134",
###"11167",
###"11439",
###"11575",
###"11582",
###"1161",
###"11705",
###]
for c in collection_ids:
print "RUN FOR {}".format(c)
sys.stderr.flush()
sys.stdout.flush()
run_on_couchdb_by_collection(fix_rights_status,
collection_key=c)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,136 | ucldc/harvester | refs/heads/master | /setup_queuing_only.py | # Setup for machines that only need to queue jobs.
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='UCLDC Harvester',
version='0.8.1',
py_modules=['harvester.config', 'harvester.collection_registry_client'],
include_package_data=True,
license='BSD License - see LICENSE file',
description='Harvester installed for queuing jobs for the UCLDC project',
long_description=read('README.md'),
author='Mark Redar',
author_email='mark.redar@ucop.edu',
classifiers=[
'Environment :: Web Environment',
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=[
'requests==2.20.0',
'Logbook==0.6.0',
'redis==2.10.1',
'rq==0.8.2',
],
test_suite='test',
tests_require=['mock>=1.0.1', 'httpretty==0.8.3', ],
)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,137 | ucldc/harvester | refs/heads/master | /harvester/post_processing/enrich_existing_couch_doc.py | from __future__ import print_function
import sys
import httplib
import json
import argparse
import couchdb
from harvester.couchdb_init import get_couchdb
def _get_source(doc):
'''Return the "source". For us use the registry collection url.
if collection or collection field not found, report and reraise error.
'''
try:
source = doc['originalRecord']['collection'][0]['@id']
return source
except KeyError as e:
print("No originalRecord.collection for document ID: {}".format(
doc['_id']))
print("KEYS:{}".format(doc['originalRecord'].keys()))
raise e
def _get_enriched_doc(doc, enrichment, port):
'''Submit the document to the Akara enrichment endpoint'''
source = _get_source(doc)
conn = httplib.HTTPConnection("localhost", port)
headers = {
"Source": source,
"Content-Type": "application/json",
"Pipeline-item": enrichment.replace('\n',''),
}
#conn.request("POST", "/enrich", json.dumps([doc['originalRecord']]), headers)
conn.request("POST", "/enrich", json.dumps([doc]), headers)
resp = conn.getresponse()
if not resp.status == 200:
raise Exception("Error (status {}) for doc {}".format(
resp.status, doc['_id']))
data = json.loads(resp.read())
# there should only be one
assert(len(data['enriched_records'].keys()) == 1)
return data['enriched_records'][data['enriched_records'].keys()[0]]
def _update_doc(doc, newdoc):
'''Update the original doc with new information from new doc, while
not hammering any data in original doc.
for now I'm modifying the input doc, but should probably return copy?
'''
doc['originalRecord'].update(newdoc['originalRecord'])
del(newdoc['originalRecord'])
doc['sourceResource'].update(newdoc['sourceResource'])
del(newdoc['sourceResource'])
doc.update(newdoc)
return doc
# NOTE: the enrichment must include one that selects the _id from data
# data should already have the "collection" data in originalRecord
def akara_enrich_doc(doc, enrichment, port=8889):
'''Enrich a doc that already exists in couch
gets passed document, enrichment string, akara port.
'''
newdoc = _get_enriched_doc(doc, enrichment, port)
return _update_doc(doc, newdoc)
def main(doc_id, enrichment, port=8889):
'''Run akara_enrich_doc for one document and save result'''
_couchdb = get_couchdb()
indoc = _couchdb.get(doc_id)
doc = akara_enrich_doc(indoc, enrichment, port)
_couchdb[doc_id] = doc
if __name__=='__main__':
parser = argparse.ArgumentParser(
description='Run enrichments on couchdb document')
parser.add_argument('doc_id', help='couchdb document _id')
parser.add_argument('enrichment',
help='Comma separated string of akara enrichments to run. \
Must include enrichment to select id.')
args = parser.parse_args()
main(args.doc_id, args.enrichment)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,138 | ucldc/harvester | refs/heads/master | /test/utils.py | import os
import unittest
import tempfile
import logbook
DIR_THIS_FILE = os.path.abspath(os.path.split(__file__)[0])
DIR_FIXTURES = os.path.join(DIR_THIS_FILE, 'fixtures')
# NOTE: these are used in integration test runs
TEST_COUCH_DB = 'test-ucldc'
TEST_COUCH_DASHBOARD = 'test-dashboard'
CONFIG_FILE_DPLA = '''
[Akara]
Port=8889
[CouchDb]
URL=http://127.0.0.1:5984/
Username=mark
Password=mark
ItemDatabase=''' + TEST_COUCH_DB + '''
DashboardDatabase=''' + TEST_COUCH_DASHBOARD
def skipUnlessIntegrationTest(selfobj=None):
'''Skip the test unless the environmen variable RUN_INTEGRATION_TESTS is set
TO run integration tests need the following:
- Registry server
- couchdb server with databases setup
- redis server
- solr server with schema
'''
if os.environ.get('RUN_INTEGRATION_TESTS', False):
return lambda func: func
return unittest.skip('RUN_INTEGRATION_TESTS not set. Skipping integration tests.')
class LogOverrideMixin(object):
'''Mixin to use logbook test_handler for logging'''
def setUp(self):
'''Use test_handler'''
super(LogOverrideMixin, self).setUp()
self.test_log_handler = logbook.TestHandler()
def deliver(msg, email):
# print ' '.join(('Mail sent to ', email, ' MSG: ', msg))
pass
self.test_log_handler.deliver = deliver
self.test_log_handler.push_thread()
def tearDown(self):
self.test_log_handler.pop_thread()
class ConfigFileOverrideMixin(object):
'''Create temporary config and profile files for use by the DPLA couch
module when creating the ingest doc.
Returns names of 2 tempfiles for use as config and profile.'''
env_list = ['COUCHDB_URL', 'COUCHDB_DB', 'COUCHDB_DASHBOARD',
'DPLA_CONFIG_FILE']
def setUp_config(self, collection):
self.env_saved = {}
for envvar in self.env_list:
if envvar in os.environ:
self.env_saved[envvar] = os.environ[envvar]
del os.environ[envvar]
f, self.config_file = tempfile.mkstemp()
with open(self.config_file, 'w') as f:
f.write(CONFIG_FILE_DPLA)
f, self.profile_path = tempfile.mkstemp()
with open(self.profile_path, 'w') as f:
f.write(collection.dpla_profile)
return self.config_file, self.profile_path
def tearDown_config(self):
for envvar in self.env_saved.keys():
os.environ[envvar] = self.env_saved[envvar]
os.remove(self.config_file)
os.remove(self.profile_path)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,139 | ucldc/harvester | refs/heads/master | /scripts/rerun_enrichments.py | #! /bin/env python
'''Rerun a collection's stored enrichments
'''
import sys
import argparse
from harvester.post_processing.couchdb_runner import CouchDBJobEnqueue
from harvester.collection_registry_client import Collection
import harvester.post_processing.enrich_existing_couch_doc
def main(args):
parser = argparse.ArgumentParser(
description='run the enrichments stored for a collection.')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--collection_id',
help='Registry id for the collection')
group.add_argument('--cid_file',
help='File with collection ids for running')
parser.add_argument('--rq_queue',
help='Override queue for jobs, normal-stage is default')
args = parser.parse_args(args)
Q = 'normal-stage'
if args.rq_queue:
Q = args.rq_queue
enq = CouchDBJobEnqueue(Q)
timeout = 10000
cids = []
if args.collection_id:
cids = [ args.collection_id ]
else: #cid file
with open(args.cid_file) as foo:
lines = foo.readlines()
cids = [ l.strip() for l in lines]
print "CIDS:{}".format(cids)
for cid in cids:
url_api = ''.join(('https://registry.cdlib.org/api/v1/collection/',
cid, '/'))
coll = Collection(url_api)
print coll.id
enrichments = coll.enrichments_item
enq.queue_collection(cid, timeout,
harvester.post_processing.enrich_existing_couch_doc.main,
enrichments
)
if __name__=='__main__':
main(sys.argv[1:])
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,140 | ucldc/harvester | refs/heads/master | /harvester/fetcher/ucsf_xml_fetcher.py | # -*- coding: utf-8 -*-
import urllib
import re
from xml.etree import ElementTree as ET
from collections import defaultdict
from .fetcher import Fetcher
class UCSF_XML_Fetcher(Fetcher):
def __init__(self, url_harvest, extra_data, page_size=100, **kwargs):
self.url_base = url_harvest
self.page_size = page_size
self.page_current = 1
self.doc_current = 1
self.docs_fetched = 0
xml = urllib.urlopen(self.url_current).read()
total = re.search('search-hits pages="(?P<pages>\d+)" page="'
'(?P<page>\d+)" total="(?P<total>\d+)"', xml)
self.docs_total = int(total.group('total'))
self.re_ns_strip = re.compile('{.*}(?P<tag>.*)$')
@property
def url_current(self):
return '{0}&ps={1}&p={2}'.format(self.url_base, self.page_size,
self.page_current)
def _dochits_to_objset(self, docHits):
'''Returns list of objecs.
Objects are dictionary with tid, uri & metadata keys.
tid & uri are strings
metadata is a dict with keys matching UCSF xml metadata tags.
'''
objset = []
for d in docHits:
doc = d.find('./{http://legacy.library.ucsf.edu/document/1.1}'
'document')
obj = {}
obj['tid'] = doc.attrib['tid']
obj['uri'] = doc.find('./{http://legacy.library.ucsf.edu/document/'
'1.1}uri').text
mdata = doc.find('./{http://legacy.library.ucsf.edu/document/1.1}'
'metadata')
obj_mdata = defaultdict(list)
for md in mdata:
# strip namespace
key = self.re_ns_strip.match(md.tag).group('tag')
obj_mdata[key].append(md.text)
obj['metadata'] = obj_mdata
self.docs_fetched += 1
objset.append(obj)
return objset
def next(self):
'''get next objset, use etree to pythonize'''
if self.doc_current == self.docs_total:
if self.docs_fetched != self.docs_total:
raise ValueError(
"Number of documents fetched ({0}) doesn't match \
total reported by server ({1})"
.format(self.docs_fetched, self.docs_total))
else:
raise StopIteration
tree = ET.fromstring(urllib.urlopen(self.url_current).read())
hits = tree.findall(
".//{http://legacy.library.ucsf.edu/search/1.0}search-hit")
self.page_current += 1
self.doc_current = int(hits[-1].attrib['number'])
return self._dochits_to_objset(hits)
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,141 | ucldc/harvester | refs/heads/master | /scripts/delete_couchdocs_by_obj_checksum.py | #! /bin/env python
# -*- coding: utf-8 -*-
import sys
import argparse
from harvester.couchdb_init import get_couchdb
from harvester.couchdb_sync_db_by_collection import delete_id_list
from harvester.post_processing.couchdb_runner import CouchDBCollectionFilter
def confirm_deletion(count, objChecksum, cid):
prompt = "\nDelete {0} documents with object checksum {1} from Collection {2}? yes to confirm\n".format(count, objChecksum, cid)
while True:
ans = raw_input(prompt).lower()
if ans == "yes":
return True
else:
return False
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Delete all documents in given collection matching given object checksum. ' \
'Use for metadata-only records that can only be identified by value in object field ' \
'USAGE: delete_couchdocs_by_obj_checksum.py [collection id] [object value]')
parser.add_argument('cid', help='Collection ID')
parser.add_argument('objChecksum', help='CouchDB "object" value of documents to delete')
args = parser.parse_args(sys.argv[1:])
if not args.cid or not args.objChecksum:
parser.print_help()
sys.exit(27)
ids = []
_couchdb = get_couchdb()
rows = CouchDBCollectionFilter(collection_key=args.cid, couchdb_obj=_couchdb)
for row in rows:
couchdoc = row.doc
if 'object' in couchdoc and couchdoc['object'] == args.objChecksum:
couchID = couchdoc['_id']
ids.append(couchID)
if not ids:
print 'No docs found with object checksum matching {}'.format(args.objChecksum)
sys.exit(27)
if confirm_deletion(len(ids), args.objChecksum, args.cid):
num_deleted, delete_ids = delete_id_list(ids, _couchdb=_couchdb)
print 'Deleted {} documents'.format(num_deleted)
else:
print "Exiting without deleting"
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,142 | ucldc/harvester | refs/heads/master | /harvester/fetcher/ucd_json_fetcher.py | # -*- coding: utf-8 -*-
from collections import defaultdict
from .fetcher import Fetcher
import urllib
import extruct
import requests
import re
from xml.etree import ElementTree as ET
from w3lib.html import get_base_url
from rdflib.plugin import register, Serializer
register('json-ld', Serializer, 'rdflib_jsonld.serializer', 'JsonLDSerializer')
class UCD_JSON_Fetcher(Fetcher):
'''Retrieve JSON from each page listed on
UC Davis XML sitemap given as url_harvest'''
def __init__(self, url_harvest, extra_data, **kwargs):
self.url_base = url_harvest
self.docs_fetched = 0
xml = urllib.urlopen(self.url_base).read()
total = re.findall('<url>', xml)
self.docs_total = len(total)
# need to declare the sitemap namespace for ElementTree
tree = ET.fromstring(xml)
namespaces = {'xmlns': 'http://www.sitemaps.org/schemas/sitemap/0.9'}
self.hits = tree.findall('.//xmlns:url/xmlns:loc', namespaces)
def _dochits_to_objset(self, docHits):
'''Returns list of objects.
'''
objset = []
for d in docHits:
r = requests.get(d.text)
# get JSON-LD from the page
base_url = get_base_url(r.text)
data = extruct.extract(r.text, base_url)
jsld = data.get('json-ld')[0]
obj = {}
obj_mdata = defaultdict(list)
for mdata in jsld:
obj_mdata[mdata] = jsld[mdata]
obj['metadata'] = dict(obj_mdata)
objset.append(obj)
self.docs_fetched += 1
return objset
def next(self):
'''get next objset, use etree to pythonize'''
if self.docs_fetched >= self.docs_total:
raise StopIteration
return self._dochits_to_objset(self.hits)
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - 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.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
54,143 | ucldc/harvester | refs/heads/master | /harvester/image_harvest.py | # harvest images for the given collection
# by this point the isShownBy value for the doc should be filled in.
# this should point at the highest fidelity object file available
# from the source.
# use brian's content md5s3stash to store the resulting image.
import os
import sys
import datetime
import time
import urlparse
import urllib
from couchdb import ResourceConflict
import requests
import md5s3stash
import boto.s3
import logging
from collections import namedtuple
from collections import defaultdict
from harvester.couchdb_init import get_couchdb
from harvester.config import config
from redis import Redis
import redis_collections
from harvester.couchdb_pager import couchdb_pager
from harvester.cleanup_dir import cleanup_work_dir
from harvester.sns_message import publish_to_harvesting
from harvester.sns_message import format_results_subject
BUCKET_BASES = os.environ.get(
'S3_BUCKET_IMAGE_BASE',
'us-west-2:static-ucldc-cdlib-org/harvested_images;us-east-1:'
'static.ucldc.cdlib.org/harvested_images').split(';')
COUCHDB_VIEW = 'all_provider_docs/by_provider_name'
URL_OAC_CONTENT_BASE = os.environ.get('URL_OAC_CONTENT_BASE',
'http://content.cdlib.org')
logging.basicConfig(level=logging.DEBUG, )
class ImageHarvestError(Exception):
def __init__(self, message, doc_id=None):
super(ImageHarvestError, self).__init__(message)
self.doc_id = doc_id
class ImageHTTPError(ImageHarvestError):
# will waap exceptions from the HTTP request
dict_key = 'HTTP Error'
class HasObject(ImageHarvestError):
dict_key = 'Has Object already'
class RestoreFromObjectCache(ImageHarvestError):
dict_key = 'Restored From Object Cache'
class IsShownByError(ImageHarvestError):
dict_key = 'isShownBy Error'
class FailsImageTest(ImageHarvestError):
dict_key = 'Fails the link is to image test'
def link_is_to_image(doc_id, url, auth=None):
'''Check if the link points to an image content type.
Return True or False accordingly.
'''
if md5s3stash.is_s3_url(url):
response = requests.head(url, allow_redirects=True)
else:
response = requests.head(url, allow_redirects=True, auth=auth)
# have a server that returns a 403 here, does have content-type of
# text/html. Dropping this test here. requests throws if can't connect
if response.status_code != 200:
# many servers do not support HEAD requests, try get
if md5s3stash.is_s3_url(url):
response = requests.get(url, allow_redirects=True)
else:
response = requests.get(url, allow_redirects=True, auth=auth)
if response.status_code != 200:
raise ImageHTTPError(
'HTTP ERROR: {}'.format(response.status_code), doc_id=doc_id)
content_type = response.headers.get('content-type', None)
if not content_type:
return False
reg_type = content_type.split('/', 1)[0].lower()
# situation where a server returned 'text/html' to HEAD requests
# but returned 'image/jpeg' for GET.
# try a slower GET if not image type
if reg_type != 'image':
response = requests.get(url, allow_redirects=True, auth=auth)
if response.status_code != 200:
raise ImageHTTPError(
'HTTP ERROR: {}'.format(response.status_code), doc_id=doc_id)
content_type = response.headers.get('content-type', None)
if not content_type:
return False
reg_type = content_type.split('/', 1)[0].lower()
return reg_type == 'image'
# Need to make each download a separate job.
def stash_image_for_doc(doc,
url_cache,
hash_cache,
ignore_content_type,
bucket_bases=BUCKET_BASES,
auth=None):
'''Stash the images in s3, using md5s3stash
Duplicate it among the "BUCKET_BASES" list. This will give redundancy
in case some idiot (me) deletes one of the copies. Not tons of data so
cheap to replicate them.
Return md5s3stash report if image found
If link is not an image type, don't stash & raise
'''
try:
url_image = doc['isShownBy']
if not url_image:
raise IsShownByError(
"isShownBy empty for {0}".format(doc['_id']),
doc_id=doc['_id'])
except KeyError as e:
raise IsShownByError(
"isShownBy missing for {0}".format(doc['_id']), doc_id=doc['_id'])
if isinstance(url_image, list): # need to fix marc map_is_shown_at
url_image = url_image[0]
# try to parse url, check values of scheme & netloc at least
url_parsed = urlparse.urlsplit(url_image)
if url_parsed.scheme == 'ark':
# for some OAC objects, the reference image is not a url but a path.
url_image = '/'.join((URL_OAC_CONTENT_BASE, url_image))
elif not url_parsed.scheme or not url_parsed.netloc:
msg = 'Link not http URL for {} - {}'.format(doc['_id'], url_image)
print >> sys.stderr, msg
raise FailsImageTest(msg, doc_id=doc['_id'])
reports = []
# If '--ignore_content_type' set, don't check link_is_to_image
if link_is_to_image(doc['_id'], url_image, auth) or ignore_content_type:
for bucket_base in bucket_bases:
try:
logging.getLogger('image_harvest.stash_image').info(
'bucket_base:{0} url_image:{1}'.format(bucket_base,
url_image))
region, bucket_base = bucket_base.split(':')
conn = boto.s3.connect_to_region(region)
report = md5s3stash.md5s3stash(
url_image,
bucket_base=bucket_base,
conn=conn,
url_auth=auth,
url_cache=url_cache,
hash_cache=hash_cache)
reports.append(report)
except TypeError as e:
print >> sys.stderr, 'TypeError for doc:{} {} Msg: {} Args:' \
' {}'.format(
doc['_id'], url_image, e.message, e.args)
return reports
else:
msg = 'Not an image for {} - {}'.format(doc['_id'], url_image)
print >> sys.stderr, msg
raise FailsImageTest(msg, doc_id=doc['_id'])
class ImageHarvester(object):
'''Useful to cache couchdb, authentication info and such'''
def __init__(self,
cdb=None,
url_couchdb=None,
couchdb_name=None,
couch_view=COUCHDB_VIEW,
bucket_bases=BUCKET_BASES,
object_auth=None,
get_if_object=False,
ignore_content_type=False,
url_cache=None,
hash_cache=None,
harvested_object_cache=None):
self._config = config()
if cdb:
self._couchdb = cdb
else:
if not url_couchdb:
url_couchdb = self._config['couchdb_url']
self._couchdb = get_couchdb(url=url_couchdb, dbname=couchdb_name)
self._bucket_bases = bucket_bases
self._view = couch_view
# auth is a tuple of username, password
self._auth = object_auth
self.get_if_object = get_if_object # if object field exists, get
self.ignore_content_type = ignore_content_type # Don't check content-type in headers
self._redis = Redis(
host=self._config['redis_host'],
port=self._config['redis_port'],
password=self._config['redis_password'],
socket_connect_timeout=self._config['redis_connect_timeout'])
self._url_cache = url_cache if url_cache is not None else \
redis_collections.Dict(key='ucldc-image-url-cache',
redis=self._redis)
self._hash_cache = hash_cache if hash_cache is not None else \
redis_collections.Dict(key='ucldc-image-hash-cache',
redis=self._redis)
self._object_cache = harvested_object_cache if harvested_object_cache \
else \
redis_collections.Dict(
key='ucldc:harvester:harvested-images',
redis=self._redis)
def stash_image(self, doc):
return stash_image_for_doc(
doc,
self._url_cache,
self._hash_cache,
self.ignore_content_type,
bucket_bases=self._bucket_bases,
auth=self._auth)
def update_doc_object(self, doc, report):
'''Update the object field to point to an s3 bucket'''
doc['object'] = report.md5
doc['object_dimensions'] = report.dimensions
try:
self._couchdb.save(doc)
except ResourceConflict as e:
msg = 'ResourceConflictfor doc: {} - {}'.format(doc[
'_id'], e.message)
print >> sys.stderr, msg
return doc['object']
def harvest_image_for_doc(self, doc, force=False):
'''Try to harvest an image for a couchdb doc'''
reports = None
did = doc['_id']
object_cached = self._object_cache.get(did, False)
if not self.get_if_object and doc.get('object', False) and not force:
msg = 'Skipping {}, has object field'.format(did)
print >> sys.stderr, msg
if not object_cached:
msg = 'Save to object cache {}'.format(did)
print >> sys.stderr, msg
self._object_cache[did] = [
doc['object'], doc['object_dimensions']
]
raise HasObject(msg, doc_id=doc['_id'])
if not self.get_if_object and object_cached and not force:
# have already downloaded an image for this, just fill in data
ImageReport = namedtuple('ImageReport', 'md5, dimensions')
msg = 'Restore from object_cache: {}'.format(did)
print >> sys.stderr, msg
self.update_doc_object(doc,
ImageReport(object_cached[0],
object_cached[1]))
raise RestoreFromObjectCache(msg, doc_id=doc['_id'])
try:
reports = self.stash_image(doc)
if reports is not None and len(reports) > 0:
self._object_cache[did] = [
reports[0].md5, reports[0].dimensions
]
self.update_doc_object(doc, reports[0])
except IOError as e:
print >> sys.stderr, e
return reports
def by_doc_id(self, doc_id):
'''For a list of ids, harvest images'''
doc = self._couchdb[doc_id]
dt_start = dt_end = datetime.datetime.now()
report_errors = defaultdict(list)
try:
reports = self.harvest_image_for_doc(doc, force=True)
except ImageHarvestError as e:
report_errors[e.dict_key].append((e.doc_id, str(e)))
dt_end = datetime.datetime.now()
time.sleep((dt_end - dt_start).total_seconds())
return report_errors
def by_collection(self, collection_key=None):
'''If collection_key is none, trying to grab all of the images. (Not
recommended)
'''
if collection_key:
v = couchdb_pager(
self._couchdb,
view_name=self._view,
startkey='"{0}"'.format(collection_key),
endkey='"{0}"'.format(collection_key),
include_docs='true')
else:
# use _all_docs view
v = couchdb_pager(self._couchdb, include_docs='true')
doc_ids = []
report_errors = defaultdict(list)
for r in v:
dt_start = dt_end = datetime.datetime.now()
try:
reports = self.harvest_image_for_doc(r.doc)
except ImageHarvestError as e:
report_errors[e.dict_key].append((e.doc_id, str(e)))
doc_ids.append(r.doc['_id'])
dt_end = datetime.datetime.now()
time.sleep((dt_end - dt_start).total_seconds())
report_list = [
' : '.join((key, str(val))) for key, val in report_errors.items()
]
report_msg = '\n'.join(report_list)
subject = format_results_subject(collection_key,
'Image harvest to CouchDB {env}')
publish_to_harvesting(subject, ''.join(
('Processed {} documents\n'.format(len(doc_ids)), report_msg)))
return doc_ids, report_errors
def harvest_image_for_doc(doc_id,
url_couchdb=None,
object_auth=None,
get_if_object=False,
force=False):
'''Wrapper to call from rqworker.
Creates ImageHarvester object & then calls harvest_image_for_doc
'''
harvester = ImageHarvester(
url_couchdb=url_couchdb,
object_auth=object_auth,
get_if_object=get_if_object,
ignore_content_type=ignore_content_type)
# get doc from couchdb
couchdb = get_couchdb(url=url_couchdb)
doc = couchdb[doc_id]
if not get_if_object and 'object' in doc and not force:
print >> sys.stderr, 'Skipping {}, has object field'.format(doc['_id'])
else:
harvester.harvest_image_for_doc(doc, force=force)
def main(collection_key=None,
url_couchdb=None,
object_auth=None,
get_if_object=False,
ignore_content_type=False):
cleanup_work_dir() # remove files from /tmp
doc_ids, report_errors = ImageHarvester(
url_couchdb=url_couchdb,
object_auth=object_auth,
get_if_object=get_if_object,
ignore_content_type=ignore_content_type).by_collection(collection_key)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description='Run the image harvesting on a collection')
parser.add_argument('collection_key', help='Registry collection id')
parser.add_argument(
'--object_auth',
nargs='?',
help='HTTP Auth needed to download images - username:password')
parser.add_argument(
'--url_couchdb', nargs='?', help='Override url to couchdb')
parser.add_argument(
'--get_if_object',
action='store_true',
default=False,
help='Should image harvester not get image if the object field exists '
'for the doc (default: False, always get)')
args = parser.parse_args()
print(args)
object_auth = None
if args.object_auth:
object_auth = (args.object_auth.split(':')[0],
args.object_auth.split(':')[1])
main(
args.collection_key,
object_auth=object_auth,
url_couchdb=args.url_couchdb,
get_if_object=args.get_if_object)
| {"/test/test_oai_fetcher.py": ["/test/utils.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/__init__.py"], "/harvester/run_ingest.py": ["/harvester/config.py", "/harvester/collection_registry_client.py", "/harvester/sns_message.py", "/harvester/image_harvest.py", "/harvester/cleanup_dir.py"], "/test/test_preservica_api_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_collection_registry_client.py": ["/harvester/collection_registry_client.py", "/test/utils.py"], "/harvester/post_processing/batch_update_couchdb_by_collection.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/scripts/queue_deep_harvest_single_object_jobs.py": ["/harvester/config.py", "/harvester/collection_registry_client.py"], "/scripts/queue_image_harvest_by_doc.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/queue_image_harvest_for_doc_ids.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py"], "/scripts/image_harvest_opl_preservica.py": ["/harvester/image_harvest.py"], "/test/test_nuxeo_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/test/test_harvestcontroller.py": ["/test/utils.py", "/harvester/fetcher/__init__.py", "/harvester/collection_registry_client.py", "/harvester/fetcher/controller.py"], "/harvester/rq_worker_sns_msgs.py": ["/harvester/sns_message.py"], "/scripts/queue_delete_couchdb_collection.py": ["/harvester/config.py"], "/scripts/remove_field_list_from_collection_docs.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/image_harvest.py", "/harvester/couchdb_init.py"], "/test/test_cmisatomfeed_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_marc_fetcher.py": ["/harvester/collection_registry_client.py", "/test/utils.py", "/harvester/fetcher/__init__.py"], "/scripts/redis_delete_harvested_images_script.py": ["/harvester/post_processing/couchdb_runner.py"], "/scripts/queue_document_reenrich.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/harvester/fetcher/controller.py": ["/harvester/collection_registry_client.py", "/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py"], "/test/test_flickr_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_deep_harvest_single_object_with_components.py": ["/harvester/config.py"], "/scripts/enq_date_fix.py": ["/harvester/post_processing/couchdb_runner.py", "/harvester/post_processing/run_transform_on_couchdb_docs.py"], "/test/test_youtube_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_enrich_existing_couch_doc.py": ["/test/utils.py", "/harvester/config.py", "/harvester/post_processing/enrich_existing_couch_doc.py"], "/scripts/queue_harvest.py": ["/harvester/config.py"], "/harvester/post_processing/enrich_existing_couch_doc.py": ["/harvester/couchdb_init.py"], "/harvester/image_harvest.py": ["/harvester/couchdb_init.py", "/harvester/config.py", "/harvester/couchdb_pager.py", "/harvester/cleanup_dir.py", "/harvester/sns_message.py"], "/test/test_ucsf_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/sync_couch_to_solr.py": ["/harvester/couchdb_pager.py", "/harvester/couchdb_init.py"], "/test/test_xml_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/test/test_dedupe_sourceresource.py": ["/test/utils.py"], "/test/test_integration_tests.py": ["/test/utils.py", "/harvester/fetcher/__init__.py"], "/harvester/couchdb_sync_db_by_collection.py": ["/harvester/collection_registry_client.py", "/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/harvester/fetcher/__init__.py": ["/harvester/fetcher/oai_fetcher.py", "/harvester/fetcher/solr_fetcher.py", "/harvester/fetcher/marc_fetcher.py", "/harvester/fetcher/nuxeo_fetcher.py", "/harvester/fetcher/oac_fetcher.py", "/harvester/fetcher/ucsf_xml_fetcher.py", "/harvester/fetcher/cmis_atom_feed_fetcher.py", "/harvester/fetcher/flickr_fetcher.py", "/harvester/fetcher/youtube_fetcher.py", "/harvester/fetcher/ucd_json_fetcher.py", "/harvester/fetcher/emuseum_fetcher.py", "/harvester/fetcher/ia_fetcher.py", "/harvester/fetcher/preservica_api_fetcher.py", "/harvester/fetcher/controller.py"], "/test/test_emuseum_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/harvester/solr_updater.py": ["/harvester/couchdb_init.py", "/harvester/post_processing/couchdb_runner.py", "/harvester/sns_message.py"], "/test/test_ia_fetcher.py": ["/harvester/fetcher/__init__.py", "/test/utils.py"], "/scripts/queue_sync_couchdb_collection.py": ["/harvester/config.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.