Commit 08618a0b by guanxing

add data generating code

parent 30c0ef86
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<content url="file://$USER_HOME$/mermaid-env" />
<orderEntry type="jdk" jdkName="Python 3.6 virtualenv at ~/mermaid-env" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PublishConfigData">
<serverData>
<paths name="server76">
<serverdata>
<mappings>
<mapping deploy="/local_workplace/Data_Generator" local="$PROJECT_DIR$" web="/" />
<mapping local="$USER_HOME$/mermaid-env" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="server77">
<serverdata>
<mappings>
<mapping deploy="/local_workspace" local="$PROJECT_DIR$" web="/" />
<mapping local="$USER_HOME$/mermaid-env" web="/" />
<mapping deploy="/guan_case" local="$USER_HOME$/guan_case" />
</mappings>
</serverdata>
</paths>
<paths name="server78">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
<mapping local="$USER_HOME$/mermaid-env" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="server79">
<serverdata>
<mappings>
<mapping deploy="/local_workspace" local="$PROJECT_DIR$" web="/" />
<mapping local="$USER_HOME$/mermaid-env" web="/" />
<mapping deploy="/guan_case" local="$USER_HOME$/guan_case" />
</mappings>
</serverdata>
</paths>
<paths name="server80">
<serverdata>
<mappings>
<mapping deploy="local_workspace/" local="$PROJECT_DIR$" web="local_workspace/" />
</mappings>
</serverdata>
</paths>
<paths name="sh1">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
<mapping local="$USER_HOME$/mermaid-env" web="/" />
</mappings>
</serverdata>
</paths>
</serverData>
</component>
</project>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyInterpreterInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="W29" />
<option value="E501" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6 virtualenv at ~/mermaid-env" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Data_Generator.iml" filepath="$PROJECT_DIR$/.idea/Data_Generator.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteMappingsManager">
<list>
<list>
<remote-mappings server-id="python@sftp://guanxing@192.168.1.80:22/home/guanxing/venv2/bin/python">
<settings>
<list>
<mapping local-root="/opt/share/dataset/enwiki_raw/AA" remote-root="/opt/share/dataset/enwiki_raw/AA" />
</list>
</settings>
</remote-mappings>
</list>
</list>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="WebServers">
<option name="servers">
<webServer id="848a8a6c-e81d-4781-a8f3-9c69a8f49087" name="server77" url="http://192.168.1.77">
<fileTransfer host="192.168.1.77" port="22" rootFolder="/home/guanxing" accessType="SFTP">
<advancedOptions>
<advancedOptions dataProtectionLevel="Private" />
</advancedOptions>
<option name="port" value="22" />
</fileTransfer>
</webServer>
<webServer id="adecf551-758c-4932-8fe5-d392fc3d3bd6" name="server76" url="http://192.168.1.76">
<fileTransfer host="192.168.1.76" port="22" rootFolder="/home/guanxing" accessType="SFTP">
<advancedOptions>
<advancedOptions dataProtectionLevel="Private" />
</advancedOptions>
<option name="port" value="22" />
</fileTransfer>
</webServer>
<webServer id="193ac8e3-143b-4b18-81a2-673c8cd1bbde" name="sh1" url="http://ubuntu@qcloud-sh1.chewrobot.com">
<fileTransfer host="ubuntu@qcloud-sh1.chewrobot.com" port="22" accessType="SFTP">
<advancedOptions>
<advancedOptions dataProtectionLevel="Private" />
</advancedOptions>
<option name="port" value="22" />
</fileTransfer>
</webServer>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="ea024f4b-1483-4c1a-9fdf-b40e0b174f4f" name="Default" comment="" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="CoverageDataManager">
<SUITE FILE_PATH="coverage/Data_Generator$test.coverage" NAME="test Coverage Results" MODIFIED="1536320505498" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
<SUITE FILE_PATH="coverage/Data_Generator$e2e_data_generator.coverage" NAME="e2e_data_generator Coverage Results" MODIFIED="1534488467362" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
<SUITE FILE_PATH="coverage/Data_Generator$test_find_replace_word.coverage" NAME="test_find_replace_word Coverage Results" MODIFIED="1536152535229" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
<SUITE FILE_PATH="coverage/Data_Generator$data_generator_including_upper.coverage" NAME="data_generator_including_upper Coverage Results" MODIFIED="1536819485685" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
<SUITE FILE_PATH="coverage/Data_Generator$data_generator_2.coverage" NAME="data_generator_2 Coverage Results" MODIFIED="1537947149405" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
<SUITE FILE_PATH="coverage/Data_Generator$upload_data_timer.coverage" NAME="upload_data_timer Coverage Results" MODIFIED="1536151950851" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file leaf-file-name="data_generator_including_upper.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/data_generator_including_upper.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-3701">
<caret line="14" column="33" lean-forward="false" selection-start-line="14" selection-start-column="33" selection-end-line="14" selection-end-column="33" />
<folding>
<element signature="e#0#21#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="e2e_data_generator.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/e2e_data_generator.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="673">
<caret line="188" column="0" lean-forward="false" selection-start-line="188" selection-start-column="0" selection-end-line="188" selection-end-column="0" />
<folding>
<element signature="e#0#13#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="e2e_data_generator_short.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/e2e_data_generator_short.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-771">
<caret line="87" column="8" lean-forward="false" selection-start-line="87" selection-start-column="8" selection-end-line="87" selection-end-column="8" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="data_generator_2.pyx" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/data_generator_2.pyx">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="511">
<caret line="102" column="36" lean-forward="false" selection-start-line="102" selection-start-column="36" selection-end-line="102" selection-end-column="36" />
<folding>
<element signature="e#0#21#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="main.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/main.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="342">
<caret line="19" column="0" lean-forward="false" selection-start-line="19" selection-start-column="0" selection-end-line="19" selection-end-column="0" />
<folding>
<element signature="e#0#43#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="fetch_rules.py" pinned="false" current-in-tab="false">
<entry file="file://$USER_HOME$/fetch_rules.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="126">
<caret line="15" column="0" lean-forward="false" selection-start-line="15" selection-start-column="0" selection-end-line="15" selection-end-column="0" />
<folding>
<marker date="1538036921773" expanded="true" signature="1140:1184" ph="select text units" />
<marker date="1538036921773" expanded="true" signature="2018:2143" ph="select text,... units" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="training_script.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/training_script.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="75">
<caret line="100" column="0" lean-forward="false" selection-start-line="100" selection-start-column="0" selection-end-line="100" selection-end-column="0" />
<folding>
<element signature="e#0#32#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="extract_1000wan_from_5000wan.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/extract_1000wan_from_5000wan.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="144">
<caret line="9" column="16" lean-forward="false" selection-start-line="9" selection-start-column="16" selection-end-line="9" selection-end-column="16" />
<folding>
<element signature="e#0#9#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="extract_1_10_from_1_100.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/extract_1_10_from_1_100.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="72">
<caret line="6" column="0" lean-forward="false" selection-start-line="6" selection-start-column="0" selection-end-line="6" selection-end-column="0" />
<folding>
<element signature="e#0#10#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="test_find_replace_word.py" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/test_find_replace_word.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="540">
<caret line="30" column="8" lean-forward="false" selection-start-line="30" selection-start-column="8" selection-end-line="30" selection-end-column="8" />
<folding />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Python Script" />
</list>
</option>
</component>
<component name="FindInProjectRecents">
<findStrings>
<find>key_word_index</find>
<find>key_word_inde</find>
<find>field</find>
<find>tag</find>
<find>end_index</find>
<find>replace_word_pool</find>
<find>official</find>
<find>sentence_set</find>
<find>final</find>
<find>total fi</find>
<find>total file number</find>
<find>total file</find>
<find>continue</find>
<find>rint</find>
<find>input_file_index</find>
<find>weight</find>
<find>json</find>
<find>prpr</find>
<find>pos_tag</find>
<find>tqdm</find>
<find>IndexErr</find>
<find>get_excep</find>
<find>jit</find>
<find>get_exce</find>
<find>splitted_sentence</find>
<find>print</find>
<find>excepted_excepted</find>
<find>read_rules</find>
<find>qa-train-hash</find>
<find>qa_key_hash</find>
</findStrings>
<replaceStrings>
<replace />
</replaceStrings>
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/upload_data_timer.py" />
<option value="$PROJECT_DIR$/load_jsonl.py" />
<option value="$PROJECT_DIR$/TextCounting.py" />
<option value="$USER_HOME$/similars_find_server/Text_tfidf_vector_similarity.py" />
<option value="$PROJECT_DIR$/Make_Correcting_Matrix.py" />
<option value="$PROJECT_DIR$/correcting_matrix_process.py" />
<option value="$PROJECT_DIR$/e2e_data_generator_short.py" />
<option value="$USER_HOME$/guan_case/Text_tfidf_vector_similarity.py" />
<option value="$PROJECT_DIR$/test_find_replace_word.py" />
<option value="$PROJECT_DIR$/e2e_data_generator.py" />
<option value="$PROJECT_DIR$/test.py" />
<option value="$PROJECT_DIR$/Duplicate_jsonl_file.py" />
<option value="$PROJECT_DIR$/extract_positive_from_total.py" />
<option value="$PROJECT_DIR$/data_generator_2.py" />
<option value="$PROJECT_DIR$/setup.py" />
<option value="$PROJECT_DIR$/data_generator_including_upper.py" />
<option value="$PROJECT_DIR$/main.py" />
<option value="$PROJECT_DIR$/data_generator_2.pyx" />
<option value="$USER_HOME$/fetch_rules.py" />
<option value="$PROJECT_DIR$/extract_1_10_from_1_100.py" />
<option value="$PROJECT_DIR$/extract_1000wan_from_5000wan.py" />
<option value="$PROJECT_DIR$/training_script.py" />
</list>
</option>
</component>
<component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsGulpfileManager">
<detection-done>true</detection-done>
<sorting>DEFINITION_ORDER</sorting>
</component>
<component name="ProjectFrameBounds" extendedState="6">
<option name="x" value="65" />
<option name="y" value="-4" />
<option name="width" value="1857" />
<option name="height" value="1092" />
</component>
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="" version="1">
<flattenPackages />
<showMembers />
<showModules />
<showLibraryContents />
<hideEmptyPackages />
<abbreviatePackageNames />
<autoscrollToSource />
<autoscrollFromSource />
<sortByType />
<manualOrder />
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="ProjectPane">
<subPane>
<expand>
<path>
<item name="coreference_resolution_data_generator_guan" type="b2602c69:ProjectViewProjectNode" />
<item name="Data_Generator" type="47feb1d3:ProjectViewModuleNode" />
</path>
<path>
<item name="coreference_resolution_data_generator_guan" type="b2602c69:ProjectViewProjectNode" />
<item name="Data_Generator" type="47feb1d3:ProjectViewModuleNode" />
<item name="coreference_resolution_data_generator_guan" type="462c0819:PsiDirectoryNode" />
</path>
</expand>
<select />
</subPane>
</pane>
<pane id="Scratches" />
<pane id="Scope" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="nodejs_interpreter_path.stuck_in_default_project" value="undefined stuck path" />
<property name="settings.editor.selected.configurable" value="web.server" />
<property name="WebServerToolWindowFactoryState" value="true" />
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="RunManager" selected="Python.data_generator_2">
<configuration name="data_generator_2" type="PythonConfigurationType" factoryName="Python" temporary="true">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Data_Generator" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/data_generator_2.pyx" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
</configuration>
<configuration name="data_generator_including_upper" type="PythonConfigurationType" factoryName="Python" temporary="true">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Data_Generator" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/data_generator_including_upper.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
</configuration>
<configuration name="test" type="PythonConfigurationType" factoryName="Python" temporary="true">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Data_Generator" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/test.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
</configuration>
<configuration name="test_find_replace_word" type="PythonConfigurationType" factoryName="Python" temporary="true">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Data_Generator" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/test_find_replace_word.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
</configuration>
<configuration name="upload_data_timer" type="PythonConfigurationType" factoryName="Python" temporary="true">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="Data_Generator" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/upload_data_timer.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
</configuration>
<list size="5">
<item index="0" class="java.lang.String" itemvalue="Python.upload_data_timer" />
<item index="1" class="java.lang.String" itemvalue="Python.test_find_replace_word" />
<item index="2" class="java.lang.String" itemvalue="Python.data_generator_including_upper" />
<item index="3" class="java.lang.String" itemvalue="Python.test" />
<item index="4" class="java.lang.String" itemvalue="Python.data_generator_2" />
</list>
<recent_temporary>
<list size="5">
<item index="0" class="java.lang.String" itemvalue="Python.data_generator_2" />
<item index="1" class="java.lang.String" itemvalue="Python.data_generator_including_upper" />
<item index="2" class="java.lang.String" itemvalue="Python.test" />
<item index="3" class="java.lang.String" itemvalue="Python.test_find_replace_word" />
<item index="4" class="java.lang.String" itemvalue="Python.upload_data_timer" />
</list>
</recent_temporary>
</component>
<component name="ShelveChangesManager" show_recycled="false">
<option name="remove_strategy" value="false" />
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="ea024f4b-1483-4c1a-9fdf-b40e0b174f4f" name="Default" comment="" />
<created>1532932049838</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1532932049838</updated>
</task>
<servers />
</component>
<component name="ToolWindowManager">
<frame x="65" y="-4" width="1855" height="1084" extended-state="6" />
<editor active="true" />
<layout>
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32941177" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" x="37" y="565" width="1855" height="1056" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Python Console" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Remote Host" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.2184225" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
<window_info id="Docker" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Database" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="SciView" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
<window_info id="File Transfer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32941177" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
</layout>
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="1" />
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<default-breakpoints>
<breakpoint type="python-exception">
<properties notifyOnTerminate="true" exception="BaseException">
<option name="notifyOnTerminate" value="true" />
</properties>
</breakpoint>
</default-breakpoints>
</breakpoint-manager>
<watches-manager />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/data_generator_including_upper.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="4212">
<caret line="244" column="4" lean-forward="false" selection-start-line="244" selection-start-column="4" selection-end-line="244" selection-end-column="4" />
<folding>
<element signature="e#0#21#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/e2e_data_generator.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="324">
<caret line="26" column="0" lean-forward="false" selection-start-line="26" selection-start-column="0" selection-end-line="26" selection-end-column="0" />
<folding>
<element signature="e#0#13#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test.py" />
<entry file="file://$PROJECT_DIR$/test_find_replace_word.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="540">
<caret line="30" column="8" lean-forward="false" selection-start-line="30" selection-start-column="8" selection-end-line="30" selection-end-column="8" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/guan_case/Text_tfidf_vector_similarity.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="72">
<caret line="30" column="3" lean-forward="false" selection-start-line="30" selection-start-column="3" selection-end-line="30" selection-end-column="3" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/TextCounting.py" />
<entry file="file://$PROJECT_DIR$/load_jsonl.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="162">
<caret line="9" column="34" lean-forward="false" selection-start-line="9" selection-start-column="34" selection-end-line="9" selection-end-column="34" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Make_Correcting_Matrix.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1368">
<caret line="81" column="0" lean-forward="false" selection-start-line="81" selection-start-column="0" selection-end-line="81" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/e2e_data_generator_short.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1440">
<caret line="87" column="8" lean-forward="false" selection-start-line="87" selection-start-column="8" selection-end-line="87" selection-end-column="8" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/data_generator_including_upper.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="4212">
<caret line="244" column="4" lean-forward="false" selection-start-line="244" selection-start-column="4" selection-end-line="244" selection-end-column="4" />
<folding>
<element signature="e#0#21#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/e2e_data_generator.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="324">
<caret line="26" column="0" lean-forward="false" selection-start-line="26" selection-start-column="0" selection-end-line="26" selection-end-column="0" />
<folding>
<element signature="e#0#13#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test.py" />
<entry file="file://$PROJECT_DIR$/test_find_replace_word.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="540">
<caret line="30" column="8" lean-forward="false" selection-start-line="30" selection-start-column="8" selection-end-line="30" selection-end-column="8" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/guan_case/Text_tfidf_vector_similarity.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="72">
<caret line="30" column="3" lean-forward="false" selection-start-line="30" selection-start-column="3" selection-end-line="30" selection-end-column="3" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/TextCounting.py" />
<entry file="file://$PROJECT_DIR$/load_jsonl.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="162">
<caret line="9" column="34" lean-forward="false" selection-start-line="9" selection-start-column="34" selection-end-line="9" selection-end-column="34" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Make_Correcting_Matrix.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1368">
<caret line="81" column="0" lean-forward="false" selection-start-line="81" selection-start-column="0" selection-end-line="81" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/e2e_data_generator_short.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1440">
<caret line="87" column="8" lean-forward="false" selection-start-line="87" selection-start-column="8" selection-end-line="87" selection-end-column="8" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/data_generator_including_upper.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="4212">
<caret line="244" column="4" lean-forward="false" selection-start-line="244" selection-start-column="4" selection-end-line="244" selection-end-column="4" />
<folding>
<element signature="e#0#21#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/e2e_data_generator.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="594">
<caret line="41" column="27" lean-forward="false" selection-start-line="41" selection-start-column="27" selection-end-line="41" selection-end-column="27" />
<folding>
<element signature="e#0#13#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/TextCounting.py" />
<entry file="file://$PROJECT_DIR$/Make_Correcting_Matrix.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="162">
<caret line="25" column="14" lean-forward="false" selection-start-line="25" selection-start-column="14" selection-end-line="25" selection-end-column="14" />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/guan_case/Text_tfidf_vector_similarity.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1062">
<caret line="84" column="55" lean-forward="false" selection-start-line="84" selection-start-column="55" selection-end-line="84" selection-end-column="55" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/e2e_data_generator.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1800">
<caret line="108" column="0" lean-forward="false" selection-start-line="108" selection-start-column="0" selection-end-line="108" selection-end-column="0" />
<folding>
<element signature="e#0#13#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/load_jsonl.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="162">
<caret line="9" column="34" lean-forward="false" selection-start-line="9" selection-start-column="34" selection-end-line="9" selection-end-column="34" />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/NewPartion/new_mermaid/mermaid/sessions/training_session.py" />
<entry file="file://$PROJECT_DIR$/Make_Correcting_Matrix.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="162">
<caret line="25" column="14" lean-forward="false" selection-start-line="25" selection-start-column="14" selection-end-line="25" selection-end-column="14" />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/mermaid-env/lib/python3.6/site-packages/redis/client.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="303">
<caret line="1658" column="8" lean-forward="false" selection-start-line="1658" selection-start-column="8" selection-end-line="1658" selection-end-column="8" />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/NewPartion/new_mermaid/mermaid/sessions/training_session.py" />
<entry file="file://$USER_HOME$/similars_find_server/Text_tfidf_vector_similarity.py" />
<entry file="file://$PROJECT_DIR$/upload_data_timer.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="468">
<caret line="28" column="43" lean-forward="false" selection-start-line="28" selection-start-column="43" selection-end-line="28" selection-end-column="43" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/correcting_matrix_process.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-989">
<caret line="31" column="4" lean-forward="false" selection-start-line="31" selection-start-column="4" selection-end-line="31" selection-end-column="4" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Make_Correcting_Matrix.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1368">
<caret line="81" column="0" lean-forward="false" selection-start-line="81" selection-start-column="0" selection-end-line="81" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/guan_case/Text_tfidf_vector_similarity.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="72">
<caret line="30" column="3" lean-forward="false" selection-start-line="30" selection-start-column="3" selection-end-line="30" selection-end-column="3" />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/mermaid-env/lib/python3.6/random.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="200">
<caret line="747" column="0" lean-forward="false" selection-start-line="747" selection-start-column="0" selection-end-line="747" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Duplicate_jsonl_file.py" />
<entry file="file://$PROJECT_DIR$/extract_positive_from_total.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="216">
<caret line="15" column="29" lean-forward="false" selection-start-line="15" selection-start-column="29" selection-end-line="15" selection-end-column="29" />
<folding>
<element signature="e#0#21#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test_find_replace_word.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="540">
<caret line="30" column="8" lean-forward="false" selection-start-line="30" selection-start-column="8" selection-end-line="30" selection-end-column="8" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/setup.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="90">
<caret line="5" column="46" lean-forward="false" selection-start-line="5" selection-start-column="46" selection-end-line="5" selection-end-column="46" />
<folding>
<element signature="e#0#32#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/fetch_rules.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="126">
<caret line="15" column="0" lean-forward="false" selection-start-line="15" selection-start-column="0" selection-end-line="15" selection-end-column="0" />
<folding>
<marker date="1538036921773" expanded="true" signature="1140:1184" ph="select text units" />
<marker date="1538036921773" expanded="true" signature="2018:2143" ph="select text,... units" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/extract_1_10_from_1_100.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="72">
<caret line="6" column="0" lean-forward="false" selection-start-line="6" selection-start-column="0" selection-end-line="6" selection-end-column="0" />
<folding>
<element signature="e#0#10#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/load_jsonl.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="162">
<caret line="9" column="34" lean-forward="false" selection-start-line="9" selection-start-column="34" selection-end-line="9" selection-end-column="34" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/extract_1000wan_from_5000wan.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="144">
<caret line="9" column="16" lean-forward="false" selection-start-line="9" selection-start-column="16" selection-end-line="9" selection-end-column="16" />
<folding>
<element signature="e#0#9#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/test.py" />
<entry file="file://$PROJECT_DIR$/TextCounting.py" />
<entry file="file://$PROJECT_DIR$/training_script.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="75">
<caret line="100" column="0" lean-forward="false" selection-start-line="100" selection-start-column="0" selection-end-line="100" selection-end-column="0" />
<folding>
<element signature="e#0#32#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/data_generator_including_upper.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-3701">
<caret line="14" column="33" lean-forward="false" selection-start-line="14" selection-start-column="33" selection-end-line="14" selection-end-column="33" />
<folding>
<element signature="e#0#21#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/e2e_data_generator.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="673">
<caret line="188" column="0" lean-forward="false" selection-start-line="188" selection-start-column="0" selection-end-line="188" selection-end-column="0" />
<folding>
<element signature="e#0#13#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/e2e_data_generator_short.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-771">
<caret line="87" column="8" lean-forward="false" selection-start-line="87" selection-start-column="8" selection-end-line="87" selection-end-column="8" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/main.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="342">
<caret line="19" column="0" lean-forward="false" selection-start-line="19" selection-start-column="0" selection-end-line="19" selection-end-column="0" />
<folding>
<element signature="e#0#43#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/data_generator_2.pyx">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="511">
<caret line="102" column="36" lean-forward="false" selection-start-line="102" selection-start-column="36" selection-end-line="102" selection-end-column="36" />
<folding>
<element signature="e#0#21#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</component>
</project>
\ No newline at end of file
import json
import os
from tqdm import tqdm_notebook
from mermaid import preprocessing as pp
from mermaid import models
import numpy as np
class CorrectingMatrix():
def __init__(self, texts_set, antecedent_scores, mention_starts, mention_ends, prpr):
self.original_text = texts_set
self.antecedent_scores = antecedent_scores
self.mention_starts = mention_starts
self.mention_ends = mention_ends
self.prpr = prpr
def find_sentence_by_mention(self, sentence, start_index, end_index):
total_length = len(sentence)
for i in range(start_index, -2, -1):
if sentence[i] == '.' or sentence[i] == ',' or i == 0: # 找到关键词前面的句号或逗号的index
cut_start = i
break
for j in range(end_index, total_length):
if sentence[j] == '.' or sentence[j] == ',' or j == total_length - 1: # 找到关键词后面的句号或逗号的 index
cut_end = j or total_length
break
if cut_start == 0:
modified_start = start_index
modified_end = end_index
return sentence[cut_start:cut_end], modified_start, modified_end # 返回这个句子,以及在新句子中关键词的位置.
else:
modified_start = start_index - cut_start - 1
modified_end = end_index - cut_start - 1
return sentence[cut_start + 1:cut_end], modified_start, modified_end
def replace_sentence(self, sentence, mention_starts, mention_ends, antecedent_score):
count = 0
for index in range(1, len(mention_starts)):
for index2 in range(0, index):
q, modified_start, modified_end \
= self.find_sentence_by_mention(sentence, \
mention_starts[index], \
mention_ends[index])
d, modified_start2, modified_end2 \
= self.find_sentence_by_mention(sentence, \
mention_starts[index2], \
mention_ends[index2])
to_replace = ['the'] + d[modified_start2:modified_end2 + 1] # 将句子中的关键词替换为 the ...
if 'the' in to_replace[1] or 'The' in to_replace[1]:
to_replace = to_replace[1:]
q[modified_start:modified_end + 1] = to_replace # 替换关键词
d = ' '.join(d)
q = ' '.join(q)
if index2 + 1 < antecedent_score.shape[1] and antecedent_score[index][index2 + 1] > 0:
label = 1
else:
label = 0
yield [{'d': d, 'q': q, 'label': label}], index, index2
def pack_data(self, prpr, i):
stream = pp.Stream()
row = np.array([])
column = np.array([])
mention_starts = self.mention_starts[i]
mention_ends = self.mention_ends[i]
single_text = self.original_text[i]
antecedent_score = self.antecedent_scores[i]
for dq, index, index2 in self.replace_sentence(single_text,mention_starts, mention_ends, antecedent_score):
stream.append(pp.Entry(**dq[0])) # dq pair in sequential stream
row = np.append(row, np.array([index])) # row matrix information
column = np.append(column, np.array([index2])) # Column matrix information
prpr.tokenize(a)
prpr.vectorize(a)
if self.save_correcting_stream:
stream.name = '343dev_dq_pair' + str(i)
stream.save(overwrite=True)
return [stream.d.vector, stream.q.vector], row, column
def generate_correcting_matrix(self, *args):
dq_matrix, row, column, model = [item for item in args]
length_of_mention = int(max(row))
correcting_matrix = -np.inf * np.ones([length_of_mention + 1, length_of_mention + 2])
result_matrix = model.predict(dq_matrix)
for score, row_index, column_index in zip(result_matrix, row, column):
correcting_matrix[int(row_index), int(column_index + 1)] = score
for index in range(int(max(row)) + 1):
correcting_matrix[index, 0] = 0
return correcting_matrix
def main(self, model_name):
total_correcting_matrix = []
model = models.Model.load(model_name)
for i in tqdm_notebook(range(len(self.original_text))):
dq_matrix, row, column = pack_data(self.prpr, i)
correcting_matrix = self.generate_correcting_matrix(dq_matrix, row, column, model)
total_correcting_matrix.append(correcting_matrix)
return total_correcting_matrix
\ No newline at end of file
import numpy as np
def sub_to_0(total_correcting_matrix, threshold):
new_total_correcting_matrix = []
for item in total_correcting_matrix:
new_item = item - threshold
for row in new_item:
row[0] = 0
new_total_correcting_matrix.append(new_item)
return new_total_correcting_matrix
def stretching_matrix(matrix, threshold):
new_matrix = []
for i, doc_matrix in enumerate(matrix):
new_doc_matrix = np.zeros((matrix[i].shape))
for j, mention_matrix in enumerate(doc_matrix):
for k, item in enumerate(mention_matrix):
if item < 0:
new_item = item * 40
new_doc_matrix[j, k] = new_item
else:
new_item = item * 2
new_doc_matrix[j, k] = new_item
new_matrix.append(new_doc_matrix)
return np.array(new_matrix)
def destretching_matrix(matrix, threshold):
new_matrix = []
for i, doc_matrix in enumerate(matrix):
new_doc_matrix = np.zeros((matrix[i].shape))
for j, mention_matrix in enumerate(doc_matrix):
for k, item in enumerate(mention_matrix):
if item < 0:
new_item = item / 40.0
new_doc_matrix[j, k] = new_item
else:
new_item = item / 2.0
new_doc_matrix[j, k] = new_item
new_matrix.append(new_doc_matrix)
return np.array(new_matrix)
def weighted_mixing(correcting_matrix, antecedent_scores):
new_matrix = []
for i, doc_matrix in enumerate(antecedent_scores):
new_doc_matrix = np.zeros((doc_matrix.shape))
for j, mention_matrix in enumerate(doc_matrix):
for k, item in enumerate(mention_matrix):
if k != 0:
new_item = correcting_matrix[i][j][k] + mention_matrix[k]
new_doc_matrix[j, k] = new_item
new_matrix.append(new_doc_matrix)
return np.array(new_matrix)
def reshape_correcting_matrix(matrix, antecedent_matrix):
reshaped_correcting_matrix = []
for i, item in enumerate(matrix):
origin_shape = antecedent_matrix[i].shape
to_modify_shape = matrix[i].shape
new_matrix = []
if origin_shape[1] > to_modify_shape[1]:
for index, item in enumerate(matrix[i]):
new_item = np.append(item, 0)
new_matrix.append(new_item)
elif origin_shape[1] <= to_modify_shape[1]:
for index, item in enumerate(matrix):
new_item = item[:origin_shape[1]]
new_matrix.append(new_item)
reshaped_correcting_matrix.append(np.array(new_matrix))
return np.array(reshaped_correcting_matrix)
def filter_by_confidence(matrix, threshold=0.3):
for item in matrix:
new_matrix = []
for i, doc_matrix in enumerate(matrix):
new_doc_matrix = np.zeros((matrix[i].shape))
for j, mention_matrix in enumerate(doc_matrix):
for k, item in enumerate(mention_matrix):
if item < -threshold:
new_item = item + threshold
new_doc_matrix[j, k] = new_item
elif item > threshold:
new_item = item - threshold
new_doc_matrix[j, k] = new_item
else:
new_item = 0
new_doc_matrix[j, k] = new_item
new_matrix.append(new_doc_matrix)
return np.array(new_matrix)
def l2_regularation_matrix(matrix):
new_matrix = []
for i, doc_matrix in enumerate(matrix):
new_doc_matrix = np.zeros((matrix[i].shape))
for j, mention_matrix in enumerate(doc_matrix):
for k, item in enumerate(mention_matrix):
if item < 0:
new_item = -(item * 2) ** 2
new_doc_matrix[j, k] = new_item
elif item > 0:
new_item = (item * 2) ** 2
new_doc_matrix[j, k] = new_item
else:
new_item = 0
new_doc_matrix[j, k] = new_item
new_matrix.append(new_doc_matrix)
return np.array(new_matrix)
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
from tqdm import tqdm
import copy
import random
from nltk import pos_tag
from data_generator_including_upper import DataGenerator
import multiprocessing as mp
import json
from numba import jit
import cProfile
import pstats
global _o
class DataGenerator2(DataGenerator):
def generate(self, ratio, copy_or_not, output_file_name_1_1=None):
with open(self.file_name, 'r') as file:
with open(self.output_file_name, 'a') as out:
text_tuple = [json.loads(jsonline)['text'] for jsonline in file.readlines()]
file_total_sentences = self.get_file_all_sentences(text_tuple)
print(f'length of file_total_sentences is : ', len(file_total_sentences))
for text in tqdm(text_tuple):
copied_file_total_sentences = copy.deepcopy(file_total_sentences)
dq_from_one_text, dq_1_1 = self.process_single_text(text, copied_file_total_sentences, ratio, copy_or_not)
for item in dq_from_one_text:
out.write(json.dumps(item) + '\n')
if output_file_name_1_1:
with open(output_file_name_1_1, 'a') as out2:
for item in dq_1_1:
out2.write(json.dumps(item) + '\n')
def get_file_all_sentences(self, text_tuple):
total_sentence = []
for text in text_tuple:
total_sentence.extend(self.split_text(text))
return total_sentence
def find_replace_word(self, former_sentence, key_word, upper_or_not):
replace_word_pool = []
excepted = self.split_sentence(former_sentence)
excepted.append('.') # 在句尾加上一个标点,方便返回最后一个大写名词.
if upper_or_not:
# 如果有大写的专有名词, 优先选择大写的专有名词(连续的)
replace_upper_word = ''
tag = False
for index in range(1, len(excepted)):
if excepted[index].lower() != excepted[index]:
tag = True
replace_upper_word += excepted[index] + ' '
else:
if tag:
replace_word_pool.append(replace_upper_word)
break
tag = False
else:
for item in pos_tag(excepted[1:]):
if 'NN' in item[1]:
replace_word_pool.append(item[0])
break
replace_word_pool = list(set(replace_word_pool))
for single_key_word in key_word:
replace_word_pool = [item for item in replace_word_pool if single_key_word not in item]
while len(replace_word_pool) < 1:
replace_word_pool.append(excepted[0])
return replace_word_pool
def append_negative_dq(self, dq_set, current_sentence, start_index, end_index, replace_word_pool, replace_word_index, former_sentence):
new_neg_sentence = copy.deepcopy(current_sentence)
new_neg_sentence[start_index] = replace_word_pool[replace_word_index]
new_neg_sentence = new_neg_sentence[:start_index+1]+new_neg_sentence[end_index:]
dq_negative = {'d': former_sentence,
'q': ' '.join(new_neg_sentence),
'label': 0}
dq_set.append(dq_negative) # negative dq from exception sentences list
return dq_set
def find_antecedent_sentence(self, the_index, splitted_sentence, former_sentence, exception_sentence, ratio, copy_or_not):
dq_set = []
dq_set_1_1 = []
i = 0
for wow, index in enumerate(the_index):
if index == len(splitted_sentence) - 1:
break
start_index = index+1
end_index = min(index+1+the_index[index],len(splitted_sentence)-1)
if end_index>38 or len(former_sentence)>40 or len(former_sentence) < 5:
break
if splitted_sentence[start_index].lower()!=splitted_sentence[start_index]:
upper_or_not = True
else:
upper_or_not = False
key_word = splitted_sentence[start_index:end_index]
pos_tag_of_sentence = pos_tag(splitted_sentence)
if 'NN' in pos_tag_of_sentence[start_index][1] and 'NN' not in pos_tag_of_sentence[end_index][1] and \
all(single_key_word in former_sentence for single_key_word in key_word):
# 关键词都在前一句中
# 找到所有关键词的所有 index
dq = {'d': ' '.join(former_sentence), \
'q': ' '.join(splitted_sentence), \
'label': 1} # positive dq
dq_set_1_1.append(dq)
if copy_or_not:
for i in range(ratio):
dq_set.append(dq)
else:
dq_set.append(dq)
for i in range(ratio):
# 找5个不相关的句子,替换关键词
single_exception_sentence = random.choice(exception_sentence)
exception_replace_word = self.find_replace_word(single_exception_sentence, key_word, upper_or_not)
if i == 0:
dq_set_1_1 = self.append_negative_dq(dq_set_1_1, splitted_sentence, start_index, end_index, exception_replace_word,0,single_exception_sentence)
dq_set = self.append_negative_dq(dq_set, splitted_sentence, start_index, end_index, exception_replace_word, 0, single_exception_sentence)
return dq_set, dq_set_1_1
def get_exception_sentence(self, sentence_set, former_sentence, sentence):
# 找到并返回在文本中,除了当前句和当前句前x句以外的所有句子
try:
sentence_set.remove(former_sentence)
sentence_set.remove(sentence)
except ValueError:
pass
return sentence_set
def process_single_text(self, text, *args):
sentence_set = self.split_text(text)
total_sentences, ratio, copy_or_not = args[0], args[1], args[2]
total_dq = []
total_dq_1_1 = []
for sent_index, sentence in enumerate(sentence_set):
splitted_sentence = self.split_sentence(sentence)
if len(splitted_sentence)<3:
continue
upper_word_index = self.existing_upper_word(splitted_sentence) # 返回大写词的前一个 index
the_index = self.find_key_word_index(splitted_sentence, upper_word_index)
if the_index!={}:
for i in range(0, min(sent_index, 3)):
former_sentence = sentence_set[max(0, sent_index - 1 - i)] # 找到前1.2,3句
exception_sentence = self.get_exception_sentence(total_sentences, former_sentence, sentence)
former_sentence = self.split_sentence(former_sentence)
if len(former_sentence) < 3:
continue
result, result1_1 = self.find_antecedent_sentence(the_index, splitted_sentence, former_sentence,
exception_sentence, ratio, copy_or_not)
total_dq.extend(result)
total_dq_1_1.extend(result1_1)
return total_dq, total_dq_1_1
def split_text(self, text):
cdef str s = ',.\'()!:\-'
for c in s:
text = text.replace(c, ' ' + c + ' ')
text = text.replace("\"", ' ')
sentence_set = text.split('.')
return sentence_set
def split_sentence(self, str sentence):
return sentence.split()
def cprofile_run(self):
_o = self
cProfile.run('_o.generate()', 'restats')
p = pstats.Stats('restats')
p.sort_stats('cumulative').print_stats(30)
from tqdm import tqdm
import pathlib
import os
import copy
import json
import random
import cProfile
import pstats
from multiprocessing import Pool
from nltk import pos_tag
class DataGenerator(object):
def __init__(self, file_name, output):
self.file_name = file_name
self.output_file_name = output
print('output file name is:',self.output_file_name)
def generate(self):
with open(self.file_name, 'r') as file:
with open(self.output_file_name, 'a') as out:
text_tuple = [json.loads(jsonline)['text'] for jsonline in file.readlines()]
file_total_sentences = self.get_file_all_sentences(text_tuple)
print('length of file_total_sentences is : ', len(file_total_sentences))
pos_tag_map = {}
for text in text_tuple:
for sent in self.split_text(text):
processed_sent = self.split_sentence(sent)
pos_tag_map.setdefault(sent, pos_tag(processed_sent))
for text in tqdm(text_tuple):
#copied_file_total_sentences = copy.deepcopy(file_total_sentences)
dq_from_one_text = self.process_single_text(text, file_total_sentences, pos_tag_map)
for item in dq_from_one_text:
out.write(json.dumps(item) + '\n')
def get_file_all_sentences(self, text_tuple):
total_sentence = []
for text in text_tuple:
total_sentence.extend(self.split_text(text))
return total_sentence
def existing_upper_word(self, sentence):
indexes = {}
i = 1
while i < len(sentence):
upper_num = 0
while i+upper_num<len(sentence) and sentence[i + upper_num].lower() != sentence[i + upper_num]:
upper_num += 1
if upper_num!=0:
indexes.setdefault(i-1, upper_num)
i += 1+upper_num
return indexes
def find_key_word_index(self, sentence, upper_word_index):
the_index = [index for index, word in enumerate(sentence) if word == 'the' or word == 'The']
for item in the_index:
if item not in (upper_word_index.keys()):
upper_word_index.setdefault(item, 1)
return upper_word_index
def process_single_text(self, text, exception_sentence, pos_tag_map):
sentence_set = self.split_text(text)
total_dq = []
for sent_index, sentence in enumerate(sentence_set):
splitted_sentence = self.split_sentence(sentence)
pos_tag_of_splitted_sentence = pos_tag_map[sentence]
if len(splitted_sentence)<3:
continue
upper_word_index = self.existing_upper_word(splitted_sentence)
the_index = self.find_key_word_index(splitted_sentence, upper_word_index)
if the_index!={}:
for i in range(0, min(sent_index, 3)):
#try:
former_sentence = sentence_set[max(0, sent_index - 1 - i)]
#exception_sentence = self.get_exception_sentence(exception_sentence, former_sentence, sentence)
copied_sentence_set = copy.deepcopy(sentence_set)
exception_sentence = self.get_exception_sentence(copied_sentence_set, former_sentence, sentence)
splitted_former_sentence = self.split_sentence(former_sentence)
if len(former_sentence) < 3 or len(exception_sentence) < 1:
continue
result = self.find_antecedent_sentence(the_index, \
splitted_sentence, pos_tag_of_splitted_sentence,
splitted_former_sentence, pos_tag_map,
exception_sentence)
total_dq.extend(result)
#except:
# raise IndexError
return total_dq
def get_exception_sentence(self, sentence_set, former_sentence, sentence):
try:
sentence_set.remove(former_sentence)
sentence_set.remove(sentence)
except:
pass
return sentence_set
'''
def find_total_exception_replace_word(self, exception_sentence, key_word):
total_replace_word = []
for sentence in exception_sentence:
total_replace_word.extend([item[0].lower() for item in pos_tag(sentence) if 'NN' in item[1]])
if len(total_replace_word) >= 10:
break
replace_word_pool = list(set(total_replace_word))
for single_key_word in key_word:
replace_word_pool = [item for item in replace_word_pool if single_key_word not in item]
return replace_word_pool
'''
def get_pnn(self, splitted_sentence, index):
upper_words = []
for item in splitted_sentence[index+1:]:
if item.lower()!=item:
upper_words.append(item)
return upper_words
def find_antecedent_sentence(self, the_index, splitted_sentence,pos_tag_of_splitted_sent, former_sentence, pos_tag_map, exception_sentence):
dq_set = []
for index in the_index:
if index == len(splitted_sentence) - 1:
break
start_index = index+1
end_index = min(index+1+the_index[index],len(splitted_sentence)-1)
if end_index>40 or len(former_sentence)>40 or len(former_sentence) < 5:
break
if splitted_sentence[start_index].lower()!=splitted_sentence[start_index]:
upper_or_not = True
else:
upper_or_not = False
key_word = splitted_sentence[start_index:end_index]
if 'NN' in pos_tag_of_splitted_sent[start_index][1] and 'NN' not in pos_tag_of_splitted_sent[end_index][1]:
if all(single_key_word in former_sentence for single_key_word in key_word):
dq = {'d': ' '.join(former_sentence),\
'q': ' '.join(splitted_sentence),\
'label': 1} # positive dq
dq_set.append(dq)
for i in range(10):
chosen_sentence = random.choice(exception_sentence)
splitted_chosen_sentence = self.split_sentence(chosen_sentence)
exception_replace_word = self.find_replace_word(splitted_chosen_sentence, chosen_sentence, pos_tag_map, key_word, upper_or_not)
if len(exception_replace_word)<1:
exception_replace_word = ['item']
dq_set = self.append_negative_dq(dq_set, splitted_sentence, start_index, end_index, exception_replace_word, 0, splitted_chosen_sentence)
return dq_set
def append_negative_dq(self, dq_set, current_sentence, start_index, end_index, replace_word_pool, replace_word_index, former_sentence):
new_neg_sentence = copy.deepcopy(current_sentence)
new_neg_sentence[start_index] = replace_word_pool[replace_word_index]
new_neg_sentence = new_neg_sentence[:start_index+1]+new_neg_sentence[end_index:]
dq_negative = {'d': ' '.join(former_sentence),
'q': ' '.join(new_neg_sentence),
'label': 0}
dq_set.append(dq_negative) # negative dq from exception sentences list
return dq_set
def find_replace_word(self, former_sentence, original_former_sentence, pos_tag_map, key_word, upper_or_not):
replace_word_pool = []
excepted = former_sentence
excepted.append('.')
if upper_or_not:
replace_upper_word = ''
tag = False
for index in range(1, len(excepted)):
if excepted[index].lower() != excepted[index]:
tag = True
replace_upper_word += excepted[index] + ' '
else:
if tag:
replace_word_pool.append(replace_upper_word)
replace_upper_word = ''
tag = False
break
if replace_word_pool == []:
for item in pos_tag_map[original_former_sentence][1:]:
if 'NN' in item[1]:
replace_word_pool.append(item[0])
break
else:
for item in pos_tag_map[original_former_sentence][1:]:
if 'NN' in item[1]:
replace_word_pool.append(item[0])
break
for single_key_word in key_word:
replace_word_pool = [item for item in replace_word_pool if single_key_word not in item]
return replace_word_pool
def split_text(self, text):
sentence_set = text.split('.')
return sentence_set
def split_sentence(self, sentence):
s = ',.\'()!:\-'
for c in s:
sentence = sentence.replace(c, ' ' + c + ' ')
sentence = sentence.replace("\"", ' ')
sentence = sentence.replace("\n", '')
return sentence.split()
def cprofile_run(self):
global _o
_o = self
cProfile.run('_o.generate()', 'restats')
p = pstats.Stats('restats')
p.sort_stats('cumulative').print_stats(30)
'''
file_list = []
for index, item in enumerate(os.walk('/opt/share/dataset/enwiki_raw')):
if index == 0:
continue
for i in range(len(item[2])):
file_list.append(pathlib.PurePath(item[0]).joinpath(item[2][i]))
#file_list = file_list[:50]
#random.shuffle(file_list)
print('total file number is: ', len(file_list))
for index, file_path in tqdm(enumerate(file_list[8000:9000])):
out_path = '/opt/share/dataset/enwiki_output/final_large_enwiki_dq/Replace_Upper_Noun_medium_dq_pairs' + str(index) +'.jsonl'
generator = DataGenerator(file_path, out_path)
generator.generate()
file_list = []
for index, item in enumerate(os.walk('/opt/share/data/enwiki_similar_texts')):
for i in range(len(item[2])):
file_name = pathlib.PurePath(item[0]).joinpath(item[2][i])
file_list.append(file_name)
print('file list is: ', file_list)
for file_path in tqdm(file_list):
out_path = '/opt/share/data/enwiki_output/Replace_Upper_Noun_medium_dq_pairs.jsonl'
# out_path = '/opt/share/data/enwiki_output/Replace_Upper_Noun_small_dq_pairs.jsonl'
generator = DataGenerator(file_path, out_path)
generator.generate()
'''
if __name__=='__main__':
file_list = []
for index, item in enumerate(os.walk('/opt/share/dataset/enwiki_small_raw')):
if index == 0:
continue
for i in range(len(item[2])):
file_list.append(pathlib.PurePath(item[0]).joinpath(item[2][i]))
print('total file number is: ', len(file_list))
for index, file_path in tqdm(enumerate(file_list)):
print('processing file: ', file_path)
out_path = '/opt/share/dataset/enwiki_output/enwiki_neg_from_all_data/original_data_1_10.jsonl'
generator = DataGenerator(file_path, out_path)
generator.cprofile_run()
#generator.generate()
import random
from tqdm import tqdm
import pathlib
import os
import copy
import json
import random
from nltk import pos_tag
class DataGenerator(object):
def __init__(self, file_name, output):
self.file_name = file_name
self.output_file_name = output
print(f'output file name is: {self.output_file_name}')
def generate(self):
with open(self.file_name, 'r') as file:
with open(self.output_file_name, 'a') as out:
text_tuple = [json.loads(jsonline)['text'] for jsonline in file.readlines()]
# random.shuffle(text_tuple)
for text in tqdm(text_tuple):
dq_from_one_text = self.process_single_text(text)
for item in dq_from_one_text:
out.write(json.dumps(item) + '\n')
def existing_upper_word(self, sentence):
'''
如果有大写的专有名词,返回位置和 True/False.
'''
for index, item in enumerate(sentence[1:]):
if item.lower() != item:
return True, index
else:
return False, None
def process_single_text(self, text):
sentence_set = self.split_text(text)
total_dq = []
for sent_index, sentence in enumerate(sentence_set):
splitted_sentence = self.split_sentence(sentence)
if ' the ' in sentence or 'The ' in sentence :
the_index = self.find_key_word(splitted_sentence)
for i in range(0, min(sent_index, 3)):
#try:
former_sentence = sentence_set[max(0, sent_index - 1 - i)] # 找到前1.2,3句
exception_sentence = self.get_exception_sentence(sentence_set, former_sentence, sentence)
former_sentence = self.split_sentence(former_sentence)
result = self.find_antecedent_sentence(the_index, splitted_sentence, former_sentence,
exception_sentence)
total_dq.extend(result)
#except:
# continue
return total_dq
def get_exception_sentence(self, sentence_set, former_sentence, sentence):
# 找到并返回在文本中,除了当前句和当前句前x句以外的所有句子
exception_sentence = []
for item in sentence_set:
if item != sentence and item != former_sentence:
exception_sentence.append(self.split_sentence(item))
return exception_sentence
def find_total_exception_replace_word(self, exception_sentence, key_word):
total_replace_word = []
for sentence in exception_sentence:
total_replace_word.extend([item[0].lower() for item in pos_tag(sentence) if 'NN' in item[1]])
if len(total_replace_word) >= 5:
break
total_replace_word = set(total_replace_word)
if key_word in total_replace_word:
total_replace_word.remove(key_word)
return [item for item in total_replace_word]
def find_antecedent_sentence(self, the_index, splitted_sentence, former_sentence, exception_sentence):
dq_set = []
for index in the_index:
if index == len(splitted_sentence) - 1:
break
key_word = splitted_sentence[index + 1]
if index + 2 < len(splitted_sentence):
key_word_later = splitted_sentence[index + 2]
else:
key_word_later = ' '
pos_tag_of_sentence = pos_tag(splitted_sentence)
if 'NN' in pos_tag_of_sentence[index+1][1] and 'NN' not in pos_tag([key_word_later])[0][1]:
if key_word in former_sentence:
key_word_index = former_sentence.index(key_word)
total_exception_replace_word_pool = self.find_total_exception_replace_word(exception_sentence, key_word)
if len(total_exception_replace_word_pool) < 5:
break
replace_word_pool = self.find_replace_word(former_sentence, key_word_index, total_exception_replace_word_pool, key_word.lower())
dq = {'d': ' '.join(former_sentence),\
'q': ' '.join(splitted_sentence),\
'label': 1} # positive dq
dq_set.append(dq)
for i in range(5):
# 找5个不相关的句子,替换关键词
single_exception_sentence = random.choice(exception_sentence)
exception_replace_word = None
next_index = 0
single_exception_sentence_pos_tag = pos_tag(single_exception_sentence)
for word_index, word in enumerate(single_exception_sentence):
if 'NN' in single_exception_sentence_pos_tag[word_index][1]:
exception_replace_word += word
# 找到连续的大写专有名词
next_word =
while word.lower()!=word:
exception_replace_word += ' ' + word
next_index = next_index + 1
word = single_exception_sentence[next_index + word_index]
exception_replace_word = word
if not exception_replace_word:
exception_replace_word = total_exception_replace_word_pool[i]
new_neg_sentence = copy.deepcopy(splitted_sentence)
new_neg_sentence[index + 1] = exception_replace_word
dq_negative = {'d': ' '.join(single_exception_sentence),
'q': ' '.join(new_neg_sentence),
'label': 0}
dq_set.append(dq_negative) # negative dq from exception sentences list
for j in range(5):
# 前一句中替换关键词
new_neg_sentence = copy.deepcopy(splitted_sentence)
new_neg_sentence[index + 1] = replace_word_pool[j]
# negative dq by replacing wrong key word
dq_negative = {
'd': ' '.join(former_sentence),\
'q': ' '.join(new_neg_sentence),\
'label': 0}
dq_set.append(dq_negative)
return dq_set
def find_replace_word(self, former_sentence, key_word_index, total_exception_replace_word, key_word):
i = 0
excepted = former_sentence[:key_word_index] + former_sentence[key_word_index + 1:]
replace_word_pool = set([item[0].lower() for item in pos_tag(excepted) if 'NN' in item[1]])
if key_word in replace_word_pool:
replace_word_pool.remove(key_word)
while len(replace_word_pool) < 5:
replace_word_pool.add(total_exception_replace_word[i])
i+=1
return [item for item in replace_word_pool]
def split_text(self, text):
sentence_set = text.split('.')
return sentence_set
def split_sentence(self, sentence):
s = ',.\'()!:\-'
for c in s:
sentence = sentence.replace(c, ' ' + c + ' ')
sentence = sentence.replace("\"", ' ')
return sentence.split()
def find_key_word(self, sentence):
the_index = [index for index, word in enumerate(sentence) if word == 'the' or word == 'The']
return the_index
'''
file_list = []
for index, item in enumerate(os.walk('/opt/share/dataset/enwiki_raw')):
if index == 0:
continue
for i in range(len(item[2])):
file_list.append(pathlib.PurePath(item[0]).joinpath(item[2][i]))
file_list = file_list[:50]
random.shuffle(file_list)
print('total file number is: ', len(file_list))
'''
file_list = []
for index, item in enumerate(os.walk('/opt/share/data/enwiki_similar_texts')):
for i in range(len(item[2])):
file_name = pathlib.PurePath(item[0]).joinpath(item[2][i])
file_list.append(file_name)
print('file list is: ', file_list)
for file_path in tqdm(file_list[:4]):
out_path = '/opt/share/data/enwiki_output/large_dq_pairs_from_similar_text.jsonl'
generator = DataGenerator(file_path, out_path)
generator.generate()
import random
from tqdm import tqdm
import pathlib
import os
import copy
import json
from nltk import pos_tag
class ShortDataGenerator(object):
def __init__(self, file_name, output):
self.file_name = file_name
self.output_file_name = output
print(f'output file name is: {self.output_file_name}')
def generate(self):
with open(self.file_name, 'r') as file:
with open(self.output_file_name, 'a') as out:
text_tuple = [json.loads(jsonline)['text'] for jsonline in file.readlines()]
for text in tqdm(text_tuple):
dq_from_one_text = self.process_single_text(text)
for item in dq_from_one_text:
out.write(json.dumps(item) + '\n')
def process_single_text(self, text):
sentence_set = self.split_text(text)
total_dq = []
for sent_index, sentence in enumerate(sentence_set):
if ' the ' in sentence or 'The ' in sentence:
splitted_sentence = self.split_sentence(sentence)
the_index = self.find_key_word(splitted_sentence)
for i in range(0, min(sent_index, 3)):
try:
former_sentence = sentence_set[max(0, sent_index - 1 - i)] # 找到前1.2,3句
exception_sentence = self.get_exception_sentence(sentence_set, former_sentence, sentence)
former_sentence = self.split_sentence(former_sentence)
result = self.find_antecedent_sentence(the_index, splitted_sentence, former_sentence,
exception_sentence)
total_dq.extend(result)
except:
print('error')
continue
return total_dq
def get_exception_sentence(self, sentence_set, former_sentence, sentence):
# 找到并返回在文本中,除了当前句和当前句前x句以外的所有句子
exception_sentence = []
for item in sentence_set:
if item != sentence and item != former_sentence:
exception_sentence.append(self.split_sentence(item))
return exception_sentence
def find_replace_word(self, former_sentence, key_word_index, total_exception_replace_word, key_word):
i = 0
start = max(0, key_word_index-5)
end = min(len(former_sentence), key_word_index+6)
excepted = former_sentence[start:key_word_index] + former_sentence[(key_word_index+1):end]
replace_word_pool = set([item[0].lower() for item in pos_tag(excepted) if 'NN' in item[1]])
if key_word.lower() in replace_word_pool:
replace_word_pool.remove(key_word.lower())
while len(replace_word_pool) < 5:
replace_word_pool.add(total_exception_replace_word[i])
i+=1
return [item for item in replace_word_pool]
def split_text(self, text):
sentence_set = text.split('.')
return sentence_set
def split_sentence(self, sentence):
s = ',.\'()!:\-'
for c in s:
sentence = sentence.replace(c, ' ' + c + ' ')
sentence = sentence.replace("\"", ' ')
return sentence.split()
def find_key_word(self, sentence):
the_index = [index for index, word in enumerate(sentence) if word == 'the' or word == 'The']
return the_index
def find_total_exception_replace_word(self, exception_sentence, key_word):
total_replace_word = []
for sentence in exception_sentence:
total_replace_word.extend([item[0].lower() for item in pos_tag(sentence) if 'NN' in item[1]])
if len(total_replace_word) >= 5:
break
total_replace_word = set(total_replace_word)
if key_word.lower() in total_replace_word:
total_replace_word.remove(str(key_word.lower()))
return [item for item in total_replace_word]
def find_antecedent_sentence(self, the_index, splitted_sentence, former_sentence, exception_sentence):
'''
Return positive and negative dq pairs of length 10 around the key word
:param the_index: the index of 'the'
:param splitted_sentence: current 'q' sentence
:param former_sentence: correlated former sentence
:param exception_sentence: sentences except current 'q' sentence and former sentence
:return: dq_pairs_list
'''
dq_set = []
for index in the_index:
if index == len(splitted_sentence)-1:
break
key_word = splitted_sentence[index + 1]
if index+2 < len(splitted_sentence):
key_word_later = splitted_sentence[index+2]
else:
key_word_later = ' '
if 'NN' in pos_tag([key_word])[0][1] and 'NN' not in pos_tag([key_word_later])[0][1]:
if key_word in former_sentence:
key_word_index = former_sentence.index(key_word)
total_exception_replace_word_pool = self.find_total_exception_replace_word(exception_sentence, key_word)
if len(set(total_exception_replace_word_pool))<5:
break
replace_word_pool = self.find_replace_word(former_sentence, key_word_index, total_exception_replace_word_pool, key_word)
former_sentence_start_index = max(0, key_word_index-5)
former_sentence_end_index = key_word_index+6
current_sentence_start_index = max(0, index-5)
current_sentence_end_index = index+6
dq = {'d': ' '.join(former_sentence[former_sentence_start_index:former_sentence_end_index]), \
'q': ' '.join(splitted_sentence[current_sentence_start_index:current_sentence_end_index]), \
'label': 1} # positive dq
dq_set.append(dq)
for i in range(5):
# 找5个不相关的句子,替换关键词
short_exception_sentence = random.choice(exception_sentence)[:10]
exception_replace_word = None
for word in short_exception_sentence:
if 'NN' in pos_tag([word])[0][1]:
exception_replace_word = word
if not exception_replace_word:
exception_replace_word = total_exception_replace_word_pool[i]
new_neg_sentence = copy.deepcopy(splitted_sentence)
new_neg_sentence[index + 1] = exception_replace_word
dq_negative = {'d': ' '.join(short_exception_sentence),
'q': ' '.join(new_neg_sentence[current_sentence_start_index:current_sentence_end_index]), 'label': 0}
dq_set.append(dq_negative) # negative dq from exception sentences list
for j in range(5):
# 前一句中替换关键词
new_neg_sentence = copy.deepcopy(splitted_sentence)
new_neg_sentence[index + 1] = replace_word_pool[j]
# negative dq by replacing wrong key word
dq_negative = {'d': ' '.join(former_sentence[former_sentence_start_index:former_sentence_end_index]), \
'q': ' '.join(new_neg_sentence[current_sentence_start_index:current_sentence_end_index]), \
'label': 0}
dq_set.append(dq_negative)
return dq_set
file_list = []
for index, item in enumerate(os.walk('/opt/share/dataset/enwiki_similar_texts')):
print(item)
for i in range(len(item[2])):
file_name = pathlib.PurePath(item[0]).joinpath(item[2][i])
file_list.append(file_name)
print('file list is: ', file_list)
for file_path in tqdm(file_list):
out_path = '/opt/share/dataset/enwiki_output/short_dq_pairs_from_similar_text_no_random.jsonl'
generator = ShortDataGenerator(file_path, out_path)
generator.generate()
import os
import shutil
dir = '/opt/share/dataset/enwiki_output/enwiki_neg_from_all_data/1_10_no_duplicate_dq_pairs_mini/'
dir = '/opt/share/dataset/enwiki_output/enwiki_neg_from_all_data/1_10_dq_pairs_all_5000wan/'
dir = '/opt/share/dataset/enwiki_raw/'
file_list = os.listdir(dir)
small = []
for item in file_list:
if 'AV' in item or 'AU' in item:
small.append(item)
if 'AX' in item:
if int(item[-8:-6])<49:
small.append(item)
'''
i=-1
while len(small)<250:
small.append(file_list[i])
i-=1
'''
small_dir = '/opt/share/dataset/enwiki_output/enwiki_neg_from_all_data/test1/'
if not os.path.exists(small_dir):
os.mkdir(small_dir)
for item in small:
shutil.copy(dir+item, small_dir+item)
import sys
import json
import os
input_path_dir = sys.argv[1]
out_path_dir = sys.argv[2]
n = int(sys.argv[3])
print(f'extract {n} negative from 1:1000 data...')
def extract(n, input_path_dir, out_path_dir):
dq_set = []
count_down = 0
line_index = 0
root_path = input_path_dir
in_file_list = [input_path_dir+item for item in os.listdir(root_path)]
out_file_list = [out_path_dir+item for item in os.listdir(root_path)]
for in_file, out_file in zip(in_file_list, out_file_list):
with open(in_file, 'r') as f_in, open(out_file, 'w') as f_out:
for line in f_in:
line_index+=1
if line_index%1000000==0:
print(f'processing line : ', line_index)
single_line = json.loads(line)
if single_line['label']==1:
f_out.write(json.dumps(single_line)+'\n')
count_down = n
elif count_down>0 and single_line['label'] == 0:
f_out.write(json.dumps(single_line)+'\n')
count_down -= 1
else:
continue
if __name__=='__main__':
extract(n, input_path_dir, out_path_dir)
\ No newline at end of file
from tqdm import tqdm
import sys
import json
import os
root_path = '/opt/share/dataset/enwiki_output/enwiki_neg_from_all_data/1_10_dq_pairs_mini/'
output_root_path = '/opt/share/dataset/enwiki_output/enwiki_neg_from_all_data/1_10_no_duplicate_dq_pairs_mini/'
file_list = [{root_path+item: output_root_path+item} for item in os.listdir(root_path)]
print(f'file list is {file_list}')
for file in tqdm(file_list):
for key, item in file.items():
pos_data = []
neg_data = []
with open(key, 'r') as f:
with open(item, 'w') as f_out:
for item in f:
single_data = json.loads(item)
if single_data['label'] == 1:
if single_data not in pos_data:
pos_data.append(single_data)
else:
neg_data.append(single_data)
print(f'length of positive is {len(pos_data)}')
print(f'length of negative is {len(neg_data)}')
total = pos_data+neg_data
for item in total:
f_out.write(json.dumps(item)+'\n')
\ No newline at end of file
import os
import json
import copy
import re
from tqdm import tqdm
import zipfile
import cProfile, pstats
from data_generator_including_upper import DataGenerator
class DataGeneratorGutenberg(DataGenerator):
def __init__(self, text, output):
text = re.sub('\n+', ' ', text)
text = re.sub('\r', '', text)
try:
text = re.split('START OF THIS PROJECT GUTENBERG EBOOK', text)[1]
text = re.split('END OF THIS PROJECT', text)[0]
except:
text = text
self.text = [text]
self.output_file_name = output
print('output_file_name is ',self.output_file_name)
def generate(self):
with open(self.output_file_name, 'a') as out:
file_total_sentences = self.get_file_all_sentences(self.text)
print('length of file_total_sentences is : ', len(file_total_sentences))
# random.shuffle(text_tuple)
copied_file_total_sentences = copy.deepcopy(file_total_sentences)
dq_from_one_text = self.process_single_text(self.text[0], copied_file_total_sentences)
for item in dq_from_one_text:
out.write(json.dumps(item) + '\n')
os_walk = os.walk('/opt/share/dataset/gutenberg/aleph.gutenberg.org/')
output_dir = '/opt/share/dataset/gutenberg/dq_output/'
fir = []
for item in os_walk:
if item[2]!=[]:
files = [item[0]+'/'+name for name in item[2]] # All file name
fir.extend(files)
print('Togal number of files: ',len(fir))
for index, file in tqdm(enumerate(fir)):
try:
zp = zipfile.ZipFile(file)
except:
print(file)
for text in zp.namelist():
print(file)
single_text = zp.read(text).decode("ISO-8859-1")
if len(single_text)<100:
continue
data_generator = DataGeneratorGutenberg(single_text, output_dir+str(index))
# cProfile.run('data_generator.generate()', 'stats')
# p = pstats.Stats('stats')
# p.sort_stats('cumulative').print_stats(30)
data_generator.generate()
import json
data = []
with open('./auto-train_origin08-17-14:18.jsonl','r') as f:
for item in f:
data.append(json.loads(item))
print(f'Data length is: {len(data)}')
print(f'Data instance is: {data[0]}')
\ No newline at end of file
from data_generator_2 import DataGenerator2
import os
import sys
import pathlib
from tqdm import tqdm
import time
if sys.argv:
input_file_index = [sys.argv[1], sys.argv[2]]
print('input file index is: ', input_file_index)
if len(sys.argv)>3:
pos_neg_ratio = int(sys.argv[3])
else:
pos_neg_ratio = 10
if len(sys.argv)>4:
copy_or_not = bool(sys.argv[4])
else:
copy_or_not = False
print('pos neg ratio is : {pos_neg_ratio}')
print('copy or not: {copy_or_not}')
file_list = []
for index, item in enumerate(os.walk('/opt/share/dataset/enwiki_small_raw')):
if index == 0:
continue
for i in range(len(item[2])):
file_list.append(pathlib.PurePath(item[0]).joinpath(item[2][i]))
print('total file list num is : ', len(file_list))
file_list = file_list[int(input_file_index[0]):int(input_file_index[1])]
print('file list is: ', file_list, 'length is: ', len(file_list))
for file_path in tqdm(file_list):
out_path = '/opt/share/dataset/enwiki_output/enwiki_neg_from_all_data/1_10_dq_pairs_all_1000wan_redo/1_10_dq_pairs_' + str(file_path)[-10:-8]+str(file_path)[-3:] +'.jsonl'
#output_file_1_1 = '/opt/share/dataset/enwiki_output/enwiki_neg_from_all_data/1_1_dq_pairs_all_1000wan/1_1_dq_pairs_' + str(file_path)[-10:-8]+str(file_path)[-3:] +'.jsonl'
#out_path = '/tmp/1.jsonl'
#output_file_1_1 = '/tmp/2.jsonl'
generator = DataGenerator2(file_path, out_path)
generator.generate(pos_neg_ratio, copy_or_not)
from data_generator_including_upper import DataGenerator
import numpy as np
from multiprocessing import Pool
import os
import sys
import pathlib
from tqdm import tqdm
import time
if sys.argv:
total_index = sys.argv[1]
print('total index is: ', total_index)
output_dir = sys.argv[2]
print('output directory is:', output_dir)
if len(sys.argv)>3:
pos_neg_ratio = int(sys.argv[3])
else:
pos_neg_ratio = 10
if len(sys.argv)>4:
copy_or_not = bool(sys.argv[4])
else:
copy_or_not = False
print('pos neg ratio is : {pos_neg_ratio}')
print('copy or not: {copy_or_not}')
file_list = []
for index, item in enumerate(os.walk('/opt/share/dataset/enwiki_raw')):
if index == 0:
continue
for i in range(len(item[2])):
file_list.append(pathlib.PurePath(item[0]).joinpath(item[2][i]))
print('total file list num is : ', len(file_list))
def main(index):
file_list_chunk = file_list[index*25:(index+1)*25]
print('file list is: ', file_list_chunk, 'length is: ', len(file_list_chunk))
for file_path in tqdm(file_list_chunk):
out_path = output_dir + '1_10_dq_pairs_' + str(file_path)[-10:-8]+str(file_path)[-3:] +'.jsonl'
#output_file_1_1 = '/opt/share/dataset/enwiki_output/enwiki_neg_from_all_data/1_1_dq_pairs_all_1000wan/1_1_dq_pairs_' + str(file_path)[-10:-8]+str(file_path)[-3:] +'.jsonl'
#out_path = '/tmp/1.jsonl'
#output_file_1_1 = '/tmp/2.jsonl'
generator = DataGenerator(file_path, out_path)
generator.generate()
p = Pool(processes=12)
index = np.arange(int(total_index))
p.map(main, index)
from distutils.core import setup
from Cython.Build import cythonize
setup(
name='data_generator_including_upper',
ext_modules=cythonize("data_generator_including_upper.pyx")
)
from nltk import pos_tag
def find_replace_word(former_sentence, key_word_index, total_exception_replace_word, upper_or_not):
i = 1
replace_word_pool = []
excepted = former_sentence[:key_word_index[0]] + former_sentence[key_word_index[-1] + 1:]
excepted.append('.')
if upper_or_not:
# 如果有大写的专有名词, 优先选择大写的专有名词(连续的)
excepted_excepted = []
replace_upper_word = ''
tag = False
if 'The' in former_sentence[0]:
start_index = 1
else:
start_index = 0
for index in range(start_index, len(excepted)):
if excepted[index].lower() != excepted[index]:
tag = True
replace_upper_word += excepted[index] + ' '
else:
if tag:
replace_word_pool.append(replace_upper_word)
replace_upper_word = ''
excepted_excepted.append(excepted[index])
tag = False
replace_word_pool.extend([item[0] for item in pos_tag(excepted_excepted) if 'NN' in item[1]])
else:
#  如果没有大写的专有名词
replace_word_pool = [item[0] for item in pos_tag(excepted) if 'NN' in item[1]]
while len(replace_word_pool) < 5:
replace_word_pool.append(total_exception_replace_word[i])
i += 1
return replace_word_pool
former_sentence ='Alexander and Montgomery were able to resist the pressure from Churchill , building the pressure \' s strength and adding a pursuit formation , X Corps , to the Army \' s XIII and XXX Corps'
key_word_index = [7,8]
exception_word = []
result = find_replace_word(former_sentence.split(), key_word_index, exception_word, True)
print(result)
\ No newline at end of file
from multiprocessing import Pool
from mermaid.embeddings import Embedding
from mermaid.factory import Factory
from mermaid.preprocessing.chunker import *
from mermaid import models
from mermaid import sessions
import os
import sys
data_dir = sys.argv[1]
chunker_id = sys.argv[2]
batch_size = 1024
gpu_num = sys.argv[4]
os.environ['CUDA_VISIBLE_DEVICES'] = gpu_num
print(f'Using gpu : {gpu_num}')
glove_100 = '/home/guanxing/glove_word_vec/glove.6B.100d.txt'
t2v = pp.Token2Vec(glove_100)
vocab = pp.Vocabulary()
vocab.extend(t2v.keys())
vocab.compile()
glove_embeddings = Embedding(vocab, dim=100)
glove_embeddings.load_t2v(t2v)
def Lower(text):
return text.lower()
class lower_tokenizer(pp.Tokenizer):
def __init__(self, max_len = None):
seg_char_cmds = [
pp.transformations.Lower(),
pp.transformations.Split(),
pp.transformations.LimitLength(max_len)
]
super().__init__(transformations=seg_char_cmds, max_len=max_len)
tokenizer = lower_tokenizer
prpr = pp.Preprocessor(targets={'q':40,'d':40}, seg=tokenizer, vocab=vocab)
training_data_list = [data_dir+item for item in os.listdir(data_dir)]
def make_copy(stream, rate):
duplicated_stream = pp.Stream()
for item in stream:
duplicated_stream.extend([item] * rate)
return duplicated_stream
def copy_pos_stream(train_data):
poss = pp.Stream([e for e in train_data if e.label.value == 1])
negs = pp.Stream([e for e in train_data if e.label.value == 0])
#duplicated_poss = make_copy(poss, 10)
return pp.cat(poss, negs)
step = math.ceil(len(training_data_list)/25)
def preprocess(index):
print('step is : ', step)
for chunk_index, training_data_file in enumerate(training_data_list[index*step:(index+1)*step]):
stream = pp.FileStream(training_data_file)
if sys.argv[3] == 'True':
print(f'Copy positive data to be 1:1')
stream = copy_pos_stream(stream)
stream.shuffle()
if len(stream) == 0:
stream = pp.Stream([pp.Entry(d='Null stream', q='Hello, world.', label=0)])
prpr.tokenize(stream)
prpr.vectorize(stream)
if 'd' in stream[0]:
X = [stream.d.vector, stream.q.vector]
elif 'a' in stream[0]:
X = [stream.a.vector, stream.q.vector]
Y = stream.label.vector
"""
# 翻转 Y
new_array = np.zeros(stream.label.vector.shape)
for index2, item in enumerate(stream.label.vector):
if item == [0]:
new_array[index2] = np.array([1])
else:
new_array[index2] = np.array([0])
"""
total_chunk_index = index*step+chunk_index
print(total_chunk_index)
output_path = chunk_path + '/' + str(total_chunk_index)
with open(output_path,'wb') as f:
dill.dump((X, Y), f)
print('Chunk saved at ', output_path)
print(f'chunks preprocessing finished!')
chunk_path = '/opt/share/mermaid-data/tmp/' + chunker_id
if not os.path.exists(chunk_path):
os.mkdir(chunk_path)
p = Pool(processes=12)
index = np.arange(25)
p.map(preprocess, index)
# 开始训练!
chunk_group_file = pp.chunker.ChunksGroupManager(chunker_id)
chunks = pp.chunker.CachedChunks(chunk_group_file, len(training_data_list))
dev_stream = pp.FileStream('/opt/share/dataset/10000_dev_dq_pairs_v2')
class ChunksDataPack(pp.TrainingDataPack):
def __init__(self):
super().__init__(pp.DQPacker())
def load(self):
self._train = chunks
data_loader = pp.DataLoader(prpr)
data_loader.setup(dev_stream)
self._dev = data_loader.get()
self._test = self._dev
pack = ChunksDataPack()
model = Factory.Model(models.ConvKNRM, glove_embeddings, a_max_len=40, b_max_len=40)
sess2 = sessions.TrainingSession()
sess2.setup.data_pack(pack)
sess2.setup.model(model)
sess2.compile()
for i in range(50):
print(f'this is {i}th epoch.')
sess2.fit(batch_size=batch_size, epochs=1)
sess2.model.name = 'epoch' + str(i) + chunker_id + 'model'
sess2.model.embedding.name = 'epoch' + str(i) + chunker_id + 'embedding'
sess2.model.save(overwrite=True)
import argparse
parser = argparse.ArgumentParser(prog='xing',description='this is a test parser', epilog='no')
parser.add_argument('--version', action='version', version='%(prog)s 2.0')
parser.add_argument('integers', metavar='N',type=int, nargs='+', help='an integer for the accumulator')
#parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')
parser.add_argument('--sum', dest='accumulate', action='store', nargs='?', const=max, default=max)
parser.add_argument('bar', nargs='?',help='bar')
args = parser.parse_args()
print(args.accumulate(args.integers))
import datetime
import time
import redis
redis_db = 'dev01.centaurstech.com:38293:4165e05741185f79633cf486c4b0bd05bc9f6fd9eb46b940bdb0ee58a5992efb'
qa_key_hash = 'qa-train-hash'
qa_key_new = 'qa-train-new'
def get_redis(db = ''):
params = db.split(':')
print(f'params is :{params}')
return redis.StrictRedis(host=params[0], port=params[1], password=params[2], db=1)
def doit():
r = get_redis(redis_db)
ip_list = r.smembers(qa_key_hash)
for ip in ip_list:
r.srem(qa_key_hash, ip)
print(f'removed {ip} from server ip hash list')
r.delete(qa_key_new)
print(f'removed redis training data')
time.sleep(60)
def main():
print(f'Waiting for the time 3:00...')
while True:
while True:
now = datetime.datetime.now()
if now.hour==3 and now.minute==0:
break
time.sleep(30)
doit()
main()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment