Topic on Manual talk:Pywikibot

Replace script and fix option

13
Summary by Speravir

The cause for the error messages was on user side: I mistakenly added a comma at a place where it does not belong.

Speravir (talkcontribs)

@Xqt, I do not know whether this is a bug or an issue on my side, therefore here and not in Phabricator:

I’ve added this to user-fixes.py:

fixes['ampCode'] = {
    'generator': [
        r'-ns:0',
        r'-search:insource:"%26" insource:/%26/',
    ],
    'regex': False,
    'msg': {
        '_default': 'Bot-Änderung: überflüss. Kodierung für [[Und-Zeichen]] ersetzt, vgl. [[Spezial:Diff/233908956|Anfrage]]',
    },
    'replacements': [
        (r' %26 ', ' & '),
    ]
}

and then started Pywikibot with this (Windows) command line (user is pre-configured):

pwb replace -simulate -lang:de -fix:ampCode -log:fix-ampCode.log

This resulted in this error message:

2023-05-24 00:40:34            http.py,  123 in              flush: VERBOSE  Traceback (most recent call last):
  File "C:\Programs\Netz\pywikibot\pwb.py", line 39, in <module>
    sys.exit(main())
             ^^^^^^
  File "C:\Programs\Netz\pywikibot\pwb.py", line 35, in main
    runpy.run_path(str(path), run_name='__main__')
  File "<frozen runpy>", line 291, in run_path
  File "<frozen runpy>", line 98, in _run_module_code
  File "<frozen runpy>", line 88, in _run_code
  File "C:\Programs\Netz\pywikibot\pywikibot\scripts\wrapper.py", line 514, in <module>
    main()
  File "C:\Programs\Netz\pywikibot\pywikibot\scripts\wrapper.py", line 498, in main
    if not execute():
           ^^^^^^^^^
  File "C:\Programs\Netz\pywikibot\pywikibot\scripts\wrapper.py", line 485, in execute
    run_python_file(filename, script_args, module)
  File "C:\Programs\Netz\pywikibot\pywikibot\scripts\wrapper.py", line 147, in run_python_file
    exec(compile(source, filename, 'exec', dont_inherit=True),
  File "C:\Programs\Netz\pywikibot\scripts\replace.py", line 1113, in <module>
    main()
  File "C:\Programs\Netz\pywikibot\scripts\replace.py", line 1008, in main
    if not fix['replacements']:
           ~~~^^^^^^^^^^^^^^^^
TypeError: tuple indices must be integers or slices, not str
2023-05-24 00:40:34            http.py,  132 in              flush: CRITICAL Exiting due to uncaught exception TypeError: tuple indices must be integers or slices, not str

Used Pywikibot version is:

Release version: 8.1.2
setuptools version: 65.5.0
mwparserfromhell version: 0.6.3
wikitextparser version: 0.51.1
requests version: 2.28.1

With explicit command line options the task worked then, the call was:

pwb replace -simulate -lang:de -ns:0 -search:"insource:\"%26\" insource:/ %26 /" -summary:"Bot-Änderung: überflüss. Kodierung für [[Und-Zeichen]] ersetzt, vgl. [[Spezial:Diff/233908956|Anfrage]]" -log:fix-ampCode.log " %26 " " & "
Sakura emad (talkcontribs)

CHATGPT generated Answer:

Hi there! It seems that there is an issue with the replacements field in your code snippet. The error message indicates that "tuple indices must be integers or slices, not str." To fix this, please replace the parentheses with square brackets in the replacements field to define a list of tuples. Here's the corrected code snippet:

fixes['ampCode'] = {
    'generator': [
        r'-ns:0',
        r'-search:insource:"%26" insource:/%26/',
    ],
    'regex': False,
    'msg': {
        '_default': 'Bot-Änderung: überflüss. Kodierung für [[Und-Zeichen]] ersetzt, vgl. [[Spezial:Diff/233908956|Anfrage]]',
    },
    'replacements': [
        [r' %26 ', ' & '],
    ]
}

Speravir (talkcontribs)

No, that is not the reason:

  1. Inspite I wondered about this change (see next item), I tested it and the error message did not disappear.
  2. Though it could be outdated on Manual:Pywikibot/user-fixes.py, the syntax with parentheses is still visible there.
  3. Also, I actually had copied older entries and adjusted them to new task. Back in the past all had worked fine.
Sakura emad (talkcontribs)

: ) New Answer:

If correcting the replacements field did not resolve the issue, here are a few additional suggestions to investigate further:

Check for any recent changes or updates in the Pywikibot library or related dependencies that could be causing compatibility issues. It's possible that there might be a newer version or a specific configuration that is causing the error.

Double-check the command line arguments and options being used to start Pywikibot. Ensure that all necessary arguments are provided correctly, and there are no missing or incorrect options in the command.

Verify if you have the latest version of Pywikibot installed. While you mentioned version 8.1.2, it's worth checking if there are any newer releases available that might include bug fixes or improvements related to the issue you are facing.

I recommend reaching out to the Pywikibot community or forums for assistance. They have extensive experience with the library and might be able to provide specific guidance or insights based on similar issues they have encountered.

Xqt (talkcontribs)

Could you please add the following lines in front of line 1008 in replace.py:

from pprint import pprint
pprint(fix)

Seems that the replace.py script found an evaluated fixes entry different from that given above. The fix itself is read as tuple instead a dict somehow.  @xqt 04:24, 31 May 2023 (UTC)

Speravir (talkcontribs)

With how much indentation? I did it this way:

if isinstance(fix['msg'], str): # line 1007
    from pprint import pprint
    pprint(fix)
    set_summary = i18n.twtranslate(site, str(fix['msg']))

The error message remains.

I also have deleted the whole pywikibot (without my user scripts and config, but unintentionally the logs) and then re-extracted the zip file and then temporarily uninstalled mwparserfromhell, because I noticed the subdirectory in pywikibot. No success at all.

Side question: Can I without any risk add -simulate as generator option into user-fixes.py?

Xqt (talkcontribs)

> With how much indentation? I did it this way:

Seems you have updated the script in meantime. What you should do is the following: Replace the following code

       if not fix['replacements']:
           pywikibot.warning(f'No replacements defined for fix {fix_name!r}')
           continue

with

       from pprint import pprint
       print(type(fix))
       pprint(fix)
       if not fix['replacements']:
           pywikibot.warning(f'No replacements defined for fix {fix_name!r}')
           continue

The reason is that fix seems not to be a dict but a tuple. Maybe you have added a comma at the end of the ampCode fix in your fixes.py.  @xqt 11:57, 2 June 2023 (UTC)

Speravir (talkcontribs)

> “Maybe you have added a comma at the end of the ampCode fix in your fixes.py.“

Oh. My. God. This is sooo embarrassing! Auf Deutsch: Ich möchte im Boden versinken!

Yes, this was my simple, but that extensive mistake.

On one hand I am glad not having opened a Phabricator task, but on the other hand (again) so much stress and effort for such a tiny cause. Nethertheless thank you, Xqt, for having the right idea!

Just for the record and for comparison: With the addition of the print code this will be displayed in the terminal (but not the log) as first lines after the command input:

  • in case of defunct user-fix.py with spurious comma (obviously changed code for test case):
<class 'tuple'>                                                                                                      
({'generator': ['-ns:0', '-search:insource:"eszett"'],                                                               
  'msg': {'_default': 'Test Pywikibot, Replace-Skript'},                                                            
  'regex': False,                                                                                                    
  'replacements': [('eszett', 'ß')]},)
  • in correct working state without this comma:
<class 'dict'>                                                                                                       
{'generator': ['-ns:0', '-search:insource:"eszett"'],                                                                
 'msg': {'_default': 'Test Pywikibot, Replace-Skript'},                                                             
 'regex': False,                                                                                                     
 'replacements': [('eszett', 'ß')]}
Xqt (talkcontribs)

> the print code this will be displayed in the terminal (but not the log)

Yes this is intentional. print and pprint does not go throught the ui wrapper but directly to the terminal. I usually use them for debugging. Schönes Wochenende wünsch' ich.  @xqt 09:51, 3 June 2023 (UTC)

Xqt (talkcontribs)

> Side question: Can I without any risk add -simulate as generator option into user-fixes.py?

This does not work because generator options are only taken as pagegenerators options. It may contains generators and filters, see generator options and filter options. -simulate is a global option and must be given with the replace.py script or the pwb wrapper script.  @xqt 11:13, 2 June 2023 (UTC)
Speravir (talkcontribs)

Thanks, I will have a look.

Reply to "Replace script and fix option"