Spaces:
Sleeping
Sleeping
Update app.py
Browse files19 unmodified lines2021222324252622 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481493 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617717853 unmodified lines23223323423523623723823924024124224324413 unmodified lines25825926026126226326426526626726826960 unmodified lines33033133233333433533633719 unmodified linesapp = Flask(__name__)cache = Cache(app, config={'CACHE_TYPE': 'simple'}) # You can choose a caching type based on your requirementsCORS(app)import moviepy.editor as mp22 unmodified linesprint(3)return face_locationsdef separate_image_text_from_pdf(pdf_url):# List to store page informationpages_info = []# Fetch the PDF from the URLresponse = requests.get(pdf_url)if response.status_code == 200:# Create a temporary directory to store the PDF datatemp_dir = tempfile.mkdtemp()# Define the temporary file path for the PDFtemp_pdf_path = os.path.join(temp_dir, "temp.pdf")# Write the PDF data to the temporary filewith open(temp_pdf_path, "wb") as tmp_file:tmp_file.write(response.content)# Open the PDFpdf = fitz.open(temp_pdf_path)# Iterate through each pagefor page_num in range(len(pdf)):page = pdf.load_page(page_num)# Extract texttext = page.get_text()# Count imagesimage_list = page.get_images(full=True)# Convert images to BytesIO and store in a listimages_bytes = []for img_index, img_info in enumerate(image_list):xref = img_info[0]base_image = pdf.extract_image(xref)image_bytes = base_image["image"]images_bytes.append(image_bytes)# Store page information in a dictionarypage_info = {"pgno": page_num + 1,"images": images_bytes,"text": text}# Append page information to the listpages_info.append(page_info)# Close the PDFpdf.close()# Clean up the temporary filesos.unlink(temp_pdf_path)os.rmdir(temp_dir)else:print("Failed to fetch the PDF from the URL.")return pages_infodef pdf_image_text_embedding_and_text_embedding(pages_info):# List to store page embeddingspage_embeddings = []# Iterate through each pagefor page in pages_info:# Extract text from the pagetext = page["text"]# Extract images from the pageimages = page["images"]# List to store image embeddingsimage_embeddings = []# Iterate through each imagefor image in images:# Get the image embeddingimage_embedding = get_image_embedding(image)extracted_text = extract_text(image)# Append the image embedding to the listimage_embeddings.append({"image_embedding": image_embedding.tolist() ,"extracted_text":extracted_text})# Get the text embedding# Store the page embeddings in a dictionarypage_embedding = {"images": image_embeddings,"text": text,}# Append the page embedding to the listpage_embeddings.append(page_embedding)return page_embeddingsdef separate_audio_from_video(video_url):try:3 unmodified lines# Extract audioaudio = video.audio# Create a temporary directory to store temporary filestemp_dir = tempfile.mkdtemp()# Define the temporary file path for the audiotemp_audio_filename = os.path.join(temp_dir, "audio.wav")# Write the audio data to the temporary fileaudio.write_audiofile(temp_audio_filename)# Read the audio data from the temporary file as byteswith open(temp_audio_filename, "rb") as f:audio_bytes = f.read()return audio_bytesexcept Exception as e:print("An error occurred:", e)@cache.cached(timeout=300)@app.route('/get_text_embedding', methods=['POST'])53 unmodified linesdef get_video_embedding_route():try:video_url = request.json.get("videoUrl")audio_data = separate_audio_from_video(video_url)audio_embedding = extract_audio_embeddings(audio_data)audio_embedding_list = audio_embeddingaudio_file = io.BytesIO(audio_data)r = sr.Recognizer()with sr.AudioFile(audio_file) as source:audio_data = r.record(source)extracted_text = ""try:text = r.recognize_google(audio_data)13 unmodified linestry:pdf_url = request.json.get("pdfUrl")print(1)pages_info = seperate_image_text_from_pdf(pdf_url)content = pdf_image_text_embedding_and_text_embedding(pages_info)print(content)return jsonify({"content": content}), 200except Exception as e:return jsonify({"error": str(e)}), 500# Route to get text description embeddings60 unmodified linesexcept Exception as e:return jsonify({"error": str(e)}), 500@app.route('/')def hello():return 'Hello, World!'19 unmodified lines2021222324252622 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531543 unmodified lines15815916016116216316416516616716816917017117217317417517617717817918018118253 unmodified lines23623723823924024124224324424524624724824925025125225325425525625725825926013 unmodified lines27427527627727827928028128228328428528628728828929029129229329429560 unmodified lines35635735819 unmodified linesapp = Flask(_name_)cache = Cache(app, config={'CACHE_TYPE': 'simple'}) # You can choose a caching type based on your requirementsCORS(app)import moviepy.editor as mp22 unmodified linesprint(3)return face_locationsdef seperate_image_text_from_pdf(pdf_url):# List to store page informationtry:pages_info = []# Fetch the PDF from the URLresponse = requests.get(pdf_url)if response.status_code == 200:# Create a temporary file to save the PDF datawith tempfile.NamedTemporaryFile(delete=False) as tmp_file:tmp_file.write(response.content)tmp_file_path = tmp_file.name# Open the PDFpdf = fitz.open(tmp_file_path)# Iterate through each pagefor page_num in range(len(pdf)):page = pdf.load_page(page_num)# Extract texttext = page.get_text()# Count imagesimage_list = page.get_images(full=True)# Convert images to BytesIO and store in a listimages_bytes = []for img_index, img_info in enumerate(image_list):xref = img_info[0]base_image = pdf.extract_image(xref)image_bytes = base_image["image"]images_bytes.append(image_bytes)# Store page information in a dictionarypage_info = {"pgno": page_num + 1,"images": images_bytes,"text": text}# Append page information to the listpages_info.append(page_info)# Close the PDFpdf.close()# Clean up the temporary fileimport osos.unlink(tmp_file_path)else:print("Failed to fetch the PDF from the URL.")except Exception as e:print("An error occurred:", e)return "Error"return pages_infodef pdf_image_text_embedding_and_text_embedding(pages_info):try:# List to store page embeddingspage_embeddings = []# Iterate through each pagefor page in pages_info:# Extract text from the pagetext = page["text"]# Extract images from the pageimages = page["images"]# List to store image embeddingsimage_embeddings = []# Iterate through each imagefor image in images:# Get the image embeddingimage_embedding = get_image_embedding(image)extracted_text = extract_text(image)# Append the image embedding to the listimage_embeddings.append({"image_embedding": image_embedding.tolist() ,"extracted_text":extracted_text})# Get the text embedding# Store the page embeddings in a dictionarypage_embedding = {"images": image_embeddings,"text": text,}# Append the page embedding to the listpage_embeddings.append(page_embedding)return page_embeddingsexcept Exception as e:print("An error occurred:", e)return "Error"def separate_audio_from_video(video_url):try:3 unmodified lines# Extract audioaudio = video.audio# Create a temporary file to write the audio datatry :with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio_file:temp_audio_filename = temp_audio_file.name# Write the audio data to the temporary fileaudio.write_audiofile(temp_audio_filename)# Read the audio data from the temporary file as byteswith open(temp_audio_filename, "rb") as f:audio_bytes = f.read()except Exception as e:return "Error"return audio_bytesexcept Exception as e:print("An error occurred:", e)return "Error"@cache.cached(timeout=300)@app.route('/get_text_embedding', methods=['POST'])53 unmodified linesdef get_video_embedding_route():try:video_url = request.json.get("videoUrl")try:audio_data = separate_audio_from_video(video_url)except Exception as e:return jsonify({"error": "Failed to extract audio from video 1"}), 500try:audio_embedding = extract_audio_embeddings(audio_data)except Exception as e:return jsonify({"error": "Failed to extract audio embeddings 2"}), 500audio_embedding_list = audio_embeddingtry :audio_file = io.BytesIO(audio_data)except Exception as e:return jsonify({"error": "Failed to extract audio embeddings 3"}), 500try :r = sr.Recognizer()with sr.AudioFile(audio_file) as source:audio_data = r.record(source)except Exception as e:return jsonify({"error": "Failed to extract audio embeddings 4"}), 500extracted_text = ""try:text = r.recognize_google(audio_data)13 unmodified linestry:pdf_url = request.json.get("pdfUrl")print(1)pages_infotry :pages_info = seperate_image_text_from_pdf(pdf_url)except Exception as e:print(e)return jsonify({"error": "Failed to fetch the PDF from the URL"}), 500if(pages_info == "Error"):return jsonify({"error": "Failed to fetch the PDF from the URL seperate_image_text_from_pdf "}), 500content = pdf_image_text_embedding_and_text_embedding(pages_info)if content == "Error":return jsonify({"error": "An error occurred while processing the PDF"}), 500print(content)return jsonify({"content": content}), 200except Exception as e:print(e)return jsonify({"error": str(e)}), 500# Route to get text description embeddings60 unmodified linesexcept Exception as e:return jsonify({"error": str(e)}), 500
app.py+133-112