Spaces:
Runtime error
Runtime error
Upload 3 files
Browse filesFiles changed (3)
- app.pyAdded+201
- dependencies.pyAdded+128
- requirements.txtAdded+285
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201import cv2import streamlit as stimport tempfileimport base64import osfrom dotenv import load_dotenvfrom openai import OpenAIimport assemblyai as aaifrom moviepy.editor import *from dependencies import sign_up, fetch_users
try: users = fetch_users() emails = [] usernames = [] passwords = []
for user in users: emails.append(user['key']) usernames.append(user['username']) passwords.append(user['password'])
credentials = {'usernames': {}} for index in range(len(emails)): credentials['usernames'][usernames[index]] = {'name': emails[index], 'password': passwords[index]}
info, info1 = st.columns(2)
except: st.success('Refresh Page')
# Load environment variablesload_dotenv()aai.settings.api_key = os.getenv("ASSEMBLYAI_API_KEY")OpenAI.api_key = os.getenv("OPENAI_API_KEY")client = OpenAI() def main(): st.title('Insightly Video Content Moderation') # Video upload section uploaded_video = st.file_uploader('Upload a video', type=["mp4", "avi", "mov"]) if uploaded_video is not None: # Save the video to a temp file tfile = tempfile.NamedTemporaryFile(delete=False) tfile.write(uploaded_video.read()) video_file_path = tfile.name tfile.close()
transcriber = aai.Transcriber() transcript = transcriber.transcribe(tfile.name)
# Process the video and display frames in a grid layout base64_frames = video_to_base64_frames(video_file_path) display_frame_grid(base64_frames[::30]) # Display every 30th frame in a 3-column grid st.write("Actions:") # Header for the actions/buttons section
# Creating four columns to align the buttons col1, col2, col3, col4 = st.columns(4)
with col1: if st.button("Description"): st.session_state['description'] = generate_description(base64_frames) if 'description' not in st.session_state else st.session_state['description'] with col2: if st.button("Frame Description"): st.session_state['frame_description'] = generate_frame_description(base64_frames) if 'frame_description' not in st.session_state else st.session_state['frame_description']
with col3: if st.button("Generate Transcript"): st.session_state['transcript'] = transcript.text if 'transcript' not in st.session_state else st.session_state['transcript'] with col4: if st.button("Category of Video"): st.session_state['category'] = generate_category(base64_frames) if 'category' not in st.session_state else st.session_state['category']
# If any value exists in session state then display it if 'description' in st.session_state and st.session_state['description']: st.subheader("Video Description") st.write(st.session_state['description']) if 'frame_description' in st.session_state and st.session_state['frame_description']: st.subheader("Frame Description") st.write(st.session_state['frame_description']) if 'transcript' in st.session_state and st.session_state['transcript']: st.subheader("Video Transcript") st.write(st.session_state['transcript']) if 'category' in st.session_state and st.session_state['category']: st.subheader("Video Category") st.write(st.session_state['category'])
def video_to_base64_frames(video_file_path): # Logic to extract all frames from the video and convert them to base64 video = cv2.VideoCapture(video_file_path) base64_frames = [] while video.isOpened(): success, frame = video.read() if not success: break _, buffer = cv2.imencode('.jpg', frame) base64_frame = base64.b64encode(buffer).decode('utf-8') base64_frames.append(base64_frame) video.release() return base64_frames
##########################################Generate Video descriptiondef generate_description(base64_frames): prompt_messages = [ { "role": "user", "content": [ "1. Generate a description for this sequence of video frames in about 90 words.\ Return the following : 1. List of objects in the video 2. Any restrictive content or sensitive content and if so which frame ", *map(lambda x: {"image": x, "resize": 428}, base64_frames[0::30]), ], }, ] response = client.chat.completions.create( model="gpt-4-vision-preview", messages=prompt_messages, max_tokens=3000, ) return response.choices[0].message.content
#Generate frame descriptiondef generate_frame_description(base64_frames): prompt_messages = [ { "role": "user", "content": [ "Describe what is happening in each frame.", *map(lambda x: {"image": x, "resize": 428}, base64_frames[0::30]), ], }, ] response = client.chat.completions.create( model="gpt-4-vision-preview", messages=prompt_messages, max_tokens=3000, ) return response.choices[0].message.content
#Generate Category of Videodef generate_category(base64_frames): prompt_messages = [ { "role": "user", "content": [ "What category can this video be tagged to?", *map(lambda x: {"image": x, "resize": 428}, base64_frames[0::30]), ], }, ] response = client.chat.completions.create( model="gpt-4-vision-preview", messages=prompt_messages, max_tokens=3000, ) return response.choices[0].message.content
######################## def display_frame_grid(base64_frames): cols_per_row = 3 n_frames = len(base64_frames) for idx in range(0, n_frames, cols_per_row): cols = st.columns(cols_per_row) for col_index in range(cols_per_row): frame_idx = idx + col_index if frame_idx < n_frames: with cols[col_index]: frame = base64_frames[frame_idx] st.image(base64.b64decode(frame), caption=f'Frame {frame_idx * 30 + 1}', width=200) if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import streamlit as stimport streamlit_authenticator as stauthimport datetimeimport refrom deta import Deta
DETA_KEY = 'YOUR_DETA_KEY'
deta = Deta(DETA_KEY)
db = deta.Base('YOUR_DETA_BASE')
def insert_user(email, username, password): """ Inserts Users into the DB :param email: :param username: :param password: :return User Upon successful Creation: """ date_joined = str(datetime.datetime.now())
return db.put({'key': email, 'username': username, 'password': password, 'date_joined': date_joined})
def fetch_users(): """ Fetch Users :return Dictionary of Users: """ users = db.fetch() return users.items
def get_user_emails(): """ Fetch User Emails :return List of user emails: """ users = db.fetch() emails = [] for user in users.items: emails.append(user['key']) return emails
def get_usernames(): """ Fetch Usernames :return List of user usernames: """ users = db.fetch() usernames = [] for user in users.items: usernames.append(user['key']) return usernames
def validate_email(email): """ Check Email Validity :param email: :return True if email is valid else False: """ pattern = "^[a-zA-Z0-9-_]+@[a-zA-Z0-9]+\.[a-z]{1,3}$" #tesQQ12@gmail.com
if re.match(pattern, email): return True return False
def validate_username(username): """ Checks Validity of userName :param username: :return True if username is valid else False: """
pattern = "^[a-zA-Z0-9]*$" if re.match(pattern, username): return True return False
def sign_up(): with st.form(key='signup', clear_on_submit=True): st.subheader(':green[Sign Up]') email = st.text_input(':blue[Email]', placeholder='Enter Your Email') username = st.text_input(':blue[Username]', placeholder='Enter Your Username') password1 = st.text_input(':blue[Password]', placeholder='Enter Your Password', type='password') password2 = st.text_input(':blue[Confirm Password]', placeholder='Confirm Your Password', type='password')
if email: if validate_email(email): if email not in get_user_emails(): if validate_username(username): if username not in get_usernames(): if len(username) >= 2: if len(password1) >= 6: if password1 == password2: # Add User to DB hashed_password = stauth.Hasher([password2]).generate() insert_user(email, username, hashed_password[0]) st.success('Account created successfully!!') st.balloons() else: st.warning('Passwords Do Not Match') else: st.warning('Password is too Short') else: st.warning('Username Too short') else: st.warning('Username Already Exists')
else: st.warning('Invalid Username') else: st.warning('Email Already exists!!') else: st.warning('Invalid Email')
btn1, bt2, btn3, btn4, btn5 = st.columns(5)
with btn3: st.form_submit_button('Sign Up')
sign_up()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285absl-py==1.4.0aiofiles==23.1.0aiohttp==3.8.4aiosignal==1.3.1altair==4.2.2anyio==3.6.2appnope==0.1.3argon2-cffi==21.3.0argon2-cffi-bindings==21.2.0arrow==1.2.3asttokens==2.2.1astunparse==1.6.3async-lru==2.0.2async-timeout==4.0.2attrs==23.1.0awscli==1.27.139Babel==2.12.1backcall==0.2.0bcrypt==4.1.2beautifulsoup4==4.12.2bibtexparser==1.4.0bleach==6.0.0blinker==1.6.2botocore==1.29.139cachetools==5.3.0certifi==2023.5.7cffi==1.15.1charset-normalizer==3.1.0click==8.1.3colorama==0.4.4comm==0.1.3contourpy==1.0.7cycler==0.11.0dash==2.10.2dash-core-components==2.0.0dash-html-components==2.0.0dash-table==5.0.0dataclasses-json==0.5.8datasets==2.12.0debugpy==1.6.7decorator==5.1.1defusedxml==0.7.1deta==1.2.0dill==0.3.6distlib==0.3.6docutils==0.16entrypoints==0.4environs==9.5.0exceptiongroup==1.1.2executing==1.2.0extra-streamlit-components==0.1.60faiss-cpu==1.7.4fastapi==0.96.1fastjsonschema==2.16.3ffmpy==0.3.0filelock==3.12.0Flask==2.2.5flatbuffers==23.5.9fonttools==4.39.4fqdn==1.5.1frozenlist==1.3.3fsspec==2023.6.0gast==0.4.0gitdb==4.0.10GitPython==3.1.31google-auth==2.18.1google-auth-oauthlib==1.0.0google-images-download @ git+https://github.com/Joeclinton1/google-images-download.git@e91e6a38ad654877f59edc7894822f5319d75df1google-pasta==0.2.0gradio==3.34.0gradio_client==0.2.6greenlet==2.0.2grpcio==1.53.0grpcio-tools==1.53.0h11==0.14.0h5py==3.8.0httpcore==0.17.2httpx==0.24.1huggingface-hub==0.15.1idna==3.4importlib-metadata==6.6.0install==1.3.5ipykernel==6.23.1ipypublish==0.10.12ipython==8.13.2ipython-genutils==0.2.0ipywidgets==8.0.6isoduration==20.11.0itsdangerous==2.1.2jaraco.classes==3.2.3jax==0.4.10jedi==0.18.2Jinja2==3.1.2jmespath==1.0.1json5==0.9.14jsonextended==0.7.11jsonpointer==2.3jsonschema==4.17.3jupyter==1.0.0jupyter-console==6.6.3jupyter-events==0.6.3jupyter-lsp==2.2.0jupyter_client==8.2.0jupyter_core==5.3.0jupyter_server==2.5.0jupyter_server_terminals==0.4.4jupyterlab==4.0.2jupyterlab-pygments==0.2.2jupyterlab-widgets==3.0.7jupyterlab_server==2.23.0jupytext==1.15.0keras==2.12.0keyring==23.13.1kiwisolver==1.4.4lab==7.3langchain==0.0.184libclang==16.0.0linkify-it-py==2.0.2Markdown==3.4.3markdown-it-py==2.2.0MarkupSafe==2.1.2marshmallow==3.19.0marshmallow-enum==1.5.1matplotlib==3.7.1matplotlib-inline==0.1.6mdit-py-plugins==0.3.3mdurl==0.1.2mistune==2.0.5ml-dtypes==0.1.0mmh3==4.0.0more-itertools==9.1.0mpmath==1.3.0multidict==6.0.4multiprocess==0.70.14mypy-extensions==1.0.0nbclassic==1.0.0nbclient==0.7.4nbconvert==7.4.0nbformat==5.8.0nest-asyncio==1.5.6networkx==3.1notebook==6.5.4notebook_shim==0.2.3numexpr==2.8.4numpy==1.23.5oauthlib==3.2.2openai==0.27.6openapi-schema-pydantic==1.2.4opencv-python==4.7.0.72opt-einsum==3.3.0ordered-set==4.1.0orjson==3.9.1outcome==1.2.0packaging==23.1pandas==2.0.2pandocfilters==1.5.0panflute==2.3.0parso==0.8.3pathlib2==2.3.7.post1pexpect==4.8.0pickleshare==0.7.5Pillow==9.5.0pkginfo==1.9.6platformdirs==3.5.1plotly==5.15.0progressbar==2.5prometheus-client==0.16.0prompt-toolkit==3.0.38protobuf==3.20.3psutil==5.9.5ptyprocess==0.7.0pure-eval==0.2.2pyarrow==12.0.0pyasn1==0.5.0pyasn1-modules==0.3.0pycairo @ file:///private/tmp/py3cairo-20231022-6916-1lfc5vx/pycairo-1.25.1pycparser==2.21pydantic==1.10.9pydeck==0.8.1b0pydub==0.25.1Pygments==2.15.1PyGObject==3.46.0pygoogle-image==1.0.0PyJWT==2.8.0pymilvus==2.2.5Pympler==1.0.1pyparsing==3.0.9PyPDF2==3.0.1pyrsistent==0.19.3PySocks==1.7.1python-dateutil==2.8.2python-dotenv==1.0.0python-json-logger==2.0.7python-magic-bin==0.4.14python-multipart==0.0.6pytz==2023.3pytz-deprecation-shim==0.1.0.post0PyYAML==5.4.1pyzmq==25.0.2qtconsole==5.4.3QtPy==2.3.1readme-renderer==37.3regex==2023.6.3reportlab==4.0.4requests==2.30.0requests-oauthlib==1.3.1requests-toolbelt==1.0.0responses==0.18.0rfc3339-validator==0.1.4rfc3986==2.0.0rfc3986-validator==0.1.1rich==13.4.1rsa==4.7.2ruamel.yaml==0.17.32ruamel.yaml.clib==0.2.7s3transfer==0.6.1safetensors==0.3.1scipy==1.10.1selenium==4.10.0semantic-version==2.10.0Send2Trash==1.8.2sentencepiece==0.1.99simple-image-download==0.5simplejson==3.19.1six==1.16.0smmap==5.0.0sniffio==1.3.0sortedcontainers==2.4.0soupsieve==2.4.1SQLAlchemy==2.0.16stack-data==0.6.2starlette==0.27.0streamlit==1.22.0streamlit-authenticator==0.2.3sympy==1.12tabulate==0.9.0tenacity==8.2.2tensorboard==2.12.3tensorboard-data-server==0.7.0tensorflow==2.12.0tensorflow-estimator==2.12.0tensorflow-io-gcs-filesystem==0.32.0termcolor==2.3.0terminado==0.17.1tiktoken==0.4.0tinycss2==1.2.1tokenizers==0.13.3toml==0.10.2toolz==0.12.0torch==2.0.1torchvision==0.15.2tornado==6.3.2towhee==1.1.0towhee.models==1.1.0tqdm==4.65.0traitlets==5.9.0transformers==4.30.1trio==0.22.2trio-websocket==0.10.3tweepy==4.14.0twine==4.0.2txt2tags==3.8typing-inspect==0.9.0typing_extensions==4.5.0tzdata==2023.3tzlocal==4.3uc-micro-py==1.0.2ujson==5.7.0uri-template==1.2.0urllib3==1.26.15uvicorn==0.22.0validators==0.20.0virtualenv==20.23.0wcwidth==0.2.6webcolors==1.13webencodings==0.5.1websocket-client==1.5.1websockets==11.0.3Werkzeug==2.2.3widgetsnbextension==4.0.7wrapt==1.14.1wsproto==1.2.0xxhash==3.2.0yarl==1.9.2zipp==3.15.0app.pyAdded+201
dependencies.pyAdded+128
requirements.txtAdded+285