File size: 2,487 Bytes
bf76cbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# app.py
from flask import Flask, render_template, request
import subprocess
import json
import os
import sys
from sentence_transformers import SentenceTransformer
from pinecone import Pinecone

app = Flask(__name__)

PINECONE_API_KEY = os.environ.get('PINECONE_API_KEY')
PINECONE_SPACE_NAME = os.environ.get('PINECONE_SPACE_NAME')

model = SentenceTransformer('paraphrase-MiniLM-L6-v2')

# Initialize Pinecone client
pc = Pinecone(api_key=PINECONE_API_KEY, environment='gcp-starter')
indexE = pc.Index(PINECONE_SPACE_NAME)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/search', methods=['POST'])
def search():
    if request.method == 'POST':
        query = request.form['query']
        youtube_links = []

        try:
            # Encode the user-provided input
            query_vector = model.encode(query)

            # Convert the query vector to a list
            query_vector_list = query_vector.tolist()

            # Query Pinecone with the vector using the 'Index' object
            results = indexE.query(
                namespace='',
                top_k=3,
                include_values=True,
                include_metadata=True,
                vector=query_vector_list,
            )

            if results and 'matches' in results and results['matches']:
                # Access metadata from each match
                for match in results['matches']:
                    metadata = match.get('metadata', {})
                    video_id = metadata.get('video_id')
                    start_time = metadata.get('start_time')
                    time = int(start_time)

                    # Create a clickable YouTube link
                    youtube_link = f'https://www.youtube.com/watch?v={video_id}&t={time}s'
                    youtube_links.append(youtube_link)

        except Exception as e:
            # Handle exceptions gracefully
            error_message = str(e)
            output = {'error': error_message}
            print(json.dumps(output))

        else:
            # No exceptions, render the template with results
            if youtube_links:
                return render_template('results.html', query=query, youtube_links=youtube_links)
            else:
                no_results_message = "No results found."
                return render_template('results.html', query=query, no_results_message=no_results_message)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)