Spaces:
Configuration error

yonkasoft commited on
Commit
03c3044
1 Parent(s): 7573dc2

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +67 -0
handler.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pymongo import MongoClient
3
+ from sentence_transformers import SentenceTransformer, util
4
+ import boto3
5
+ import os
6
+
7
+ #----------------------------------------------------------------------------
8
+ def lambda_handler(event, context):
9
+ # S3'tan Python versiyonlarını alma
10
+ python_versions = _known_python_versions()
11
+
12
+ # Kullanıcıdan gelen inputu işleme
13
+ user_input = event.get("input")
14
+ if not user_input:
15
+ return {
16
+ "statusCode": 400,
17
+ "body": json.dumps("Input data is required")
18
+ }
19
+
20
+
21
+ save_user_input_to_mongodb({"input": user_input})
22
+ refenece_data_mongodb({})
23
+
24
+ # Similarity hesaplama
25
+ similarity_score = calculate_similarity(user_input, "Referans metin")
26
+
27
+ # Sonuçları döndürme
28
+ return {
29
+ "statusCode": 200,
30
+ "body": json.dumps({
31
+ "python_versions": python_versions,
32
+ "similarity_score": similarity_score
33
+ })
34
+ }
35
+ #-------------------------------------------------------------------------------
36
+ #s3 keywords'ü oluşturma gerekli
37
+ def _known_python_versions():
38
+ """Get current list from S3."""
39
+ try:
40
+ s3 = boto3.resource("s3")
41
+ obj = s3.Object(os.environ["S3_BUCKET"], "python/versions.json")
42
+ content = obj.get()["Body"].read().decode("utf-8")
43
+ except botocore.exceptions.ClientError:
44
+ print("Key not found, using empty list")
45
+ content = '{"python_versions":[]}'
46
+ return json.loads(content)
47
+
48
+ def save_user_input_to_mongodb(input_data):
49
+ client = MongoClient(os.environ["MONGODB_URI"])
50
+ db = client["EgitimDatabase"]
51
+ collection = db["input"]
52
+ collection.insert_one(input_data)
53
+ client.close()
54
+
55
+ def refenece_data_mongodb(reference_data):
56
+ client = MongoClient(os.environ["MONGODB_URI"])
57
+ db = client["EgitimDatabase"]
58
+ collection = db["test"]
59
+ collection.insert_one(reference_data)
60
+ client.close()
61
+ #--------------------------------------------------------------------------------
62
+ def calculate_similarity(text1, text2):
63
+ model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
64
+ embedding1 = model.encode(text1, convert_to_tensor=True)
65
+ embedding2 = model.encode(text2, convert_to_tensor=True)
66
+ similarity_score = util.pytorch_cos_sim(embedding1, embedding2)
67
+ return similarity_score.item()