Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ pids
*.seed
*.pid.lock

# Ignore Python cache directories
__pycache__/

# Ignore compiled Python files
*.pyc

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

Expand Down
7 changes: 7 additions & 0 deletions backend/crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import mongoConnect as mc

if __name__ == "__main__":
uri = "mongodb+srv://wangyukun721:[email protected]/?retryWrites=true&w=majority&appName=Cluster0"

with mc.connect_to_mongoDB(uri) as client:
mc.upload(r'C:\Users\81548\OneDrive\文档\GitHub\Team-JSSH-HTV9\backend\test.txt', client)
13 changes: 13 additions & 0 deletions backend/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from fastapi import FastAPI

app = FastAPI()

# Define a simple route
@app.get("/")
def read_root():
return {"Hello": "World"}

# Another route for example
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
109 changes: 109 additions & 0 deletions backend/mongoConnect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import pprint
import ast

from pymongo import MongoClient
import pymongo
from bson.objectid import ObjectId

def connect_to_mongoDB(uri):
try:
client = MongoClient(uri, server_api=pymongo.server_api.ServerApi(
version="1", strict=True, deprecation_errors=True))
# end example code here
client.admin.command("ping")
print("Connected successfully")
return client

except Exception as e:
raise Exception(
"The following error occurred: ", e)
def read_and_parse_file(file_path):
"""
Safely reads a string from a text file and converts it into a list of dictionaries.

:param file_path: The path to the text file containing the string representation of a list of dictionaries.
:return: A list of dictionaries if parsing is successful, otherwise None.
"""
try:
# Step 1: Read the file content
with open(file_path, 'r', encoding='utf-8') as file:
file_content = file.read()

# Step 2: Safely parse the content using ast.literal_eval
data = ast.literal_eval(file_content)

# Ensure that the parsed data is indeed a list of dictionaries
if isinstance(data, list) and all(isinstance(item, dict) for item in data):
return data
else:
raise ValueError("Parsed content is not a list of dictionaries.")

except (SyntaxError, ValueError, IOError) as e:
print(f"An error occurred while reading or parsing the file: {e}")
return None

def upload_txt (fp, client):
db = client.history
history_collection = db.singleton
content = read_and_parse_file(fp)
for dictionary in content:
db.singleton.insert_one(dictionary)
print("upload success")

def upload_json(jsonFile, client):
db = client.history
history_collection = db.singleton
for dictionary in jsonFile:
db.singleton.insert_one(dictionary)
print("upload success")

def format_meeting_records(documents):
"""
Converts a list of MongoDB documents into a human-readable string format,
separating each meeting by the 'TERMINATE' marker and formatting each speaker's content.

:param documents: List of dictionaries containing 'content', 'role', and 'name'.
:return: A string that organizes the content into separate meetings, formatted for readability.
"""
meetings = []
current_meeting = []

for document in documents:
content = document['content'].strip()
role = document['role']
name = document['name']

# If the document's content is 'TERMINATE', finalize the current meeting and start a new one
if content == 'TERMINATE':
meetings.append('\n'.join(current_meeting)) # Finalize the current meeting
current_meeting = [] # Reset for the next meeting
else:
# Format each speaker's contribution
formatted_entry = f"{name} ({role}):\n{content}\n"
current_meeting.append(formatted_entry)

# If there's leftover content after the last 'TERMINATE', finalize it
if current_meeting:
meetings.append('\n'.join(current_meeting))

# Combine all meetings with a separator between them
formatted_output = "\n\n=== New Meeting ===\n\n".join(meetings)

return formatted_output

def download_from_db(client):
db = client.history
history_collection = db.singleton
result = history_collection.find({},{"content": 1, "role": 1, "name": 1, "_id": 0})
return format_meeting_records(result)


if __name__ == "__main__":
uri = "mongodb+srv://wangyukun721:[email protected]/?retryWrites=true&w=majority&appName=Cluster0"

with connect_to_mongoDB(uri) as client:
meetings = download_from_db(client)
print(meetings)
client.close()


1 change: 1 addition & 0 deletions backend/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{'content': '\nwrite a code to comput the factorial of a numbers\n', 'role': 'assistant', 'name': 'user_proxy'}, {'content': 'Sure, here is a Python code to compute the factorial of a number:\n\n```python\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n\nnumber = 5\nresult = factorial(number)\nprint(f"The factorial of {number} is {result}")\n```\n\nThis code defines a recursive function `factorial` that calculates the factorial of a given number `n`. It then calculates the factorial of 5 and prints the result.', 'name': 'Sam', 'role': 'user'}, {'content': 'The code provided by Sam looks correct. It defines a recursive function to calculate the factorial of a number and then calculates the factorial of 5. The code should work as expected.\n\nDo you need any further assistance with this code?', 'name': 'John', 'role': 'user'}, {'content': 'exitcode: 0 (execution succeeded)\nCode output: \nThe factorial of 5 is 120\n', 'role': 'assistant', 'name': 'user_proxy'}, {'content': "Great! I'm glad the code worked as expected. If you have any more questions or need further assistance in the future, feel free to ask.", 'name': 'Sam', 'role': 'user'}, {'content': "I'm glad to hear that the code worked correctly. If you have any more questions or need assistance in the future, feel free to reach out. Have a great day!", 'name': 'John', 'role': 'user'}, {'content': 'TERMINATE', 'role': 'assistant', 'name': 'user_proxy'}]