code: def annotate_doc(doc, semgrex_result, semgrex_patterns, matches_only):
      """
      Put comments on the sentences which describe the matching semgrex patterns
      """
      doc = copy.deepcopy(doc)
      if isinstance(semgrex_patterns, str):
          semgrex_patterns = [semgrex_patterns]
      matching_sentences = []
      for sentence, graph_result in zip(
          doc.sentences, semgrex_result.result
      ):
          sentence_matched = False
          for semgrex_pattern, pattern_result in zip(
              semgrex_patterns, graph_result.result
          ):
              semgrex_pattern = semgrex_pattern.replace("\n", " ")
              if len(pattern_result.match) == 0:
                  sentence.add_comment(
                      "# semgrex pattern |%s| did not match!"
                      % semgrex_pattern
                  )
              else:
                  sentence_matched = True
                  for match in pattern_result.match:
                      match_word = "%d:%s" % (
                          match.matchIndex,
                          sentence.words[match.matchIndex - 1].text,
                      )
                      if len(match.node) == 0:
                          node_matches = ""
                      else:
                          node_matches = [
                              "%s=%d:%s"
                              % (
                                  node.name,
                                  node.matchIndex,
                                  sentence.words[
                                      node.matchIndex - 1
                                  ].text,
                              )
                              for node in match.node
                          ]
                          node_matches = "  " + " ".join(node_matches)
                      sentence.add_comment(
                          "# semgrex pattern |%s| matched at %s%s"
                          % (semgrex_pattern, match_word, node_matches)
                      )
          if sentence_matched:
              matching_sentences.append(sentence)
      if matches_only:
          doc.sentences = matching_sentences
      return doc
  
file_path: stanza/stanza/server/semgrex.py
imports: import argparse
  import copy
  import stanza
  from stanza.protobuf import SemgrexRequest, SemgrexResponse
  from stanza.server.java_protobuf_requests import send_request, add_token, add_word_to_graph, JavaProtobufContext, convert_networkx_graph
  from stanza.utils.conll import CoNLL
label_desc: Use image node_id 4 for calling a global function with example usage: annotate_doc(doc, semgrex_result, semgrex_patterns, matches_only) and returns: doc