Text extraction from a file format unknown to me - text

I have a lot of files obviously stemming from some web publishing system (unidentified) and want to convert them to plain text. The file format is characterised by a lot of curly braces, square brackets, and semicolons and contains formatting instructions besides the text. A sample file looks like this
{"content":[{"type":"paragraph","attributes":{"class":"align-left"},"content":["У Посольстві України в Республіці Польща 8 листопада було підписано Угоду між урядом України та урядом Монголії про взаємне скасування віз."]},{"type":"paragraph","attributes":{"class":"align-left"},"content":["“Ми підписали угоду, яка дозволяє громадянам України подорожувати без віз до Монголії. Це означає, що громадяни України можуть в’їжджати до Монголії без віз на 90 днів упродовж 180 днів” - ",{"type":"link","attributes":{"href":"https://www.facebook.com/UkraineMFA/posts/2498886686831903","target":"_blank","rel":null},"content":["повідомляє сторінка МЗС у Facebook"]}," із посиланям на посла України у Польщі Андрія Дещицю."]},{"type":"paragraph","attributes":{"class":"align-left"},"content":["Як підкреслив Дещиця, підписана угода важлива ще й тому, що до сьогоднішнього дня між Україною і Монголією діяла угода 1979 року, яка була підписана свого часу між СРСР і Монгольською Народною Республікою, а потім була підтверджена українським урядом."]}]}
What kind of file format is this? Is there a readily available converter to plain text or some documentation on that file format available?

A more readable way, is to use yaml format:
$ yq -p json -o yaml file
content:
- type: paragraph
attributes:
class: align-left
content:
- У Посольстві України в Республіці Польща 8 листопада було підписано Угоду між урядом України та урядом Монголії про взаємне скасування віз.
- type: paragraph
attributes:
class: align-left
content:
- '“Ми підписали угоду, яка дозволяє громадянам України подорожувати без віз до Монголії. Це означає, що громадяни України можуть в’їжджати до Монголії без віз на 90 днів упродовж 180 днів” - '
- type: link
attributes:
href: https://www.facebook.com/UkraineMFA/posts/2498886686831903
target: _blank
rel: null
content:
- повідомляє сторінка МЗС у Facebook
- ' із посиланям на посла України у Польщі Андрія Дещицю.'
- type: paragraph
attributes:
class: align-left
content:
- Як підкреслив Дещиця, підписана угода важлива ще й тому, що до сьогоднішнього дня між Україною і Монголією діяла угода 1979 року, яка була підписана свого часу між СРСР і Монгольською Народною Республікою, а потім була підтверджена українським урядом.
Or pretty print if as json:
$ jq . file
{
"content": [
{
"type": "paragraph",
"attributes": {
"class": "align-left"
},
"content": [
"У Посольстві України в Республіці Польща 8 листопада було підписано Угоду між урядом України та урядом Монголії про взаємне скасування віз."
]
},
{
"type": "paragraph",
"attributes": {
"class": "align-left"
},
"content": [
"“Ми підписали угоду, яка дозволяє громадянам України подорожувати без віз до Монголії. Це означає, що громадяни України можуть в’їжджати до Монголії без віз на 90 днів упродовж 180 днів” - ",
{
"type": "link",
"attributes": {
"href": "https://www.facebook.com/UkraineMFA/posts/2498886686831903",
"target": "_blank",
"rel": null
},
"content": [
"повідомляє сторінка МЗС у Facebook"
]
},
" із посиланям на посла України у Польщі Андрія Дещицю."
]
},
{
"type": "paragraph",
"attributes": {
"class": "align-left"
},
"content": [
"Як підкреслив Дещиця, підписана угода важлива ще й тому, що до сьогоднішнього дня між Україною і Монголією діяла угода 1979 року, яка була підписана свого часу між СРСР і Монгольською Народною Республікою, а потім була підтверджена українським урядом."
]
}
]
}
With jq, you can retrieve specifics parts. Ex:
jq '[.content | .[] | .content][0] | .[]' file
"У Посольстві України в Республіці Польща 8 листопада було підписано Угоду між урядом України та урядом Монголії про взаємне скасування віз."

Related

How to create yaml file according to this demo result?

I want to create a .yaml file by dict method in Python while reprint the following result:
MODEL:
MASK_ON: True
IMAGE_ONLY: True
META_ARCHITECTURE: "VLGeneralizedRCNN"
BACKBONE:
NAME: "build_vit_fpn_backbone"
VIT:
NAME: "layoutlmv3_base"
OUT_FEATURES: [ "layer3", "layer5", "layer7", "layer11" ]
DROP_PATH: 0.1
IMG_SIZE: [ 224,224 ]
POS_TYPE: "abs"
DATASETS:
TRAIN: ("publaynet_train",)
TEST: ("publaynet_val",)
so I tried to:
import yaml
def mk_yaml(file_path):
backbone = {
"NAME": "layoutlmv3_base"
}
vit = {
"NAME": "layoutlmv3_base",
"OUT_FEATURES": [ "layer3", "layer5", "layer7", "layer11" ],
"DROP_PATH": 0.1,
"IMG_SIZE": [ 224,224 ],
"POS_TYPE": "abs"
}
model = {
"MASK_ON": True,
"META_ARCHITECTURE": "VLGeneralizedRCNN",
"BACKBONE": backbone,
"VIT": vit}
datasets = {
"TRAIN": '("publaynet_train",)',
"TEST": '("publaynet_val",)'
}
desired_caps = {"MODEL":model, "DATASETS":datasets}
with open(file_path, 'w', encoding='utf-8') as f:
yaml.safe_dump(desired_caps, f)
However, my result is not on expected order even if I put "model" in front of "dataset" and why the key of "OUT_FEATURES" and "IMG_SIZE" is not on the list? I attched it below.
DATASETS:
TEST: ("publaynet_val",)
TRAIN: ("publaynet_train",)
MODEL:
BACKBONE:
NAME: layoutlmv3_base
MASK_ON: true
META_ARCHITECTURE: VLGeneralizedRCNN
VIT:
DROP_PATH: 0.1
IMG_SIZE:
- 224
- 224
NAME: layoutlmv3_base
OUT_FEATURES:
- layer3
- layer5
- layer7
- layer11
POS_TYPE: abs

Airflow emrAddStepsOperator unable to execute spark shaded jar

what should be in step type for spark app .. I am facing issue that master type not set or unable to recognize yarn .. seems it is considering the application as simple jar rather than spark submit mode when using emrAddStepsOperator .. please find attached airflow dag , error and emr screenshot
amazon emr cloud console manually adding spark job as a step
After adding spark jar type step rather than custom jar step .. gives option to give spark submit args and main method args separately
step type can be streaming or spark app or custom jar
My Error Message:
> Exception in thread "main" org.apache.spark.SparkException: A master URL must be set in your configuration
at org.apache.spark.SparkContext.<init>(SparkContext.scala:385)
at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2574)
at org.apache.spark.sql.SparkSession$Builder.$anonfun$getOrCreate$2(SparkSession.scala:934)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.sql.SparkSession$Builder.getOrCreate(SparkSession.scala:928)
at com.mcf.ExtractcustomerCategoryWiseSummarizedViews$.main(ExtractcustomerCategoryWiseSummarizedViews.scala:13)
at com.mcf.ExtractcustomerCategoryWiseSummarizedViews.main(ExtractcustomerCategoryWiseSummarizedViews.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.hadoop.util.RunJar.run(RunJar.java:323)
at org.apache.hadoop.util.RunJar.main(RunJar.java:236)
This is an example dag for a AWS EMR Pipeline.
Starting by creating a cluster, adding steps/operations, checking steps and finally when finished
terminating the cluster.
import time
from airflow.operators.python import PythonOperator
from datetime import timedelta
from airflow import DAG
from airflow.providers.amazon.aws.operators.emr_add_steps import EmrAddStepsOperator
from airflow.providers.amazon.aws.operators.emr_create_job_flow import EmrCreateJobFlowOperator
from airflow.providers.amazon.aws.operators.emr_terminate_job_flow import EmrTerminateJobFlowOperator
from airflow.providers.amazon.aws.sensors.emr_step import EmrStepSensor
from airflow.utils.dates import days_ago
SPARK_STEPS = [
{
'Name': 'PerformETL',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 's3://mydata/jars/open-0.0.1-SNAPSHOT.jar',
#'MainClass': 'com.sadim.main',
'Args': ['spark-submit',
'--deploy-mode',
'cluster',
'--master',
'yarn',
'--class',
'com.sadim.ExtractcustomerCategoryWiseSummarizedViews',
'--mode',
'DeltaLoadByDays',
'--noOfDaysBehindTodayForDeltaLoad',
'1',
'--s3InputPath',
's3://data-lake/documents/accountscore/categoriseddata/',
'--s3OutputPathcustomerCategoryWiseSummarizedViews',
's3://test-data/spark_output//customerCategoryWiseSummarizedViews//test'],
},
}
]
SPARK_STEPS2 = [
{
'Name': 'sadim_test3',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 's3://test-data/jars/scalatestnadeem-0.0.1-SNAPSHOT_v2.jar',
'MainClass': 'com.sadim.scalatestnadeem.Test',
'Args': ['spark-submit',
'--deploy-mode',
'client',
'--master',
'yarn',
'--conf',
'spark.yarn.submit.waitAppCompletion=true'],
},
}
]
SPARK_STEPS3 = [
{
'Name': 'sadim_test3',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 's3://mydata/jars/open-0.0.1-SNAPSHOT_masteryarnwithoutdependencyandtest.jar',
'MainClass': 'com.sadim.TestSadim',
'Args': ['spark-submit',
'--deploy-mode',
'client',
'--master',
'yarn',
'--conf',
'spark.yarn.submit.waitAppCompletion=true'],
},
}
]
SPARK_STEPS4 = [
{
'Name': 'PerformETL',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 's3://mydata/jars/open-0.0.1-SNAPSHOT.jar',
#'MainClass': 'com.sadim.ExtractcustomerCategoryWiseSummarizedViews',
'Args': ['com.sadim.ExtractcustomerCategoryWiseSummarizedViews',
'spark-submit',
'--deploy-mode',
'client',
'--master',
'yarn',
'--mode',
'DeltaLoadByDays',
'--noOfDaysBehindTodayForDeltaLoad',
'1',
'--s3InputPath',
's3://data-lake/documents/accountscore/categoriseddata/',
'--s3OutputPathcustomerCategoryWiseSummarizedViews',
's3://test-data/spark_output//customerCategoryWiseSummarizedViews//test'],
},
}
]
SPARK_STEPS5 = [
{
'Name': 'PerformETL',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 's3://mydata/jars/open-0.0.1-SNAPSHOT.jar',
#'MainClass': 'com.sadim.main',
'Args': ['com.sadim.ExtractcustomerCategoryWiseSummarizedViews',
'--mode',
'DeltaLoadByDays',
'--noOfDaysBehindTodayForDeltaLoad',
'1',
'--s3InputPath',
's3://data-lake/documents/accountscore/categoriseddata/',
'--s3OutputPathcustomerCategoryWiseSummarizedViews',
's3://test-data/spark_output//customerCategoryWiseSummarizedViews//test'],
},
}
]
JOB_FLOW_OVERRIDES = {
'Name': 'ob_emr_airflow_automation',
'ReleaseLabel': 'emr-6.6.0',
'LogUri': 's3://test-data/emr_logs/',
'Instances': {
'InstanceGroups': [
{
'Name': 'Master node',
'Market': 'ON_DEMAND',
'InstanceRole': 'MASTER',
'InstanceType': 'm5.xlarge',
'InstanceCount': 1
},
{
'Name': "Slave nodes",
'Market': 'ON_DEMAND',
'InstanceRole': 'CORE',
'InstanceType': 'm5.xlarge',
'InstanceCount': 1
}
],
'Ec2SubnetId': 'subnet-03129248888a14196',
'Ec2KeyName': 'datalake-emr-nodes',
'KeepJobFlowAliveWhenNoSteps': True,
'TerminationProtected': False
},
'BootstrapActions': [
{
'Name': 'Java11InstallBootstrap',
'ScriptBootstrapAction': {
'Path': 's3://test-data/jars/bootstrap.sh',
'Args': [
]
}
}
],
'Configurations': [
{
"Classification":"spark-defaults",
"Properties":{
"spark.driver.defaultJavaOptions":"-XX:OnOutOfMemoryError='kill -9 %p' - XX:MaxHeapFreeRatio=70",
"spark.executor.defaultJavaOptions":"-verbose:gc -Xlog:gc*::time - XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:OnOutOfMemoryError='kill -9 %p' -XX:MaxHeapFreeRatio=70 -XX:+IgnoreUnrecognizedVMOptions"
}
}
],
'JobFlowRole': 'DL_EMR_EC2_DefaultRole',
'ServiceRole': 'EMR_DefaultRole',
}
with DAG(
dag_id='emr_job_flow_manual_steps_dag_v6',
default_args={
'owner': 'airflow',
'depends_on_past': False,
'email': ['sadim.nadeem#sadim.com'],
'email_on_failure': False,
'email_on_retry': False,
},
dagrun_timeout=timedelta(hours=1),
start_date=days_ago(1),
schedule_interval='0 3 * * *',
tags=['example'],
) as dag:
# [START howto_operator_emr_manual_steps_tasks]
cluster_creator = EmrCreateJobFlowOperator(
task_id='create_job_flow',
job_flow_overrides=JOB_FLOW_OVERRIDES,
aws_conn_id='aws_default',
emr_conn_id='emr_default',
)
delay_python_task: PythonOperator = PythonOperator(task_id="delay_python_task",
dag=dag,
python_callable=lambda: time.sleep(400))
step_adder = EmrAddStepsOperator(
task_id='add_steps',
job_flow_id=cluster_creator.output,
aws_conn_id='aws_default',
steps=SPARK_STEPS5,
)
step_checker = EmrStepSensor(
task_id='watch_step',
job_flow_id=cluster_creator.output,
step_id="{{ task_instance.xcom_pull(task_ids='add_steps', key='return_value')[0] }}",
aws_conn_id='aws_default',
)
cluster_remover = EmrTerminateJobFlowOperator(
task_id='remove_cluster',
job_flow_id=cluster_creator.output,
aws_conn_id='aws_default',
)
cluster_creator >> step_adder >> step_checker >> cluster_remover
# [END howto_operator_emr_manual_steps_tasks]
# Task dependencies created via `XComArgs`:
# cluster_creator >> step_checker
# cluster_creator >> cluster_remover
The issue got fixed. We need to use the command-runner jar as jar option in emrAddStepsOperator and pass your specific ETL job jar inside args as
SPARK_STEPS = [
{
'Name': 'DetectAndLoadOrphanTransactions',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 'command-runner.jar',
#'MainClass': 'com.sadim.main',
'Args': [
'spark-submit',
'--deploy-mode',
'cluster',
'--master',
'yarn',
'--class',
'com.sadim.DetectAndLoadOrphanTransactions',
's3://nadeem-test-data/jars/open-0.0.1-SNAPSHOT_yarn_yarndep_maininpom.jar',
'--Txnspath',
's3://nadeem-test-data/spark_output//CategorizedTxnsDataset//2022_load_v2',
'--demographyPath',
's3://nadeem-test-data/spark_output//customerDemographics//2022_load_v2'
'--outPath',
's3://nadeem-test-data/spark_output//orphan_ihub_ids//2022_load_v2'],
},
}
]

I get Error parsing JSON: SyntaxError: Unexpected token u in JSON at position 0 when i try to parse a string from a JSON

fs.readFile('./horoscopy.json', 'utf8', (err, data) => {
if (err) {
console.log('File read failed:', err);
return;
}
try {
const horoscopeJson = JSON.parse(data);
console.log(horoscopeJson.horo.aries.today);
} catch (err) {
console.log('Error parsing JSON:', err);
}
});
This is my code
"aries": [
{
"yesterday": [
"\nСегодня вы вновь обретете несколько ослабшую в последнее время уверенность в себе. Ситуация начнет меняться, причем , как ни странно, в лучшую сторону.\n"
],
"today": [
"\nПостарайтесь сегодня не вмешиваться ни в чьи дела. Не разобравшись в тонкостях дела, вы можете натворить чего-то не того, действуя из лучших побуждений.\n"
],
"tomorrow": [
"\nНе тратьте сегодня свое и чужое время на всевозможные словесные изыски. Информация должна исходить от вас в четкой и понятной форме, в противном случае возможны малоприятные накладки.\n"
],
"tomorrow02": [
"\nПрежде чем покупать то, что вы давно хотели купить, постарайтесь приложить некоторые усилия к тому, чтобы попытаться заплатить не больше, чем эта вещь реально стоит.\n"
]
}
],
This is the json object I try to parse
Please help, I found similar problems but none of the solutions there helped
TIA
Json parsing is failing because payload is not in correct json format.
Remove "Aries:" and ,(comma) from your payload it should work
[
{
"yesterday": [
"\nСегодня вы вновь обретете несколько ослабшую в последнее время уверенность в себе. Ситуация начнет меняться, причем , как ни странно, в лучшую сторону.\n"
],
"today": [
"\nПостарайтесь сегодня не вмешиваться ни в чьи дела. Не разобравшись в тонкостях дела, вы можете натворить чего-то не того, действуя из лучших побуждений.\n"
],
"tomorrow": [
"\nНе тратьте сегодня свое и чужое время на всевозможные словесные изыски. Информация должна исходить от вас в четкой и понятной форме, в противном случае возможны малоприятные накладки.\n"
],
"tomorrow02": [
"\nПрежде чем покупать то, что вы давно хотели купить, постарайтесь приложить некоторые усилия к тому, чтобы попытаться заплатить не больше, чем эта вещь реально стоит.\n"
]
}
]
Try to update a line where you parse with this one:
const horoscopeJson = JSON.parse(`{${data}}`);
In fact, your file foes not conform to JSON format, that's the problem, curly brackets are missing.

FileNotFoundError: Could not find module while using jupyter notebook to import sklearn

While I try to import sklearn in the jupyter notebook, I got the error message as follows:
FileNotFoundError Traceback (most recent call last)
<ipython-input-2-ae13d4c4c2fb> in <module>
1 # Scikit-Learn ≥0.20 is required
----> 2 import sklearn
3 assert sklearn.__version__ >= "0.20"
D:\anaconda3\lib\site-packages\sklearn\__init__.py in <module>
80 from . import _distributor_init # noqa: F401
81 from . import __check_build # noqa: F401
---> 82 from .base import clone
83 from .utils._show_versions import show_versions
84
D:\anaconda3\lib\site-packages\sklearn\base.py in <module>
15 from . import __version__
16 from ._config import get_config
---> 17 from .utils import _IS_32BIT
18 from .utils._tags import (
19 _DEFAULT_TAGS,
D:\anaconda3\lib\site-packages\sklearn\utils\__init__.py in <module>
18 import warnings
19 import numpy as np
---> 20 from scipy.sparse import issparse
21
22 from .murmurhash import murmurhash3_32
D:\anaconda3\lib\site-packages\scipy\__init__.py in <module>
128
129 # Allow distributors to run custom init code
--> 130 from . import _distributor_init
131
132 from scipy._lib import _pep440
D:\anaconda3\lib\site-packages\scipy\_distributor_init.py in <module>
57 os.chdir(libs_path)
58 for filename in glob.glob(os.path.join(libs_path, '*dll')):
---> 59 WinDLL(os.path.abspath(filename))
60 finally:
61 os.chdir(owd)
D:\anaconda3\lib\ctypes\__init__.py in __init__(self, name, mode, handle, use_errno, use_last_error, winmode)
371
372 if handle is None:
--> 373 self._handle = _dlopen(self._name, mode)
374 else:
375 self._handle = handle
FileNotFoundError: Could not find module 'D:\anaconda3\lib\site-packages\scipy\.libs\libbanded5x.EHDKC2XVYTQQ5MALRS6XN2CUSS6SRL6P.gfortran-win_amd64.dll' (or one of its dependencies). Try using the full path with constructor syntax.
But I am pretty sure that the alledged missing file is there! Please advise!
!jupyter kernelspec list --json
{
"kernelspecs": {
"anaconda-base": {
"resource_dir": "C:\\Users\\Wei-shan\\AppData\\Roaming\\jupyter\\kernels\\anaconda-base",
"spec": {
"argv": [
"D:\\anaconda3\\python.exe",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"env": {},
"display_name": "Anaconda (base)",
"language": "python",
"interrupt_mode": "signal",
"metadata": {}
}
},
"python3": {
"resource_dir": "C:\\Users\\Wei-shan\\AppData\\Roaming\\jupyter\\kernels\\python3",
"spec": {
"argv": [
"D:\\anaconda3\\python.exe",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"env": {},
"display_name": "Python 3",
"language": "python",
"interrupt_mode": "signal",
"metadata": {}
}
},
"vpython": {
"resource_dir": "C:\\Users\\Wei-shan\\AppData\\Roaming\\jupyter\\kernels\\vpython",
"spec": {
"argv": [
"D:/Anaconda3/python.exe",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"env": {},
"display_name": "Python 3",
"language": "python",
"interrupt_mode": "signal",
"metadata": {}
}
}
}
}
I was experiencing the very same issue. In my case, it solved out after downgrading to tornado=6.0.4, and scikit-learn=0.23.2 and scypi=1.5.2.

why json.dumps add \n in the output,how should I remove it while saving it in a file?

Why does json.dumps add \n in the output, and how should I remove it while saving it in a file?
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import json
>>> data = {'people':[{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
>>> json.dumps(data, indent=4)
'{\n "people": [\n {\n "website": "stackabuse.com",\n "from": "Nebraska",\n "name": "Scott"\n }\n ]\n}'
>>>
You are using pretty print, if you want to avoid new lines do not use indent flag.
import json
data = {'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
print(json.dumps(data))
{"people": [{"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}]}
Your version just use nice formatting:
import json
data = {'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
print(json.dumps(data, indent=4))
{
"people": [
{
"name": "Scott",
"website": "stackabuse.com",
"from": "Nebraska"
}
]
}
In addition - new lines have no matter for json. Below two examples works same:
import json
data = {'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
with open('/tmp/file1', 'w') as f:
json.dump(data, f, indent=4)
with open('/tmp/file2', 'w') as f:
json.dump(data, f)
with open('/tmp/file1') as f:
print(json.load(f))
with open('/tmp/file2') as f:
print(json.load(f))
{'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
{'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
Because you ask it to, by providing indent. Just doing json.dumps(data) will not insert any newlines.

Resources