r/badcode • • Oct 19 '20

python The rest of the codebase is equally fucking depressing and buggy, part of an AI speech to text backend I contracted a team to build :(

Post image
1.0k Upvotes

125 comments sorted by

432

u/grrangry Oct 19 '20

The real wtf being a neon color theme and an editor with a transparent background.

157

u/Jeremy_Thursday Oct 19 '20

If only you knew the pain this code base has and is continuing to give me. The background wallpaper is a video and I also have a fuck load of CSS animations added to my editor. Still not even the most WTF, I promise

2

u/forthemostpart Oct 19 '20

What editor are you using?

4

u/Jeremy_Thursday Oct 19 '20

That’s atom. You have to compile it from source to get transparency and I’ve added like a few thousand lines of CSS

0

u/[deleted] Oct 19 '20

[deleted]

77

u/Jeremy_Thursday Oct 19 '20

Oooooo the backdrop-filter property. I’ve been looking for that forever. Good looks fam!

52

u/[deleted] Oct 19 '20 edited Oct 19 '20

Do you want win10's/winui's acrylic background? All you have to do is backdrop-filter: blur(20px) saturate(1.25); background-color: rgba(46, 46, 46, 0.6); background-image: url(paste_url_here);. For that url, you'll have to right click this image and "Open image in new tab" and copy the URL of that image in the new tab and replace paste_url_here with that url to work ;)

Edit: Found the direct image link

You can also use whatever color you want + whatever saturation (don't change the blur tho)

Edit 2: u/Jeremy_Thursday tagging just in case :)

25

u/Jeremy_Thursday Oct 19 '20

You absolute legend, that’s so fucking clutch! Thanks for sharing ❤️

14

u/[deleted] Oct 19 '20

Np and forgot to tell you, before you use that image, change its transparency/opacity to 2% (0.02) (use some online alpha/opacity changer or Photoshop or whatever you are comfortable with). Else you would have an opaque noise background

8

u/Jeremy_Thursday Oct 19 '20

Rodger that haha, I probably also want background stretch or background tile if that’s seamless noise. Is there no CSS property for background-image opacity?

Thanks again friend!

4

u/[deleted] Oct 19 '20

Uhh unfortunately no. I wish there was a background-opacity property tho

1

u/Jeremy_Thursday Oct 19 '20 edited Oct 19 '20

I know you can add opacity to an entire element with opacity:(floaty boi 0-1); but it probably wouldn’t work as well here where you’re layering multiple transparent things.

Hopefully we get a dedicated background-opacity: rule; that and Background transitions that swap in and out different gradients. There was something like that with backgrounds and transitions I wanted.

→ More replies (0)

5

u/Darkf1am3 Oct 19 '20

May I ask why you tagged it as spoilers?

10

u/[deleted] Oct 19 '20

Yea why did I hide them as spoilers. Idk lmao

7

u/tias Oct 19 '20

I'm editor? No you're editor.

4

u/[deleted] Oct 19 '20

Oh lol didn't notice that fuck autocorrect

1

u/Fingolfin734 Oct 19 '20

Whose editor

12

u/Leoniqorn Oct 19 '20

I think you would not like r/unixporn very much...

2

u/grrangry Oct 19 '20

haha likely not.

73

u/DrDelbertBlair Oct 19 '20

What would be a better solution to this? Just like a for loop that iterates the replace function through a list of the characters or is there something that works better than that?

161

u/Jeremy_Thursday Oct 19 '20

User input is really dirty here and anything that isn’t alphanumeric or an apostrophe is going to fuck shit up. So in this case we need to take a whitelist approach instead of a blacklist approach.

Regex is a tool which is great for purging text of characters you don’t want (aka characters not on your whitelist). It’s typically the tool used for stuff like this if you’re replacing more than like one type of character/text-pattern.

26

u/DrDelbertBlair Oct 19 '20

Oh that makes sense. Thanks for filling me in

22

u/Jeremy_Thursday Oct 19 '20

No prob mate.

28

u/blerp_2305 Oct 19 '20

In python using regex, re.sub would be better

10

u/Beach-Devil i++++; Oct 19 '20

Regex There’s a function that’s called re.replace_all

5

u/DreadCoder Oct 19 '20

A regex that converts anything that's not 'a-z, A-Z, 0-9' into ''

ONE line would have done it

4

u/xigoi Oct 19 '20
text = re.sub(r"[ ,!?etc]+", " ", text)

8

u/[deleted] Oct 19 '20 edited Oct 19 '20

Assuming this is python:

DisallowedCharacters = [{characters you wanna remove}]

for i in str:

    if i in DissalowedCaracters:

        str.replace(i, " ")

18

u/igoromg Oct 19 '20

Quadratic complexity right here. A linear solution exists which is also much more gc friendly:

translation_table = { chars you want to keep, also upper to lowercase }

res = []
for ch in string:
	res.append(translation_table.get(ch, ' '))

''.join(res)

1

u/omg_drd4_bbq Oct 19 '20

You should also look into str.maketrans and str.translate. It is probably faster (depends on use case) and more idiomatic.

1

u/0x564A00 Oct 19 '20

That's the actual bad code. I now have to insert 143840 different characters into a hash table just because I care about the remaining 19! ComLarsic's code was fine - much clearer even - apart from missing lower(). In languages other than Python (which is horrible inefficient), a array of characters of small (19 in this case) length can be more efficient even.

3

u/igoromg Oct 19 '20

Bruh, if you want to keep all but some chars just insert the (char, ' ') pair into the table and pass the char you want to keep as the default param to dict.get

0

u/[deleted] Oct 19 '20

[deleted]

4

u/igoromg Oct 19 '20

Now that I gave it a second thought I've misunderstood your comment. the complexity of my comment is linear if translation_table is a hash table with constant time access. The comment I replied to is quadratic since if every character in the string is in DisallowedCharacters, replace will be called for every character of the string and each invocation will traverse the entire string thus quadratic.

0

u/[deleted] Oct 19 '20

[deleted]

1

u/igoromg Oct 19 '20

Yes and then if that character is in the list it calls the replace() method which in itself is a linear traversal of the string so its actually n*(k+n)

0

u/sebamestre Oct 19 '20

Yes, but the replace method will only be called k times, because it (presumably) replaces every instance of i from the string.

Thus, it is O(N*k)

1

u/igoromg Oct 19 '20 edited Oct 19 '20

first of all changing a collection you're iterating over is the epitome of bad code and many languages will throw an error over this. second that's not how it'll work at all, since strings are immutable and replace actually creates and returns a new string. so in this regard the code in question will not function at all on top of being n*(n+k) worst case complexity.

Here's an example where n = 46, k = 2
https://www.online-python.com/yrhVDLsbAz

1

u/sebamestre Oct 20 '20

I didn't know it didn't modify the string in place. I don't use python.

Well, if it did modify in place, it would work and run in O(nk). Do you at least agree with that?

I mean, I can tell you understood what I meant. You're just being pedantic, all the while moving the goalposts.

→ More replies (0)

34

u/FinnishArmy Oct 19 '20

Better yet, they can’t decide if they want to use “ ” or ‘ ’

10

u/Jeremy_Thursday Oct 19 '20

Lmfao I didn’t even notice ❤️

22

u/[deleted] Oct 19 '20

What a terrible day to have eyes.

10

u/Jeremy_Thursday Oct 19 '20

💀 not every day a repository makes you want to an hero.

5

u/[deleted] Oct 19 '20

Well, do you want a text to speech browser reading you all of this instead? I would rather have eyes.

44

u/LSatyreD Oct 19 '20 edited Oct 19 '20

I see nothing wrong with this.

edit: Oh wait, I see the problem now. They forgot to put an if statement to check if the replacement character is present or not before each replace.

Here I wrote an improved / updated version for you that should be safer (note: I only wrote the first four replaces, the rest is left as an excercise for the reader):

#Method to clear text
def clear_text(text=str(None)):
    """
    Replaces bad characters in text with clear text.
    Takes text as input and returns clear text.
    Text should be a string.
    """
    if text is not None:
        return_text = text
        try:
            #Replace ,
            for split_text in text.split():
                try:
                    for split_character in split_text:
                        if split_character == ','
                            return_text = return_text.replace(',', ' ')
                        else:
                            pass
                except:
                    print("ERROR replacing string of ,")
                    pass
                finally:
                    return_text = return_text
                    pass
            
            #Replace !
            for split_text in text.split():
                try:
                    for split_character in split_text:
                        if split_character == '!'
                            return_text = return_text.replace('!', ' ')
                        else:
                            pass
                except:
                    print("ERROR replacing string of !")
                    pass
                finally:
                    return_text = return_text
                    pass

            #Replace ?
            for split_text in text.split():
                try:
                    for split_character in split_text:
                        if split_character == '?'
                            return_text = return_text.replace('?', ' ')
                        else:
                            pass
                except:
                    print("ERROR replacing string of ?")
                    pass
                finally:
                    return_text = return_text
                    pass

            #Replace :
            for split_text in text.split():
                try:
                    for split_character in split_text:
                        if split_character == ':'
                            return_text = return_text.replace(':', ' ')
                        else:
                            pass
                except:
                    print("ERROR replacing string of :")
                    pass
                finally:
                    return_text = return_text
                    pass

        except:
            print("ERROR unknown error in clear_text")
            pass
        finally:
            return return_text

42

u/Jeremy_Thursday Oct 19 '20 edited Oct 19 '20

KAPPA AF someone get this man the “bad coder” flair

14

u/LSatyreD Oct 19 '20

I edited in some good code for you, feel free to use it (:

15

u/Jeremy_Thursday Oct 19 '20

Haha it’s pretty gorgeous ❤️ I think I’ll just stick with this and add more characters to blacklist the entire unused Unicode space I don’t want.

20

u/mind_overflow Oct 19 '20

i hope you're sarcastic because if you are, then what you said is hilarious, and if you aren't, it's still hilarious.

8

u/LSatyreD Oct 19 '20

The world may never know. I added some revisions to OP's original code to my previous comment, in case anyone needs a better way to do it.

9

u/taptrappapalapa Oct 19 '20

Oh my god. I think that’s somehow even worse than OPs code, as you literally no regard for it exponentially increasing runtime as I think that’s a O(4n2 ) runtime right there bud. It would be way faster just to use regex

Edit: didn’t notice the .replace methods when calculating runtime, holy shit that’s a lot of array computations.

6

u/Jeremy_Thursday Oct 19 '20

O(42069n2 ) runtime here we come baby!

2

u/LSatyreD Oct 19 '20

And don't forget there's a double nested for loop before the actual check if the character is even present. Assuming it needs to replace any non A-z 0-9 character across the unicode space, with any reasonable length message, and who knows how many messages there are.... yeah.

I mean I'm sure I could "improve" it further. But ya have to work out all these improvements before the first release that way you can later remove them, one at a time, to make users happy about "performance improvents" and "reduced processing time".

6

u/taptrappapalapa Oct 19 '20

Just imagine the runtime of iterating over strings that much for each input.

5

u/tias Oct 19 '20

You... you spent actual time on this

44

u/EyeInDaSky_ Bad coder Oct 19 '20
return ''.join ([' ' if i in ',!?:;)(".\r\n&\u2028_*' else i for i in ' '.join ([i for i in text.split (' ') if i != ''])])

I am pretty sure this would work fine

10

u/Jeremy_Thursday Oct 19 '20

Thank you haha

0

u/EyeInDaSky_ Bad coder Oct 19 '20

If you need some help I think I could do some optimization, I like that and I think I could do a lot for free.

17

u/Jeremy_Thursday Oct 19 '20

I need a whitelist regex approach here instead of this blacklist BS. The regex pattern should get rid of anything that isn’t alphanumeric or an apostrophe [ ‘ ]. Thanks so much for offering to help, that’s really nice of you! ❤️

11

u/Darudekappastorm12 Oct 19 '20

4

u/Jeremy_Thursday Oct 19 '20

Thanks! I also need apostrophes. Probably will just muddle my way through regex.

0

u/[deleted] Oct 19 '20

[deleted]

6

u/AutoModerator Oct 19 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/DankTrain, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/HowYouSeeMe Oct 19 '20

That's a comma. Points for trying tho.

7

u/[deleted] Oct 19 '20

Regex is great, was just about to parse some html with it

5

u/Jeremy_Thursday Oct 19 '20

Ahhh parsing HTML, the running with scissors of regex!

3

u/notger Oct 19 '20

The rickrolling of programmer forums.

-2

u/notger Oct 19 '20
  1. Don't offer to fix work for free, that the people that effed it up were paid for.

  2. Your tag instills confidence. I like the contrast, because you actually seem to know what you are doing, unlike the guys from above.

68

u/8asdqw731 Oct 19 '20

not as readable as text above, just because something is split on several lines doesn't mean it's bad code

24

u/TheOnlyTrueEnte Oct 19 '20

It's also way slower in this case because it has to iterate over the text and create a new string of equal length about 20 times.

3

u/8asdqw731 Oct 19 '20

that could be an issue, if it's called often,

if it's not then I'd probably still go with the more readable variant

3

u/jimgagnon Oct 19 '20

Why not just use NTLK?

5

u/Taburn Oct 19 '20

Did you pay them for their buggy code?

21

u/Jeremy_Thursday Oct 19 '20 edited Oct 19 '20

Of course! We’re not assholes. We did also drop them when they “fixed bugs” but actually didn’t fix the bugs or bother testing to see their “fix” didn’t work.

Their bug fixes were truly retarded, didn’t work and then they wanted more money to do work they’d already been paid to do.

We got burned but not too bad. I have heard some real horror stories, don’t hire developers if you don’t know how to code and don’t hire teams that make you go through an intermediary person to talk with the developers. Just my 2 cents.

1

u/Taburn Oct 20 '20

That's very kind. I was thinking that if what they gave you didn't meet the performance specification then they shouldn't get any money for it.

2

u/Tm1lly Oct 19 '20

You need to contact a priest to cleanse this... only god can save this code base.

2

u/Jeremy_Thursday Oct 20 '20

Underrated comment.

2

u/honkinggr8namespaces Oct 19 '20

i hate how your editor font is in 2 different sizes at the same time

1

u/Jeremy_Thursday Oct 20 '20

Heh, you caught me! I kinda like it but yea it can occasionally be awkward to not have that perfect mono space

2

u/asaf92 Oct 20 '20

2028? What about 2027? Is that ok?

1

u/Jeremy_Thursday Oct 20 '20

No, they literally just coded checks for everything that was in an example. This will be replaced with a whitelist instead of a blacklist

77

u/[deleted] Oct 19 '20

I'm shocked they did text.lower() instead of just doing a text.replace("A", 'a')

49

u/AlbusSeverus14 Oct 19 '20 edited Oct 19 '20

So I can write "Contributed to AI speech to text backend open source project" on my resumé:

text = text.replace('A', 'a')
text = text.replace('B', 'b')
text = text.replace('C', 'c')
text = text.replace('D', 'd')
text = text.replace('E', 'e')
text = text.replace('F', 'f')
text = text.replace('G', 'g')
text = text.replace('H', 'h')
text = text.replace('I', 'i')
text = text.replace('J', 'j')
text = text.replace('K', 'k')
text = text.replace('L', 'l')
text = text.replace('M', 'm')
text = text.replace('N', 'n')
text = text.replace('O', 'o')
text = text.replace('P', 'p')
text = text.replace('Q', 'q')
text = text.replace('R', 'r')
text = text.replace('S', 's')
text = text.replace('T', 't')
text = text.replace('U', 'u')
text = text.replace('V', 'v')
text = text.replace('W', 'w')
text = text.replace('X', 'x')
text = text.replace('Y', 'y')
text = text.replace('Z', 'z')

26

u/[deleted] Oct 19 '20

I need you to implement multi-language by next week. I'm counting on you.

7

u/mfb- Oct 19 '20

text = re.sub('[^a-zA-Z0-9]','',text)

Fixed the issue with the strange outputs, boss.

Edit: Wait, this seems to be nearly what OP wants.

3

u/LonelyContext Oct 21 '20

Might want to throw an \s in there sothatitdoesntallruntogetherlikethis

3

u/mfb- Oct 21 '20

butthisissavingstoragespace

18

u/[deleted] Oct 19 '20

You paid for this? Damn

15

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Oct 19 '20

Image Transcription: Code


def clear_text(text):
    text = text.replace(',', ' ')
    text = text.replace('!', ' ')
    text = text.replace('?', ' ')
    text = text.replace(':', ' ')
    text = text.replace(';', ' ')
    text = text.replace(')', ' ')
    text = text.replace('(', ' ')
    text = text.replace('"', ' ')
    text = text.replace('.', ' ')
    text = text.replace('\r', ' ')
    text = text.replace('\n', ' ')
    text = text.replace("&", ' ')
    text = text.replace("\u2028", ' ')
    text = text.replace("”", ' ')
    text = text.replace("“", ' ')
    text = text.replace("-", " ")
    text = text.replace("*", " ")
    text = text.replace("  ", ' ')
    text = text.replace("  ", ' ')
    text - text.lower()
    return text

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

4

u/lachyBalboa Oct 19 '20

I like the mixed use of double- and single-quotes. Along with all the other bullshit, that isn't even consistent

1

u/[deleted] Oct 31 '20

KmozS

3

u/antonivs Oct 20 '20

Pull requests and code review catches this kind of thing early. You control the repo, they use it. For bonus points set up a static code analysis tool that runs whenever code is pushed to the repo.

2

u/mbround18 Oct 19 '20

Some peeps really struggle with regex :P

2

u/kranelegs Oct 19 '20

I mean I hate regex cuz it’s semantically stupid but...

1

u/gent861 Oct 19 '20

Who uses regex anyway

1

u/infomapaz Oct 19 '20

I feel so uncomfortable watching this

1

u/wojwesoly Oct 19 '20

What editor are you using?

1

u/lqstuart Oct 19 '20

looks like AI to me

1

u/Poddster Oct 19 '20

Contractors are notorious bad-coders. The reason is obvious: they never have to deal with their crap code.

1

u/[deleted] Oct 19 '20

I wonder, is there a python standard library function that takes a str and a dictionary and replaces all instances of keys with values in the str?

-10

u/doggyStile Oct 19 '20

Still better than using regex!!

10

u/Jeremy_Thursday Oct 19 '20

Honestly I absolutely hate regex and I'd take something like this for readability in different circumstances. The problem is user input is super dirty here and we really need a whitelist approach as opposed to a blacklist approach.

2

u/Look_Ma_Im_On_Reddit Oct 19 '20

regex aka voodoo magic aka don't touch this it works

1

u/Jeremy_Thursday Oct 19 '20

Sometimes a little dark magic is required lol.

2

u/RFC793 Oct 19 '20

Yes. This.

0

u/[deleted] Oct 19 '20

[deleted]

6

u/Jeremy_Thursday Oct 19 '20

Lmfao I love this comment! Made me laugh super hard. Any chance you could give me the pattern to purge anything that’s not alphanumeric or an apostrophe. I don’t need to replace them with a space or anything, just yeet them into the void.

2

u/the-nick-of-time Oct 19 '20

In python, re.sub(r"[^a-zA-Z0-9']", "", text) will work assuming you need only ASCII characters; it means "replace every character that is not a-z or 0-9 with nothing". You could instead do re.sub(r"[^\w']", "", text) where \w is a character class that encompasses basically any word-like character in unicode, which encompasses letters, numbers, and the underscore.

1

u/[deleted] Oct 19 '20

[removed] — view removed comment

1

u/Jeremy_Thursday Oct 19 '20

Yea it’s an ass backwards blacklist when a whitelist is what’s called for.

2

u/RFC793 Oct 19 '20

translate would be better IMHO. But, really, this should be whitelisting instead of blacklisting.

7

u/Jeremy_Thursday Oct 19 '20 edited Oct 19 '20

Yea whitelisting 100% needed here. was my first instinct as well.

3

u/ywBBxNqW Oct 19 '20

translate would be better IMHO.

Why?

1

u/RFC793 Oct 20 '20

Readability wise, it expresses “replace all this stuff with space” more clearly. No need to switch gears and mind-parse a regex. No need to think about what needs to be escaped etc. just: here’s a list of characters.

Computationally, it’s all you need. Better than creating N intermediate strings with a chain of replace. But not overkill like a regex, which despite their name, are not regular.

1

u/Exnixon Oct 19 '20

You probably don't need the double space anyway. The original code looks like they're making a buggy attempt to collapse all whitespace down to a single space. You'd want to do

s/ */ /g

after you do all the single character substitutions.

2

u/[deleted] Oct 19 '20

Or rather, s/ \+/ /g. The asterisk applies even to zero spaces, and ends up inserting a space between every character.

1

u/Exnixon Oct 19 '20

I'm gonna pretend I had two spaces there and Reddit removed one, la dee dah.

0

u/[deleted] Oct 20 '20

[deleted]

1

u/[deleted] Oct 29 '20

Yes that would work but makes for a unorganized line imo.

I would use an array/list of banned chars and just use

for i in banned_chars:
    string.replace(i, ' ')

The second line is indented but was made on mobile and doesn't work apparently