code: from flask import Flask, jsonify, request, json, send_from_directory
  import os
  import openai
  import pandas as pd
  import base64
  import os
  import requests
  import numpy as np
  # import google.cloud.texttospeech as tts
  import lancedb
  
  
  from flask_cors import CORS
  
  # os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'service.json'
  # os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.getenv("GCP")
  openai.api_key = os.getenv("OPENAI_API_KEY")
  app = Flask(__name__)
  CORS(app, resources={r"/*": {"origins": "*"}})
  
  
  
  stories_file = 'data/stories.csv'
  session_file = 'data/session.csv'
  uri = "./data/lancedb"
  db = lancedb.connect(uri)
  
  try:
      db.create_table('mytale', data=[{"vector":[0,0],"id": "0", "title": "", "story": "", "img":['','','',''], "audio":""}])
  except:
      pass
  
  def insertIntoLance(data):
      t = db.open_table('mytale')
      t.add(data=data)
      print('inserted into lance')
      return t
  
  def readLance():
      t = db.open_table('mytale')
      #print(t.head())
      print('read lance')
  
      return t.head()
  
  
  @app.route('/test', methods=['GET'])
  def getLance():
      data = readLance()
  
      id_values = data['id'].to_pandas().tolist()
      title_values = data['title'].to_pandas().tolist()
      story_values = data['story'].to_pandas().tolist()
      audio_values = data['audio'].to_pandas().tolist()
      img_values = data['img'].to_pandas().tolist()
  
      # Construct a list of dictionaries with 'id', 'title', 'story', and 'audio' keys
      final = []
      for i in range(1,len(id_values)):
        
  
          entry = {
              'id': id_values[i],
              'title': title_values[i],
              'story': f"""{story_values[i]}""",
              'img':[img_values[i][0],img_values[i][1],img_values[i][2],img_values[i][3]],
              'audio': audio_values[i]
          }
          final.append(entry)
  
      # Convert the list of dictionaries to JSON format
      return final
  
  # if not os.path.exists(stories_file):
  #     df = pd.DataFrame({
  #         "id": [],
  #         "title": [],
  #         "story": [],
  #         "img": []
  #     })
  #     df.to_csv(stories_file, index=False)
  
  if not os.path.exists(session_file):
      df = pd.DataFrame({
          "id": [],
          "sess_id": [],
          "story_id": [],
          "role": [],
          "content": []
      })
      df.to_csv(session_file, index=False)
  
  # stories_df = pd.read_csv(stories_file)
  session_df = pd.read_csv(session_file)
  
  def generate_story(topic: str) -> str:
      completion = openai.ChatCompletion.create(
          model="gpt-3.5-turbo",
          messages=[
              {"role": "user", "content": f"Generate a 4 paragraph children's story with title about {topic} that contains a moral."}
          ]
      )
      content = completion.choices[0].message.content
      content = content.encode().decode('unicode_escape')
      title = content.split('\n')[0]
      title = title.replace('Title: ', '')
      story = content[content.find('\n'):]
      story = story.lstrip()
  
      return title, story
  
  def generate_prompts(story: str):
      completion = openai.ChatCompletion.create(
          model="gpt-3.5-turbo",
          messages=[
              {"role": "user", "content": f"Create four text to image prompts, seperated by new line, that will be suitable as images of the below given story such that each image represents a paragraph in the story. Do not include the character names, instead include only the characters physical description.\n\n{story}"}
          ]
      )
      
      prompts = completion.choices[0].message.content
      prompts = prompts.encode().decode('unicode_escape')
      prompts = prompts.split('\n')
      ans = []
      for i in prompts:
          #t = i.message.content
          #t = t.encode().decode('unicode_escape')
          if ':' in i:
              i = i[i.find(':')+1:]
          i = i.strip()
          if(i != ""):
              ans.append(i)
          
      content = completion.choices[0].message.content
      content = content.encode().decode('unicode_escape')
      if ':' in content:
          content = content[content.find(':')+1:]
      content = content.strip()
      return ans
  
  def generate_image(prompt: str):
      engine_id = "stable-diffusion-512-v2-1"
      api_host = os.getenv('API_HOST', 'https://api.stability.ai')
      api_key = os.getenv("STABILITYAI_API_KEY")
  
      if api_key is None:
          raise Exception("Missing Stability API key.")
  
      response = requests.post(
          f"{api_host}/v1/generation/{engine_id}/text-to-image",
          headers={
              "Content-Type": "application/json",
              "Accept": "application/json",
              "Authorization": f"Bearer {api_key}"
          },
          json={
              "text_prompts": [
                  {
                      "text": f"{prompt}"
                  }
              ],
              "cfg_scale": 7,
              "clip_guidance_preset": "FAST_BLUE",
              "height": 512,
              "width": 512,
              "samples": 1,
              "steps": 30,
          },
      )
  
      if response.status_code != 200:
          raise Exception(
              "Non-200 response for image generation: " + str(response.text))
  
      data = response.json()
  
      for i, image in enumerate(data["artifacts"]):
  
          return image["base64"]
  
  def save_story(title: str, story: str, img: [],audio_filename: str):
      img_filename=[]
  
      for i in range(len(img)):
          img_filename.append(f"./images/{title+str(i)}.png")
          with open(img_filename[i], "wb") as f:
              f.write(base64.b64decode(img[i]))
  
      global stories_df
  
      images_dest=[]
  
      for i in range(len(img)):
          # images_dest.append(request.root_url + 'images/' + title+str(i) + '.png')
          images_dest.append('images/' + title+str(i) + '.png')
  
      images_dest = np.array(images_dest)
      # temp_df = pd.DataFrame({
      #     "id": [len(stories_df)+1],
      #     "title": [title],
      #     "story": [story],
      #     "img": [images_dest.tolist()],
      #     "audio": [request.root_url + 'audios/' + title + '.wav']
      # })
  #[{"vector": [1, 1], "id": 2, "title": "test", "story": "test", "img": ['a', 'b', 'c', 'd'], "audio": "asdasd"}]
     
      insertIntoLance([{
          "vector":[len(getLance())+1, len(getLance())+1],
          # "id": len(stories_df)+1,
          "id": len(getLance())+1,
          "title": title,
          "story": story.replace("'", "\\'"),
          "img": images_dest.tolist(),
          "audio": request.root_url + 'audios/' + title + '.wav'
      }])
  
      # stories_df = pd.concat([stories_df, temp_df], ignore_index=True)
      # stories_df.to_csv(stories_file, index=False)
  
  def get_followup_response(session_id: int, story_id: int, question: str):
      global session_df
  
      # story = stories_df[stories_df['id'] == story_id]['story'].values[0]
      # t = getLance()
      # print("t", t)
      # print(f"story id {story_id}")
      # story = t[story_id+1]['story']
  
      print("story_id", story_id)
      data = getLance()
      target_story = next((story for story in data if int(story["id"]) == story_id), None)
      story = target_story["story"]
      print("story", story)
      
      system_msg = f"You are an assistant that answers the questions to the children's "\
                   "story given below. You should answer the questions descriptively in a "\
                   "way that a child can understand them. If the question asked is unrelated "\
                   "to the story, do not answer the question and instead reply by asking the "\
                   "user to ask questions related to the story."\
                   "\n\n"\
                   f"Story: {story}"
  
      temp_df = pd.DataFrame({
          "id": [len(session_df)+1],
          "sess_id": [session_id],
          "story_id": [story_id],
          "role": ["user"],
          "content": [question]
      })
  
      session_df = pd.concat([session_df, temp_df], ignore_index=True)
  
      messages = session_df[session_df['sess_id']
                            == session_id][["id", "role", "content"]]
      messages = messages.sort_values(by=['id'])
      messages = messages[['role', 'content']]
      messages = messages.to_dict('records')
  
      completion = openai.ChatCompletion.create(
          model="gpt-3.5-turbo",
          messages=[
              {"role": "system", "content": system_msg},
              *messages
          ]
      )
  
      content = completion.choices[0].message.content
      content = content.encode().decode('unicode_escape')
  
      temp_df = pd.DataFrame({
          "id": [len(session_df)+1],
          "sess_id": [session_id],
          "story_id": [story_id],
          "role": ["assistant"],
          "content": [content]
      })
  
      session_df = pd.concat([session_df, temp_df], ignore_index=True)
      session_df.to_csv(session_file, index=False)
  
      return content
  
  def text_to_wav(text: str, title, dest, voice_name = "en-IN-Wavenet-A"):
      language_code = "-".join(voice_name.split("-")[:2])
      text_input = tts.SynthesisInput(text=text)
      voice_params = tts.VoiceSelectionParams(
          language_code=language_code, name=voice_name
      )
      audio_config = tts.AudioConfig(audio_encoding=tts.AudioEncoding.LINEAR16,
                                     speaking_rate=0.8)
  
      client = tts.TextToSpeechClient()
      response = client.synthesize_speech(
          input=text_input,
          voice=voice_params,
          audio_config=audio_config,
      )
  
      filename = f"{dest + '/' + title}.wav"
      with open(filename, "wb") as out:
          out.write(response.audio_content)
          print(f'Generated speech saved to "{filename}"')
  
      return filename
  
  @app.route('/', methods=['GET'])
  def index():
      return jsonify({'message': 'Hello World!'})
  
  @app.route('/images/<path:path>', methods=['GET'])
  def get_image(path):
      return send_from_directory('images', path)
  
  @app.route('/audios/<path:path>', methods=['GET'])
  def get_audio(path):
      return send_from_directory('audios', path)
  
  @app.route('/generate', methods=['GET'])
  def generate():
      topic = request.args.get('topic')
      title, story = generate_story(topic)
      print(f"Title: {title}")
      print(f"Story: {story}")
      prompts = generate_prompts(story)
      print(f"Prompts: {prompts}")
      img = []
      for i in range(len(prompts)):
          img.append(generate_image(prompts[i]))
          print("Image generated")
      # audio_file = text_to_wav(story, title, "./audios")
      audio_file = ""
      print("Audio generated")
      save_story(title, story, img, audio_file)
  
      t = getLance()
      tl = len(t)
  
      return jsonify({'title': title, 'story': story, "id": tl,
                       'img': request.root_url + 'images/' + title + '.png', 'audio': request.root_url + 'audios/' + title + '.wav'})
  
  @app.route('/get_story', methods=['GET'])
  def get_story():
      story_id = int(request.args.get('id'))
      t = getLance()
      return t[story_id]['story']
      # story = stories_df[stories_df['id'] == story_id].to_dict('records')[0]
      # if(type(story['img']) == str):
      #     story['img'] = ast.literal_eval(story['img'])
  
      
  
      return jsonify({'story': story})
  
  
  @app.route('/get_n_stories', methods=['GET'])
  def get_n_stories():
      # n = int(request.args.get('n'))
      # sampled_stories = stories_df.sample(n=n).copy()
  
      # for idx, story in sampled_stories.iterrows():
      #     if(type(sampled_stories.at[idx, 'img']) == str):
      #         sampled_stories.at[idx, 'img'] = ast.literal_eval(story['img'])
  
      # stories = sampled_stories.to_dict('records')
      return jsonify({'stories': getLance()})
      return jsonify({'stories': stories})
  
  
  @app.route('/get_story_count', methods=['GET'])
  def get_story_count():
      return jsonify({'count': len(getLance())})
  
  @app.route('/get_followup', methods=['GET'])
  def get_followup():
      session_id = int(request.args.get('session_id'))
      story_id = int(request.args.get('story_id'))
      question = request.args.get('question')
      response = get_followup_response(session_id, story_id, question)
      # audio_file = text_to_wav(response, f"temp", "./audios")
      audio_file = ""
      return jsonify({'response': response, 'audio': request.root_url + 'audios/' + 'temp' + '.wav'})
  
  def transcribe_file(audio):
      """Transcribe the given audio file."""
      from google.cloud import speech
  
      client = speech.SpeechClient()
  
      audio = speech.RecognitionAudio(content=audio)
      config = speech.RecognitionConfig(
          encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
          sample_rate_hertz=48000,
          language_code="en-US",
      )
  
      response = client.recognize(config=config, audio=audio)
  
      # Each result is for a consecutive portion of the audio. Iterate through
      # them to get the transcripts for the entire audio file.
      for result in response.results:
          # The first alternative is the most likely one for this portion.
          print("Transcript: {}".format(result.alternatives[0].transcript))
          return result.alternatives[0].transcript
  
  @app.route('/post_followup_audio', methods=['POST'])
  def get_text():
      # get the audio data from form
      audio_file = request.files['audio']
      sess_id = request.form['session_id']
      story_id = request.form['story_id']
      text = transcribe_file(audio_file.read())
      if text is None:
          return jsonify({'response': 'Sorry, I could not understand you. Please try again.'})
      response = get_followup_response(sess_id, story_id, text)
      return jsonify({'response': response})
  
  if __name__ == '__main__':
  
      # app.run()
      app.run(debug=True)
apis: lancedb.connect
extract_api: [((407, 434), 'os.getenv', 'os.getenv', (['"""OPENAI_API_KEY"""'], {}), "('OPENAI_API_KEY')\n", (416, 434), False, 'import os\n'), ((441, 456), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (446, 456), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((457, 502), 'flask_cors.CORS', 'CORS', (['app'], {'resources': "{'/*': {'origins': '*'}}"}), "(app, resources={'/*': {'origins': '*'}})\n", (461, 502), False, 'from flask_cors import CORS\n'), ((603, 623), 'lancedb.connect', 'lancedb.connect', (['uri'], {}), '(uri)\n', (618, 623), False, 'import lancedb\n'), ((2347, 2372), 'pandas.read_csv', 'pd.read_csv', (['session_file'], {}), '(session_file)\n', (2358, 2372), True, 'import pandas as pd\n'), ((2083, 2111), 'os.path.exists', 'os.path.exists', (['session_file'], {}), '(session_file)\n', (2097, 2111), False, 'import os\n'), ((2122, 2208), 'pandas.DataFrame', 'pd.DataFrame', (["{'id': [], 'sess_id': [], 'story_id': [], 'role': [], 'content': []}"], {}), "({'id': [], 'sess_id': [], 'story_id': [], 'role': [],\n    'content': []})\n", (2134, 2208), True, 'import pandas as pd\n'), ((2430, 2626), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': '"""gpt-3.5-turbo"""', 'messages': '[{\'role\': \'user\', \'content\':\n    f"Generate a 4 paragraph children\'s story with title about {topic} that contains a moral."\n    }]'}), '(model=\'gpt-3.5-turbo\', messages=[{\'role\':\n    \'user\', \'content\':\n    f"Generate a 4 paragraph children\'s story with title about {topic} that contains a moral."\n    }])\n', (2458, 2626), False, 'import openai\n'), ((2987, 3375), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': '"""gpt-3.5-turbo"""', 'messages': '[{\'role\': \'user\', \'content\':\n    f"""Create four text to image prompts, seperated by new line, that will be suitable as images of the below given story such that each image represents a paragraph in the story. Do not include the character names, instead include only the characters physical description.\n\n{story}"""\n    }]'}), '(model=\'gpt-3.5-turbo\', messages=[{\'role\':\n    \'user\', \'content\':\n    f"""Create four text to image prompts, seperated by new line, that will be suitable as images of the below given story such that each image represents a paragraph in the story. Do not include the character names, instead include only the characters physical description.\n\n{story}"""\n    }])\n', (3015, 3375), False, 'import openai\n'), ((4117, 4166), 'os.getenv', 'os.getenv', (['"""API_HOST"""', '"""https://api.stability.ai"""'], {}), "('API_HOST', 'https://api.stability.ai')\n", (4126, 4166), False, 'import os\n'), ((4181, 4213), 'os.getenv', 'os.getenv', (['"""STABILITYAI_API_KEY"""'], {}), "('STABILITYAI_API_KEY')\n", (4190, 4213), False, 'import os\n'), ((4309, 4669), 'requests.post', 'requests.post', (['f"""{api_host}/v1/generation/{engine_id}/text-to-image"""'], {'headers': "{'Content-Type': 'application/json', 'Accept': 'application/json',\n    'Authorization': f'Bearer {api_key}'}", 'json': "{'text_prompts': [{'text': f'{prompt}'}], 'cfg_scale': 7,\n    'clip_guidance_preset': 'FAST_BLUE', 'height': 512, 'width': 512,\n    'samples': 1, 'steps': 30}"}), "(f'{api_host}/v1/generation/{engine_id}/text-to-image',\n    headers={'Content-Type': 'application/json', 'Accept':\n    'application/json', 'Authorization': f'Bearer {api_key}'}, json={\n    'text_prompts': [{'text': f'{prompt}'}], 'cfg_scale': 7,\n    'clip_guidance_preset': 'FAST_BLUE', 'height': 512, 'width': 512,\n    'samples': 1, 'steps': 30})\n", (4322, 4669), False, 'import requests\n'), ((5650, 5671), 'numpy.array', 'np.array', (['images_dest'], {}), '(images_dest)\n', (5658, 5671), True, 'import numpy as np\n'), ((7674, 7725), 'pandas.concat', 'pd.concat', (['[session_df, temp_df]'], {'ignore_index': '(True)'}), '([session_df, temp_df], ignore_index=True)\n', (7683, 7725), True, 'import pandas as pd\n'), ((7996, 8116), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': '"""gpt-3.5-turbo"""', 'messages': "[{'role': 'system', 'content': system_msg}, *messages]"}), "(model='gpt-3.5-turbo', messages=[{'role':\n    'system', 'content': system_msg}, *messages])\n", (8024, 8116), False, 'import openai\n'), ((8493, 8544), 'pandas.concat', 'pd.concat', (['[session_df, temp_df]'], {'ignore_index': '(True)'}), '([session_df, temp_df], ignore_index=True)\n', (8502, 8544), True, 'import pandas as pd\n'), ((9462, 9498), 'flask.jsonify', 'jsonify', (["{'message': 'Hello World!'}"], {}), "({'message': 'Hello World!'})\n", (9469, 9498), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((9583, 9618), 'flask.send_from_directory', 'send_from_directory', (['"""images"""', 'path'], {}), "('images', path)\n", (9602, 9618), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((9703, 9738), 'flask.send_from_directory', 'send_from_directory', (['"""audios"""', 'path'], {}), "('audios', path)\n", (9722, 9738), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((9809, 9834), 'flask.request.args.get', 'request.args.get', (['"""topic"""'], {}), "('topic')\n", (9825, 9834), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((10332, 10501), 'flask.jsonify', 'jsonify', (["{'title': title, 'story': story, 'id': tl, 'img': request.root_url +\n    'images/' + title + '.png', 'audio': request.root_url + 'audios/' +\n    title + '.wav'}"], {}), "({'title': title, 'story': story, 'id': tl, 'img': request.root_url +\n    'images/' + title + '.png', 'audio': request.root_url + 'audios/' +\n    title + '.wav'})\n", (10339, 10501), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((10857, 10882), 'flask.jsonify', 'jsonify', (["{'story': story}"], {}), "({'story': story})\n", (10864, 10882), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((11340, 11369), 'flask.jsonify', 'jsonify', (["{'stories': stories}"], {}), "({'stories': stories})\n", (11347, 11369), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((11673, 11701), 'flask.request.args.get', 'request.args.get', (['"""question"""'], {}), "('question')\n", (11689, 11701), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((11864, 11956), 'flask.jsonify', 'jsonify', (["{'response': response, 'audio': request.root_url + 'audios/' + 'temp' + '.wav'}"], {}), "({'response': response, 'audio': request.root_url + 'audios/' +\n    'temp' + '.wav'})\n", (11871, 11956), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((12075, 12096), 'google.cloud.speech.SpeechClient', 'speech.SpeechClient', ([], {}), '()\n', (12094, 12096), False, 'from google.cloud import speech\n'), ((12110, 12148), 'google.cloud.speech.RecognitionAudio', 'speech.RecognitionAudio', ([], {'content': 'audio'}), '(content=audio)\n', (12133, 12148), False, 'from google.cloud import speech\n'), ((12162, 12297), 'google.cloud.speech.RecognitionConfig', 'speech.RecognitionConfig', ([], {'encoding': 'speech.RecognitionConfig.AudioEncoding.LINEAR16', 'sample_rate_hertz': '(48000)', 'language_code': '"""en-US"""'}), "(encoding=speech.RecognitionConfig.AudioEncoding.\n    LINEAR16, sample_rate_hertz=48000, language_code='en-US')\n", (12186, 12297), False, 'from google.cloud import speech\n'), ((13215, 13246), 'flask.jsonify', 'jsonify', (["{'response': response}"], {}), "({'response': response})\n", (13222, 13246), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((10594, 10616), 'flask.request.args.get', 'request.args.get', (['"""id"""'], {}), "('id')\n", (10610, 10616), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((11577, 11607), 'flask.request.args.get', 'request.args.get', (['"""session_id"""'], {}), "('session_id')\n", (11593, 11607), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((11628, 11656), 'flask.request.args.get', 'request.args.get', (['"""story_id"""'], {}), "('story_id')\n", (11644, 11656), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((13064, 13141), 'flask.jsonify', 'jsonify', (["{'response': 'Sorry, I could not understand you. Please try again.'}"], {}), "({'response': 'Sorry, I could not understand you. Please try again.'})\n", (13071, 13141), False, 'from flask import Flask, jsonify, request, json, send_from_directory\n'), ((5386, 5410), 'base64.b64decode', 'base64.b64decode', (['img[i]'], {}), '(img[i])\n', (5402, 5410), False, 'import base64\n')]