internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: pymedusa/Medusa

Issue:
Search system of Yggtorrent has changed
Hi, like i said, the search system has changed, and medusa can't search in Yggtorrent anymore.

```
2017-11-28 18:45:00 ERROR    SEARCHQUEUE-FORCED-257655 :: [Yggtorrent] :: [b96b3ee] Failed parsing provider.
Traceback (most recent call last):
  File "/volume1/@appstore/sickbeard-custom/var/SickBeard/medusa/providers/torrent/html/yggtorrent.py", line 141, in parse
    pubdate = self.parse_pubdate(pubdate_raw, human_time=True)
  File "/volume1/@appstore/sickbeard-custom/var/SickBeard/medusa/providers/generic_provider.py", line 557, in parse_pubdate
    return datetime.now(tz.tzlocal()) - timedelta(seconds=seconds)
TypeError: unsupported type for timedelta seconds component: NoneType
```
regards


Discussion:

Resolving patch:
diff --git a/medusa/providers/generic_provider.py b/medusa/providers/generic_provider.py
--- a/medusa/providers/generic_provider.py
+++ b/medusa/providers/generic_provider.py
@@ -564,7 +564,7 @@ def parse_pubdate(pubdate, human_time=False, timezone=None, **kwargs):
                 dt = dt.astimezone(tz.gettz(timezone))
             return dt
 
-        except (AttributeError, ValueError):
+        except (AttributeError, TypeError, ValueError):
             log.exception('Failed parsing publishing date: {0}', pubdate)
 
     def _get_result(self, episodes=None):
diff --git a/medusa/providers/torrent/html/yggtorrent.py b/medusa/providers/torrent/html/yggtorrent.py
--- a/medusa/providers/torrent/html/yggtorrent.py
+++ b/medusa/providers/torrent/html/yggtorrent.py
@@ -45,6 +45,7 @@ def __init__(self):
 
         # Miscellaneous Options
         self.translation = {
+            'heure': 'hour',
             'heures': 'hours',
             'jour': 'day',
             'jours': 'days',
@@ -137,8 +138,13 @@ def parse(self, data, mode):
                     pubdate = None
                     pubdate_match = re.match(r'(\d+)\s(\w+)', cells[2].get_text(strip=True))
                     if pubdate_match:
-                        pubdate_raw = '{0} {1}'.format(pubdate_match.group(1), self.translation.get(pubdate_match.group(2)))
-                        pubdate = self.parse_pubdate(pubdate_raw, human_time=True)
+                        translated = self.translation.get(pubdate_match.group(2))
+                        if not translated:
+                            log.exception('No translation mapping available for value: {0}', pubdate_match.group(2))
+                            continue
+                        else:
+                            pubdate_raw = '{0} {1}'.format(pubdate_match.group(1), translated)
+                            pubdate = self.parse_pubdate(pubdate_raw, human_time=True)
                     else:
                         log.warning('Could not translate publishing date with value: {0}', cells[2].get_text(strip=True))
 


Test patch:
Repository: pymedusa/Medusa

Issue:
H264-20-40 is wrongly parsed as episodes 20-40
### Before submitting your issue:

Enable debug logging in Medusa settings, reproduce the error (be sure to disable after the bug is fixed)

**Branch/Commit:** develop
**OS:** windows/linux
**What you did:** Parsing the title `The.Good.Wife.Season.6.480p.HDTV.H264-20-40.WEB-DL`, results in the parsing the 20-40 describes the episodes, but it actually describes the h264 encoding settings.
**What happened:**
**What you expected:**
**Logs:**
```
D:\Development\Medusa2 - Copy\tests>python report_guessit.py The.Good.Wife.Season.6.480p.HDTV.H264-20-40.WEB-DL
# guessit: 2.1.4  rebulk: 0.9.0
? The.Good.Wife.Season.6.480p.HDTV.H264-20-40.WEB-DL
: title: The Good Wife
  season: 6
  screen_size: 480p
  video_codec: h264
  episode: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
  format: WEB-DL
  type: episode
  parsing_time: 0.0469999313354
```

One more example, `Arrow.Season.2.480p.HDTV.H264-20-40`.

Reported upstream: https://github.com/guessit-io/guessit/issues/507



Discussion:
Never saw this before. @duramato did you?
I've noticed as I was making improvements to the season pack searching. As I was getting a really limited amount of season packs found. I was looking at geek.
I suggest open an issue in guessit
Thought first check it's not because of our refiners. 
Its guessit issue:

```
guessit "The.Good.Wife.Season.6.480p.HDTV.H264-20-40.WEB-D                                                                             L"
For: The.Good.Wife.Season.6.480p.HDTV.H264-20-40.WEB-DL
GuessIt found: {
    "title": "The Good Wife",
    "season": 6,
    "screen_size": "480p",
    "format": [
        "HDTV",
        "WEB-DL"
    ],
    "video_codec": "h264",
    "episode": [
        20,
        21,
        22,
        23,
        24,
        25,
        26,
        27,
        28,
        29,
        30,
        31,
        32,
        33,
        34,
        35,
        36,
        37,
        38,
        39,
        40
    ],
    "type": "episode"
}
```

Resolving patch:
diff --git a/medusa/name_parser/guessit_parser.py b/medusa/name_parser/guessit_parser.py
--- a/medusa/name_parser/guessit_parser.py
+++ b/medusa/name_parser/guessit_parser.py
@@ -21,6 +21,9 @@
 
     # episode titles in the wrong place
     'DHD',
+
+    # The.Good.Wife.Season.6.480p.HDTV.H264-20-40.WEB-DL
+    '20-40',
 ]
 
 allowed_languages = {


Test patch:
Repository: pymedusa/Medusa

Issue:
[APP SUBMITTED]: No translation mapping available for value: minutes

        ### INFO
        **Python Version**: `2.7.9 (default, Jun 29 2016, 13:08:31) [GCC 4.9.2]
        **Operating System**: `Linux-3.16.0-4-amd64-x86_64-with-debian-8.9`
        **Locale**: `UTF-8`
        **Branch**: [master](../tree/master)
        **Database**: `44.8`
        **Commit**: pymedusa/Medusa@1a8dc66c7ec9231be0d3444710e476437c9ae1c8
        **Link to Log**: https://gist.github.com/ba8bb91c8f92d3cd18d74ce092a0b5f6
        ### ERROR
        <pre>
2017-12-07 07:55:51 ERROR    SEARCHQUEUE-FORCED-321285 :: [Yggtorrent] :: [1a8dc66] No translation mapping available for value: minutes
</pre>
        ---
        _STAFF NOTIFIED_: @pymedusa/support @pymedusa/moderators
        


Discussion:

Resolving patch:
diff --git a/medusa/providers/torrent/html/yggtorrent.py b/medusa/providers/torrent/html/yggtorrent.py
--- a/medusa/providers/torrent/html/yggtorrent.py
+++ b/medusa/providers/torrent/html/yggtorrent.py
@@ -45,12 +45,18 @@ def __init__(self):
 
         # Miscellaneous Options
         self.translation = {
+            'seconde': 'second',
+            'secondes': 'seconds',
+            'minute': 'minute',
+            'minutes': 'minutes',
             'heure': 'hour',
             'heures': 'hours',
             'jour': 'day',
             'jours': 'days',
             'mois': 'month',
             'an': 'year',
+            'année': 'year',
+            'ans': 'years',
             'années': 'years'
         }
 
@@ -141,7 +147,6 @@ def parse(self, data, mode):
                         translated = self.translation.get(pubdate_match.group(2))
                         if not translated:
                             log.exception('No translation mapping available for value: {0}', pubdate_match.group(2))
-                            continue
                         else:
                             pubdate_raw = '{0} {1}'.format(pubdate_match.group(1), translated)
                             pubdate = self.parse_pubdate(pubdate_raw, human_time=True)


Test patch:
Repository: pymedusa/Medusa

Issue:
Can we have the poster by higher site rating  from tvdb please??
Commit: 1a8dc66c7ec9231be0d3444710e476437c9ae1c8
Version: OS: Linux-4.13.13-1-pve-x86_64-with-debian-9.3
Branch: master
Commit: 1a8dc66c7ec9231be0d3444710e476437c9ae1c8
Version: v0.1.20
Database: 44.8
Python Version: | 2.7.13 (default, Nov 24 2017, 17:33:09)  [GCC 6.3.0 20170516]
SSL Version: | OpenSSL 1.1.0f  25 May 2017
OS: | Linux-4.13.13-1-pve-x86_64-with-debian-9.3

Can we have the poster by higher site rating from tvdb please ??
With TVDBv2 for blindspot i have this poster https://www.thetvdb.com/banners/posters/295647-15.jpg.
On master or develop and lots of series in english.
![34072869-459d5f4e-e28f-11e7-9916-498a8d7afb8a](https://user-images.githubusercontent.com/26071810/34077626-8beec66c-e308-11e7-9219-b686f9fb2724.png)



Discussion:

Resolving patch:
diff --git a/medusa/indexers/indexer_base.py b/medusa/indexers/indexer_base.py
--- a/medusa/indexers/indexer_base.py
+++ b/medusa/indexers/indexer_base.py
@@ -210,8 +210,11 @@ def _save_images(self, sid, images):
                 # For each image type, where going to save one image based on the highest rating
                 if not len(images[image_type]):
                     continue
-                merged_image_list = [y[1] for y in [next(iteritems(v)) for _, v in iteritems(images[image_type])]]
-                highest_rated = sorted(merged_image_list, key=lambda k: float(k['rating']), reverse=True)[0]
+                # This will flatten all the images for all of the resolutions. Meaning it could pick a higher
+                # rated image that has a lower resolution.
+                merged_image_list = {image_id: image for image_id, image_value in iteritems(images[image_type])
+                                     for image_id, image in iteritems(image_value)}
+                highest_rated = sorted(merged_image_list.values(), key=lambda k: k['rating'], reverse=True)[0]
                 self._set_show_data(sid, image_type, highest_rated['_bannerpath'])
 
     def __getitem__(self, key):


Test patch:
Repository: pymedusa/Medusa

Issue:
Search Providers - Only download Freeleech - TRUE
OS: DSM 6 (NAS Synology)
Where: Settings->Search Providers->Provider Options
What happened: On any search provider, option "Only download Freeleech torrents" is set to TRUE, after MEDUSA restart, the value is FALSE.

Setup: Migration from Sickrage

Logs & screens:

<img width="776" alt="skaermbillede 2017-12-26 kl 22 41 31" src="https://user-images.githubusercontent.com/25592744/34365205-fd0dae12-ea8d-11e7-8568-2421bdfbb869.png">

When setting is set to TRUE, I get this in debug log. 
<img width="861" alt="skaermbillede 2017-12-26 kl 22 42 47" src="https://user-images.githubusercontent.com/25592744/34365216-254eda36-ea8e-11e7-89d4-b49f51b4a9d2.png">

<img width="742" alt="skaermbillede 2017-12-26 kl 22 48 27" src="https://user-images.githubusercontent.com/25592744/34365290-f91a87f2-ea8e-11e7-9397-796a51ae01f3.png">



Discussion:

Resolving patch:
diff --git a/medusa/__main__.py b/medusa/__main__.py
--- a/medusa/__main__.py
+++ b/medusa/__main__.py
@@ -1535,7 +1535,7 @@ def save_config():
                 ],
                 GenericProvider.TORRENT: [
                     'custom_url', 'digest', 'hash', 'passkey', 'pin', 'confirmed', 'ranked', 'engrelease', 'onlyspasearch',
-                    'sorting', 'ratio', 'minseed', 'minleech', 'options', 'freelech', 'cat', 'subtitle', 'cookies',
+                    'sorting', 'ratio', 'minseed', 'minleech', 'options', 'freeleech', 'cat', 'subtitle', 'cookies',
                 ],
                 GenericProvider.NZB: [
                     'cat_ids'


Test patch:
Repository: pymedusa/Medusa

Issue:
[APP SUBMITTED]: TypeError: argument 2 to map() must support iteration

### INFO
**Python Version**: `2.7.9 (default, Sep 17 2016, 20:26:04) [GCC 4.9.2]`
**Operating System**: `Linux-4.9.35-v7+-armv7l-with-debian-8.0`
**Locale**: `UTF-8`
**Branch**: [develop](../tree/develop)
**Database**: `44.9`
**Commit**: pymedusa/Medusa@c0f2ffe417e8075a26518969d9a563312c89115e
**Link to Log**: https://gist.github.com/4bb40e4873197ef94e574fff9082495b
### ERROR
<pre>
2018-01-24 14:35:16 ERROR    Thread-16 :: [c0f2ffe] Exception generated: argument 2 to map() must support iteration
Traceback (most recent call last):
  File "/home/pi/Medusa/<a href="../blob/c0f2ffe417e8075a26518969d9a563312c89115e/medusa/server/web/core/base.py#L280">medusa/server/web/core/base.py</a>", line 280, in async_call
    result = function(**kwargs)
  File "/home/pi/Medusa/<a href="../blob/c0f2ffe417e8075a26518969d9a563312c89115e/medusa/server/web/home/handler.py#L1051">medusa/server/web/home/handler.py</a>", line 1051, in pickManualSearch
    ep_objs.extend(series_obj.get_all_episodes(int(cached_result[b'season'])))
  File "/home/pi/Medusa/<a href="../blob/c0f2ffe417e8075a26518969d9a563312c89115e/medusa/tv/series.py#L613">medusa/tv/series.py</a>", line 613, in get_all_episodes
    sql_args.append(','.join(map(text_type, season)))
TypeError: argument 2 to map() must support iteration
</pre>
---
_STAFF NOTIFIED_: @pymedusa/support @pymedusa/moderators



Discussion:
Happen when trying to snatch: `Spies.Of.Warsaw.S01.720p.BluRay.X264-FLHD ` from omgwtfnzbs.
Actually, happens for _**all**_ manual snatch attempts.

Resolving patch:
diff --git a/medusa/server/web/home/handler.py b/medusa/server/web/home/handler.py
--- a/medusa/server/web/home/handler.py
+++ b/medusa/server/web/home/handler.py
@@ -1048,7 +1048,7 @@ def pickManualSearch(self, provider=None, rowid=None, manual_search_type='episod
             for episode in cached_result[b'episodes'].strip('|').split('|'):
                 ep_objs.append(series_obj.get_episode(int(cached_result[b'season']), int(episode)))
         elif manual_search_type == 'season':
-            ep_objs.extend(series_obj.get_all_episodes(int(cached_result[b'season'])))
+            ep_objs.extend(series_obj.get_all_episodes([int(cached_result[b'season'])]))
 
         # Create the queue item
         snatch_queue_item = ManualSnatchQueueItem(series_obj, ep_objs, provider, cached_result)
diff --git a/medusa/tv/series.py b/medusa/tv/series.py
--- a/medusa/tv/series.py
+++ b/medusa/tv/series.py
@@ -585,7 +585,7 @@ def get_all_episodes(self, season=None, has_location=False):
         """Retrieve all episodes for this show given the specified filter.
 
         :param season:
-        :type season: int
+        :type season: list
         :param has_location:
         :type has_location: bool
         :return:


Test patch:
Repository: pymedusa/Medusa

Issue:
TD: IndexError: list index out of range
2018-01-25 20:40:04 ERROR    FINDPROPERS :: [TorrentDay] :: [ad04c6b] Failed parsing provider.
Traceback (most recent call last):
  File "/home/osmc/Medusa/medusa/providers/torrent/html/torrentday.py", line 158, in parse
    name = cells[labels.index('name')]
IndexError: list index out of range
2018-01-25 20:40:03 INFO     FINDPROPERS :: [TorrentDay] :: [ad04c6b] Searching for any new PROPER releases from TorrentDay

@p0psicles @OmgImAlexis 


Discussion:

### INFO
**Python Version**: `2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)]`
**Operating System**: `Windows-10-10.0.16299`
**Locale**: `cp1252`
**Branch**: [develop](../tree/develop)
**Database**: `44.9`
**Commit**: pymedusa/Medusa@0fe5730f8b9a6b9209720549c7853648dd4a486b
**Link to Log**: https://gist.github.com/4c68ad4ebd8e5173d6d5b16f89eb1cba
### ERROR
<pre>
2018-01-26 00:24:43 ERROR    SEARCHQUEUE-DAILY-SEARCH :: [TorrentDay] :: [0fe5730] Failed parsing provider.
Traceback (most recent call last):
  File "C:\Medusa\Medusa\medusa\providers\torrent\html\torrentday.py", line 182, in parse
    pubdate_raw = name.find('div').get_text(strip=True).split('|')[1].strip()
IndexError: list index out of range
</pre>
---
_STAFF NOTIFIED_: @pymedusa/support @pymedusa/moderators

Tnx for the report. Will fix today

Resolving patch:
diff --git a/medusa/providers/torrent/html/torrentday.py b/medusa/providers/torrent/html/torrentday.py
--- a/medusa/providers/torrent/html/torrentday.py
+++ b/medusa/providers/torrent/html/torrentday.py
@@ -142,7 +142,7 @@ def parse(self, data, mode):
             torrent_rows = torrent_table('tr') if torrent_table else []
 
             # Continue only if at least one release is found
-            if len(torrent_rows) < 2:
+            if len(torrent_rows) < 3 and 'no torrents found' in torrent_rows[-1].find('td').get_text().lower():
                 log.debug('Data returned from provider does not contain any torrents')
                 return items
 
@@ -179,7 +179,7 @@ def parse(self, data, mode):
                     torrent_size = cells[labels.index('size')].get_text()
                     size = convert_size(torrent_size) or -1
 
-                    pubdate_raw = name.find('div').get_text(strip=True).split('|')[1].strip()
+                    pubdate_raw = name.find('div').get_text(strip=True).split('|')[-1].strip()
                     pubdate = self.parse_pubdate(pubdate_raw, human_time=True)
 
                     item = {


Test patch:
Repository: pymedusa/Medusa

Issue:
AttributeError: 'int' object has no attribute 'indexer_name'
```
curl 'http://localhost:8081/api/v2/series' -H 'Pragma: no-cache' -H 'Origin: http://localhost:4000' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-AU,en;q=0.9,en-GB;q=0.8' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' -H 'content-type: application/json' -H 'accept: application/json' -H 'Cache-Control: no-cache' -H 'authorization: Bearer JWT_TOKEN_WAS_HERE' -H 'Connection: keep-alive' -H 'Referer: http://localhost:4000/' -H 'DNT: 1' --compressed
```

```
Traceback (most recent call last):
  File "/Users/xo/code/Medusa/ext/tornado/web.py", line 1510, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "/Users/xo/code/Medusa/medusa/server/api/v2/series.py", line 43, in get
    data = [s.to_json(detailed=detailed) for s in Series.find_series(predicate=filter_series)]
  File "/Users/xo/code/Medusa/medusa/tv/series.py", line 2020, in to_json
    data['cache']['poster'] = self.poster
  File "/Users/xo/code/Medusa/medusa/tv/series.py", line 527, in poster
    return image_cache.get_artwork(img_type, self.series_id)
  File "/Users/xo/code/Medusa/medusa/image_cache.py", line 111, in get_artwork
    location = get_path(img_type, series_obj)
  File "/Users/xo/code/Medusa/medusa/image_cache.py", line 94, in get_path
    location = _cache_dir(series_obj)
  File "/Users/xo/code/Medusa/medusa/image_cache.py", line 71, in _cache_dir
    return os.path.abspath(os.path.join(app.CACHE_DIR, 'images', series_obj.indexer_name))
AttributeError: 'int' object has no attribute 'indexer_name'
```


Discussion:

Resolving patch:
diff --git a/medusa/tv/series.py b/medusa/tv/series.py
--- a/medusa/tv/series.py
+++ b/medusa/tv/series.py
@@ -524,13 +524,13 @@ def airs(self, value):
     def poster(self):
         """Return poster path."""
         img_type = image_cache.POSTER
-        return image_cache.get_artwork(img_type, self.series_id)
+        return image_cache.get_artwork(img_type, self)
 
     @property
     def banner(self):
         """Return banner path."""
         img_type = image_cache.POSTER
-        return image_cache.get_artwork(img_type, self.series_id)
+        return image_cache.get_artwork(img_type, self)
 
     @property
     def aliases(self):


Test patch:
Repository: pymedusa/Medusa

Issue:
[APP SUBMITTED]: TypeError: find_by_id() takes exactly 3 arguments (2 given)

### INFO
**Python Version**: `2.7.12 (default, Dec  4 2017, 14:50:18) [GCC 5.4.0 20160609]`
**Operating System**: `Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial`
**Locale**: `UTF-8`
**Branch**: [master](../tree/master)
**Database**: `44.9`
**Commit**: pymedusa/Medusa@ccbc0ce9a2d3977a71bde03e29be503464ebe3cd
**Link to Log**: https://gist.github.com/805878e9b4f346dab38652aef5344609
### ERROR
<pre>
2018-02-22 17:43:13 ERROR    TORNADO :: [ccbc0ce] API :: 'find_by_id() takes exactly 3 arguments (2 given)'
Traceback (most recent call last):
  File "/opt/medusa/<a href="../blob/ccbc0ce9a2d3977a71bde03e29be503464ebe3cd/medusa/server/api/v1/core.py#L126">medusa/server/api/v1/core.py</a>", line 126, in get
    out_dict = _call_dispatcher(args, kwargs)
  File "/opt/medusa/<a href="../blob/ccbc0ce9a2d3977a71bde03e29be503464ebe3cd/medusa/server/api/v1/core.py#L196">medusa/server/api/v1/core.py</a>", line 196, in call_dispatcher
    cur_out_dict = func(cur_args, cur_kwargs).run()  # call function and get response
  File "/opt/medusa/<a href="../blob/ccbc0ce9a2d3977a71bde03e29be503464ebe3cd/medusa/server/api/v1/core.py#L2312">medusa/server/api/v1/core.py</a>", line 2312, in run
    'image': ShowBanner(Show.find_by_id(INDEXER_TVDBV2, self.indexerid)),
TypeError: find_by_id() takes exactly 3 arguments (2 given)
</pre>
---
_STAFF NOTIFIED_: @pymedusa/support @pymedusa/moderators



Discussion:

Resolving patch:
diff --git a/medusa/server/api/v1/core.py b/medusa/server/api/v1/core.py
--- a/medusa/server/api/v1/core.py
+++ b/medusa/server/api/v1/core.py
@@ -2309,7 +2309,7 @@ def run(self):
         """ Get the banner of a show """
         return {
             'outputType': 'image',
-            'image': ShowBanner(Show.find_by_id(INDEXER_TVDBV2, self.indexerid)),
+            'image': ShowBanner(Show.find_by_id(app.showList, INDEXER_TVDBV2, self.indexerid)),
         }
 
 
@@ -2337,7 +2337,7 @@ def run(self):
         """
         return {
             'outputType': 'image',
-            'image': ShowNetworkLogo(Show.find_by_id(INDEXER_TVDBV2, self.indexerid)),
+            'image': ShowNetworkLogo(Show.find_by_id(app.showList, INDEXER_TVDBV2, self.indexerid)),
         }
 
 
@@ -2363,7 +2363,7 @@ def run(self):
         """ Get the fan art of a show """
         return {
             'outputType': 'image',
-            'image': ShowFanArt(Show.find_by_id(INDEXER_TVDBV2, self.indexerid)),
+            'image': ShowFanArt(Show.find_by_id(app.showList, INDEXER_TVDBV2, self.indexerid)),
         }
 
 


Test patch:
Repository: pymedusa/Medusa

Issue:
simpleanidb cache directory wanting to be created in /root/.cache
I maintain a docker running the development branch of Medusa, last night I updated the docker and it would not start as it kept attempting to create a directory in the /root/.cache folder and did not have permissions.

I shelled into my docker image and changed permissions to allow it to discover it was creation a folder called simpleanidb and in the folder it downloaded the anime_list.xml file.

It appears to be an issue with the call occurring before app.CACHE_DIR has been set to a value from the config.ini



Discussion:
Tnx I'll try to fix and include it in the release tomorrow. 

Resolving patch:
diff --git a/medusa/show/recommendations/recommended.py b/medusa/show/recommendations/recommended.py
--- a/medusa/show/recommendations/recommended.py
+++ b/medusa/show/recommendations/recommended.py
@@ -42,9 +42,25 @@
 log.logger.addHandler(logging.NullHandler())
 
 session = MedusaSession()
-anidb_api = Anidb(cache_dir=app.CACHE_DIR)
 imdb_api = imdbpie.Imdb(session=session)
 
+anidb_api = None
+
+
+def load_anidb_api(func):
+    """
+    Decorate a function to lazy load the anidb_api.
+
+    We need to do this, because we're passing the Medusa cache location to the lib. As the module is imported before
+    the app.CACHE_DIR location has been read, we can't initialize it at module level.
+    """
+    def func_wrapper(aid):
+        global anidb_api
+        if anidb_api is None:
+            anidb_api = Anidb(cache_dir=app.CACHE_DIR)
+        return func(aid)
+    return func_wrapper
+
 
 class MissingTvdbMapping(Exception):
     """Exception used when a show can't be mapped to a tvdb indexer id."""
@@ -150,6 +166,7 @@ def __str__(self):
         return 'Recommended show {0} from recommended list: {1}'.format(self.title, self.recommender)
 
 
+@load_anidb_api
 @recommended_series_cache.cache_on_arguments()
 def cached_tvdb_to_aid(tvdb_id):
     """
@@ -160,6 +177,7 @@ def cached_tvdb_to_aid(tvdb_id):
     return anidb_api.tvdb_id_to_aid(tvdbid=tvdb_id)
 
 
+@load_anidb_api
 @recommended_series_cache.cache_on_arguments()
 def cached_aid_to_tvdb(aid):
     """


Test patch: