prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Docs: Add links to source code
  This is really handy if people want to understand what's going on behind the scenes or want to implement more advanced stuff
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `generate_api_docs.py`
  Content:
  ```
  1 """https://github.com/NiklasRosenstein/pydoc-markdown/blob/master/pydocmd/__main__.py"""
  2 
  3 import os
  4 import sys
  5 import yaml
  6 
  7 from pydocmd.document import Index
  8 from pydocmd.imp import dir_object
  9 from pydocmd.loader import PythonLoader
  10 from pydocmd.preprocessor import Preprocessor
  11 
  12 
  13 with open("apidocs.yml", "r") as stream:
  14     api_structure = yaml.safe_load(stream)
  15 
  16 # Build the index and document structure first, we load the actual
  17 # docstrings at a later point.
  18 print("Building index...")
  19 index = Index()
  20 
  21 
  22 def add_sections(doc, object_names, depth=1):
  23     if isinstance(object_names, list):
  24         [add_sections(doc, x, depth) for x in object_names]
  25     elif isinstance(object_names, dict):
  26         for key, subsections in object_names.items():
  27             add_sections(doc, key, depth)
  28             add_sections(doc, subsections, depth + 1)
  29     elif isinstance(object_names, str):
  30         # Check how many levels of recursion we should be going.
  31         expand_depth = len(object_names)
  32         object_names = object_names.rstrip("+")
  33         expand_depth -= len(object_names)
  34 
  35         def create_sections(name, level):
  36             if level > expand_depth:
  37                 return
  38             index.new_section(doc, name, depth=depth + level, header_type="markdown")
  39             for sub in dir_object(name, "line", False):
  40                 sub = name + "." + sub
  41                 create_sections(sub, level + 1)
  42 
  43         create_sections(object_names, 0)
  44     else:
  45         raise RuntimeError(object_names)
  46 
  47 
  48 # Make sure that we can find modules from the current working directory,
  49 # and have them take precedence over installed modules.
  50 sys.path.insert(0, ".")
  51 
  52 for pages in api_structure:
  53     for fname, object_names in pages.items():
  54         doc = index.new_document(fname)
  55         add_sections(doc, object_names)
  56 
  57 loader = PythonLoader({})
  58 preproc = Preprocessor({})
  59 
  60 preproc.link_lookup = {}
  61 for file, doc in index.documents.items():
  62     for section in doc.sections:
  63         preproc.link_lookup[section.identifier] = file
  64 # Load the docstrings and fill the sections.
  65 print("Started generating documentation...")
  66 for doc in index.documents.values():
  67     for section in filter(lambda s: s.identifier, doc.sections):
  68         loader.load_section(section)
  69         preproc.preprocess_section(section)
  70 
  71 # Write out all the generated documents.
  72 os.makedirs(os.path.join("docs", "api"), exist_ok=True)
  73 for fname, doc in index.documents.items():
  74     with open(os.path.join("docs", "api", fname), "w") as fp:
  75         for section in doc.sections:
  76             section.render(fp)
  77
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/generate_api_docs.py b/generate_api_docs.py
  --- a/generate_api_docs.py
  +++ b/generate_api_docs.py
  @@ -1,5 +1,6 @@
   """https://github.com/NiklasRosenstein/pydoc-markdown/blob/master/pydocmd/__main__.py"""
   
  +import inspect
   import os
   import sys
   import yaml
  @@ -10,6 +11,23 @@
   from pydocmd.preprocessor import Preprocessor
   
   
  +def callable_to_source_link(obj, scope):
  +    path = scope.__file__.lstrip(".")
  +    source = inspect.getsourcelines(obj)
  +    line = source[-1] + 1 if source[0][0].startswith("@") else source[-1]
  +    link = f"https://github.com/plumerai/larq/blob/master{path}#L{line}"
  +    return f'<a class="headerlink code-link" style="float:right;" href="{link}" title="Source Code"></a>'
  +
  +
  +class PythonLoaderWithSource(PythonLoader):
  +    def load_section(self, section):
  +        super().load_section(section)
  +        obj = section.loader_context["obj"]
  +        if callable(obj):
  +            scope = section.loader_context["scope"]
  +            section.title += callable_to_source_link(obj, scope)
  +
  +
   with open("apidocs.yml", "r") as stream:
       api_structure = yaml.safe_load(stream)
   
  @@ -54,7 +72,7 @@
           doc = index.new_document(fname)
           add_sections(doc, object_names)
   
  -loader = PythonLoader({})
  +loader = PythonLoaderWithSource({})
   preproc = Preprocessor({})
   
   preproc.link_lookup = {}
  
verification_info: {"golden_diff": "diff --git a/generate_api_docs.py b/generate_api_docs.py\n--- a/generate_api_docs.py\n+++ b/generate_api_docs.py\n@@ -1,5 +1,6 @@\n \"\"\"https://github.com/NiklasRosenstein/pydoc-markdown/blob/master/pydocmd/__main__.py\"\"\"\n \n+import inspect\n import os\n import sys\n import yaml\n@@ -10,6 +11,23 @@\n from pydocmd.preprocessor import Preprocessor\n \n \n+def callable_to_source_link(obj, scope):\n+    path = scope.__file__.lstrip(\".\")\n+    source = inspect.getsourcelines(obj)\n+    line = source[-1] + 1 if source[0][0].startswith(\"@\") else source[-1]\n+    link = f\"https://github.com/plumerai/larq/blob/master{path}#L{line}\"\n+    return f'<a class=\"headerlink code-link\" style=\"float:right;\" href=\"{link}\" title=\"Source Code\"></a>'\n+\n+\n+class PythonLoaderWithSource(PythonLoader):\n+    def load_section(self, section):\n+        super().load_section(section)\n+        obj = section.loader_context[\"obj\"]\n+        if callable(obj):\n+            scope = section.loader_context[\"scope\"]\n+            section.title += callable_to_source_link(obj, scope)\n+\n+\n with open(\"apidocs.yml\", \"r\") as stream:\n     api_structure = yaml.safe_load(stream)\n \n@@ -54,7 +72,7 @@\n         doc = index.new_document(fname)\n         add_sections(doc, object_names)\n \n-loader = PythonLoader({})\n+loader = PythonLoaderWithSource({})\n preproc = Preprocessor({})\n \n preproc.link_lookup = {}\n", "issue": "Docs: Add links to source code\nThis is really handy if people want to understand what's going on behind the scenes or want to implement more advanced stuff\n", "before_files": [{"content": "\"\"\"https://github.com/NiklasRosenstein/pydoc-markdown/blob/master/pydocmd/__main__.py\"\"\"\n\nimport os\nimport sys\nimport yaml\n\nfrom pydocmd.document import Index\nfrom pydocmd.imp import dir_object\nfrom pydocmd.loader import PythonLoader\nfrom pydocmd.preprocessor import Preprocessor\n\n\nwith open(\"apidocs.yml\", \"r\") as stream:\n    api_structure = yaml.safe_load(stream)\n\n# Build the index and document structure first, we load the actual\n# docstrings at a later point.\nprint(\"Building index...\")\nindex = Index()\n\n\ndef add_sections(doc, object_names, depth=1):\n    if isinstance(object_names, list):\n        [add_sections(doc, x, depth) for x in object_names]\n    elif isinstance(object_names, dict):\n        for key, subsections in object_names.items():\n            add_sections(doc, key, depth)\n            add_sections(doc, subsections, depth + 1)\n    elif isinstance(object_names, str):\n        # Check how many levels of recursion we should be going.\n        expand_depth = len(object_names)\n        object_names = object_names.rstrip(\"+\")\n        expand_depth -= len(object_names)\n\n        def create_sections(name, level):\n            if level > expand_depth:\n                return\n            index.new_section(doc, name, depth=depth + level, header_type=\"markdown\")\n            for sub in dir_object(name, \"line\", False):\n                sub = name + \".\" + sub\n                create_sections(sub, level + 1)\n\n        create_sections(object_names, 0)\n    else:\n        raise RuntimeError(object_names)\n\n\n# Make sure that we can find modules from the current working directory,\n# and have them take precedence over installed modules.\nsys.path.insert(0, \".\")\n\nfor pages in api_structure:\n    for fname, object_names in pages.items():\n        doc = index.new_document(fname)\n        add_sections(doc, object_names)\n\nloader = PythonLoader({})\npreproc = Preprocessor({})\n\npreproc.link_lookup = {}\nfor file, doc in index.documents.items():\n    for section in doc.sections:\n        preproc.link_lookup[section.identifier] = file\n# Load the docstrings and fill the sections.\nprint(\"Started generating documentation...\")\nfor doc in index.documents.values():\n    for section in filter(lambda s: s.identifier, doc.sections):\n        loader.load_section(section)\n        preproc.preprocess_section(section)\n\n# Write out all the generated documents.\nos.makedirs(os.path.join(\"docs\", \"api\"), exist_ok=True)\nfor fname, doc in index.documents.items():\n    with open(os.path.join(\"docs\", \"api\", fname), \"w\") as fp:\n        for section in doc.sections:\n            section.render(fp)\n", "path": "generate_api_docs.py"}], "after_files": [{"content": "\"\"\"https://github.com/NiklasRosenstein/pydoc-markdown/blob/master/pydocmd/__main__.py\"\"\"\n\nimport inspect\nimport os\nimport sys\nimport yaml\n\nfrom pydocmd.document import Index\nfrom pydocmd.imp import dir_object\nfrom pydocmd.loader import PythonLoader\nfrom pydocmd.preprocessor import Preprocessor\n\n\ndef callable_to_source_link(obj, scope):\n    path = scope.__file__.lstrip(\".\")\n    source = inspect.getsourcelines(obj)\n    line = source[-1] + 1 if source[0][0].startswith(\"@\") else source[-1]\n    link = f\"https://github.com/plumerai/larq/blob/master{path}#L{line}\"\n    return f'<a class=\"headerlink code-link\" style=\"float:right;\" href=\"{link}\" title=\"Source Code\"></a>'\n\n\nclass PythonLoaderWithSource(PythonLoader):\n    def load_section(self, section):\n        super().load_section(section)\n        obj = section.loader_context[\"obj\"]\n        if callable(obj):\n            scope = section.loader_context[\"scope\"]\n            section.title += callable_to_source_link(obj, scope)\n\n\nwith open(\"apidocs.yml\", \"r\") as stream:\n    api_structure = yaml.safe_load(stream)\n\n# Build the index and document structure first, we load the actual\n# docstrings at a later point.\nprint(\"Building index...\")\nindex = Index()\n\n\ndef add_sections(doc, object_names, depth=1):\n    if isinstance(object_names, list):\n        [add_sections(doc, x, depth) for x in object_names]\n    elif isinstance(object_names, dict):\n        for key, subsections in object_names.items():\n            add_sections(doc, key, depth)\n            add_sections(doc, subsections, depth + 1)\n    elif isinstance(object_names, str):\n        # Check how many levels of recursion we should be going.\n        expand_depth = len(object_names)\n        object_names = object_names.rstrip(\"+\")\n        expand_depth -= len(object_names)\n\n        def create_sections(name, level):\n            if level > expand_depth:\n                return\n            index.new_section(doc, name, depth=depth + level, header_type=\"markdown\")\n            for sub in dir_object(name, \"line\", False):\n                sub = name + \".\" + sub\n                create_sections(sub, level + 1)\n\n        create_sections(object_names, 0)\n    else:\n        raise RuntimeError(object_names)\n\n\n# Make sure that we can find modules from the current working directory,\n# and have them take precedence over installed modules.\nsys.path.insert(0, \".\")\n\nfor pages in api_structure:\n    for fname, object_names in pages.items():\n        doc = index.new_document(fname)\n        add_sections(doc, object_names)\n\nloader = PythonLoaderWithSource({})\npreproc = Preprocessor({})\n\npreproc.link_lookup = {}\nfor file, doc in index.documents.items():\n    for section in doc.sections:\n        preproc.link_lookup[section.identifier] = file\n# Load the docstrings and fill the sections.\nprint(\"Started generating documentation...\")\nfor doc in index.documents.values():\n    for section in filter(lambda s: s.identifier, doc.sections):\n        loader.load_section(section)\n        preproc.preprocess_section(section)\n\n# Write out all the generated documents.\nos.makedirs(os.path.join(\"docs\", \"api\"), exist_ok=True)\nfor fname, doc in index.documents.items():\n    with open(os.path.join(\"docs\", \"api\", fname), \"w\") as fp:\n        for section in doc.sections:\n            section.render(fp)\n", "path": "generate_api_docs.py"}]}