Complete implementation of multi-process Video AI Analysis Tool

- Multi-process architecture: web, backend, analysis/training workers
- SQLite database for persistent configuration and system prompts
- Configurable CUDA/ROCm backends with command line override
- TCP socket-based inter-process communication
- Web interface with comprehensive configuration management
- GPLv3 licensing with copyright notices on all files
- Complete documentation: README, architecture docs, changelog
- Build and deployment scripts for different GPU backends
- Git repository setup with .gitignore for build artifacts
parents
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
*.manifest
*.spec
# Virtual environments
venv/
venv-*/
env/
ENV/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Logs
*.log
logs/
# Database
*.db
*.sqlite
*.sqlite3
# Temporary files
*.tmp
*.temp
temp/
tmp/
# Build artifacts
vidai-backend
vidai-web
vidai-analysis-*
vidai-training-*
# Result files
/tmp/vidai_results/
# Config (but keep structure)
/home/*/.config/vidai/
~/.config/vidai/
\ No newline at end of file
# Changelog
All notable changes to the Video AI Analysis Tool will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- Multi-process architecture with separate web, backend, and worker processes
- Configurable CUDA/ROCm backend selection for analysis and training
- TCP socket-based inter-process communication
- Web-based configuration interface
- Self-contained build system with PyInstaller
- Comprehensive documentation and README
- GPLv3 licensing and copyright notices
### Changed
- Refactored monolithic Flask app into distributed processes
- Replaced direct analysis calls with message-passing architecture
- Updated build scripts to generate multiple executables
- Improved error handling and process management
### Technical Details
- Implemented socket-based communication protocol
- Added configuration management system
- Created worker registration and routing system
- Added file-based result storage for reliability
- Implemented graceful shutdown and process monitoring
## [0.1.0] - 2024-10-05
### Added
- Initial release of Video AI Analysis Tool
- Web interface for image/video analysis
- Qwen2.5-VL model integration
- Frame extraction and video processing
- Model training capabilities
- CUDA/ROCm support via separate requirements
- Basic build and setup scripts
### Features
- Upload and analyze images and videos
- Automatic frame extraction from videos
- AI-powered scene description and summarization
- Fine-tune models on custom datasets
- GPU memory monitoring
- Progress tracking and cancellation
### Infrastructure
- Flask web framework
- PyTorch with CUDA/ROCm support
- Transformers library integration
- OpenCV for video processing
- PyInstaller for executable builds
\ No newline at end of file
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a way requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or indirectly liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an object code work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in effect. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the public at large.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under subsection 6 must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, copyrights, or related rights (included, but not limited to,
patent and trademark licenses); or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise is void, and will
automatically terminate your rights under this License (including any
patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, in which
the contributor contributes, of making, using, or selling its
contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor
version. For purposes of this definition, "control" includes the right
to grant patent sublicenses in a manner consistent with the requirements
of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an express agreement or commitment not to
enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, modify, or propagate
the covered work, then the patent license you grant is automatically
extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibiting the exercise of, or being
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the patent licensing business, and in which you grant, or agree to
grant, a patent license to any third party that conveys a covered work,
and the patent license you grant or agree to grant does not include at
least the following within its scope: the right to make, use, sell,
offer for sale, import and otherwise run, modify and propagate the
contents of the covered work.
The requirement in the previous paragraph also applies to combination
in the same manner with the same scope.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the work, you cannot convey it.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you can choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional permissions are granted by the fact
that you choose to follow a newer version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE USE OF THE PROGRAM IS AT YOUR OWN RISK. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, except as expressly provided in this License.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you can redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for interactive programs, you would use a menu to
display the appropriate commands.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more details on this and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
\ No newline at end of file
# Video AI Analysis Tool
A multi-process web-based tool for analyzing images and videos using AI models. Supports frame extraction, activity detection, video segmentation, and model training with configurable CUDA/ROCm backends.
## Features
- **Web Interface**: User-friendly web UI for uploading and analyzing media
- **AI Analysis**: Powered by Qwen2.5-VL models for image/video understanding
- **Multi-Process Architecture**: Separate processes for web, backend, and workers
- **Backend Selection**: Choose between CUDA and ROCm for analysis/training
- **Video Processing**: Automatic frame extraction and summarization
- **Model Training**: Fine-tune models on custom datasets
- **Configuration Management**: SQLite database for persistent settings and system prompts
- **Self-Contained**: No external dependencies beyond Python and system libraries
## Architecture
The application consists of four main components:
1. **Web Interface Process**: Flask-based UI server
2. **Backend Process**: Request routing and worker management
3. **Analysis Workers**: CUDA and ROCm variants for media analysis
4. **Training Workers**: CUDA and ROCm variants for model training
Communication between processes uses TCP sockets for reliability and self-containment.
## Requirements
- Python 3.8+
- PyTorch (CUDA or ROCm)
- Flask
- Transformers
- OpenCV
- Other dependencies listed in requirements files
## Installation
1. Clone the repository:
```bash
git clone <repository-url>
cd videotest
```
2. Set up virtual environment:
```bash
./setup.sh cuda # or ./setup.sh rocm
source venv-cuda/bin/activate # or venv-rocm
```
3. Build executables (optional):
```bash
./build.sh cuda # or ./build.sh rocm
```
## Usage
### Command Line Options
All command line options can be configured in the database and overridden at runtime:
```bash
python vidai.py [options]
```
Options:
- `--model MODEL`: Default model path (default: Qwen/Qwen2.5-VL-7B-Instruct)
- `--dir DIR`: Allowed directory for local file access
- `--optimize`: Optimize frame extraction (resize to 640px width)
- `--ffmpeg`: Force use of ffmpeg for frame extraction
- `--flash`: Enable Flash Attention 2
- `--analysis-backend {cuda,rocm}`: Backend for analysis
- `--training-backend {cuda,rocm}`: Backend for training
- `--host HOST`: Host to bind server to (default: 0.0.0.0)
- `--port PORT`: Port to bind server to (default: 5000)
- `--debug`: Enable debug mode
Command line options override database settings and are saved for future runs.
### Development Mode
1. Start all processes:
```bash
./start.sh cuda # or ./start.sh rocm
# Or run directly:
python vidai.py --analysis-backend cuda
```
2. Open browser to `http://localhost:5000`
### Production Mode
Use the built executables from `dist/` directory.
## Configuration
- Access the configuration page at `/config` in the web interface
- Select preferred backend (CUDA/ROCm) for analysis and training
- Configure system prompts, models, and processing options
- All settings are saved to SQLite database at `~/.config/vidai/vidai.db`
- Command line options override and update database settings
## API
The backend communicates via TCP sockets:
- Web interface: localhost:5001
- Workers: localhost:5002
Message format: JSON with `msg_type`, `msg_id`, and `data` fields.
## Development
### Project Structure
```
videotest/
├── vidai/ # Main package
│ ├── __init__.py
│ ├── backend.py # Backend process
│ ├── web.py # Web interface process
│ ├── worker_analysis.py # Analysis worker
│ ├── worker_training.py # Training worker
│ ├── comm.py # Communication utilities
│ └── config.py # Configuration management
├── templates/ # Flask templates
├── static/ # Static files
├── requirements*.txt # Dependencies
├── build.sh # Build script
├── start.sh # Startup script
├── setup.sh # Setup script
├── clean.sh # Clean script
├── LICENSE # GPLv3 license
└── README.md # This file
```
### Adding New Features
1. Define message types in `comm.py`
2. Implement handlers in backend and workers
3. Update web interface routes
4. Add configuration options if needed
## License
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
See [LICENSE](LICENSE) for details.
Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make changes
4. Test thoroughly
5. Submit a pull request
## Support
For issues and questions, please open a GitHub issue or contact the maintainer.
\ No newline at end of file
#!/bin/bash
# Video AI Build Script
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Build script for Video AI Analysis Tool
# Creates self-contained executables for each component using PyInstaller
TARGET=${1:-cuda} # Default to cuda
echo "Building Video AI Analysis Tool for $TARGET..."
# Check if pyinstaller is installed
if ! command -v pyinstaller &> /dev/null; then
echo "PyInstaller not found. Installing..."
pip install pyinstaller
fi
# Build backend
pyinstaller --onefile \
--name vidai-backend \
--hidden-import torch \
--hidden-import transformers \
vidai/backend.py
# Build web interface
pyinstaller --onefile \
--name vidai-web \
--add-data "templates:templates" \
--add-data "static:static" \
--hidden-import flask \
vidai/web.py
# Build analysis worker
pyinstaller --onefile \
--name vidai-analysis-$TARGET \
--hidden-import torch \
--hidden-import transformers \
--hidden-import cv2 \
vidai/worker_analysis.py
# Build training worker
pyinstaller --onefile \
--name vidai-training-$TARGET \
--hidden-import torch \
--hidden-import transformers \
vidai/worker_training.py
echo "Build complete for $TARGET!"
echo "Executables created in dist/:"
echo " - vidai-backend"
echo " - vidai-web"
echo " - vidai-analysis-$TARGET"
echo " - vidai-training-$TARGET"
\ No newline at end of file
#!/bin/bash
# Video AI Clean Script
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Clean script for Video AI Analysis Tool
# Removes PyInstaller build artifacts
echo "Cleaning build artifacts..."
# Remove PyInstaller directories
if [ -d "dist" ]; then
rm -rf dist
echo "Removed dist/ directory"
fi
if [ -d "build" ]; then
rm -rf build
echo "Removed build/ directory"
fi
# Remove .spec file
if [ -f "vidai.spec" ]; then
rm vidai.spec
echo "Removed vidai.spec"
fi
# Remove virtual environments
for venv in venv venv-cpu venv-cuda venv-rocm; do
if [ -d "$venv" ]; then
rm -rf "$venv"
echo "Removed $venv/ directory"
fi
done
# Remove __pycache__ directories
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
echo "Removed __pycache__ directories"
echo "Clean complete!"
\ No newline at end of file
# Architecture Documentation
## Overview
The Video AI Analysis Tool is designed as a multi-process application to provide scalability, fault isolation, and flexible backend selection for GPU acceleration.
## Process Architecture
### Components
1. **Web Interface Process** (`vidai/web.py`)
- Flask-based HTTP server
- Serves the user interface
- Communicates with backend via TCP socket (port 5001)
- Handles file uploads and result polling
2. **Backend Process** (`vidai/backend.py`)
- Central message router
- Manages worker registration and task distribution
- Listens on two ports:
- 5001: Web interface communication
- 5002: Worker communication
- Routes requests based on configured backends
3. **Analysis Workers** (`vidai/worker_analysis.py`)
- CUDA variant: Processes analysis requests using CUDA acceleration
- ROCm variant: Processes analysis requests using ROCm acceleration
- Connect to backend on port 5002
- Handle image/video analysis using Qwen2.5-VL models
4. **Training Workers** (`vidai/worker_training.py`)
- CUDA variant: Handles model training with CUDA
- ROCm variant: Handles model training with ROCm
- Connect to backend on port 5002
- Execute training scripts with appropriate GPU backend
### Communication Protocol
All inter-process communication uses TCP sockets with JSON messages:
```json
{
"msg_type": "analyze_request",
"msg_id": "uuid-string",
"data": {
"model_path": "Qwen/Qwen2.5-VL-7B-Instruct",
"prompt": "Describe this image",
"local_path": "/path/to/media",
"interval": 10
}
}
```
#### Message Types
- `analyze_request`: Web to backend, analysis job
- `train_request`: Web to backend, training job
- `config_update`: Web to backend, update configuration
- `get_config`: Web to backend, retrieve current config
- `register`: Worker to backend, register worker type
- `analyze_response`: Worker to backend, analysis result
- `train_response`: Worker to backend, training result
- `config_response`: Backend to web, configuration data
### Configuration Management
- Stored in `~/.config/vidai/config.json`
- Managed by `vidai/config.py`
- Allows selection of CUDA/ROCm for analysis and training independently
### Data Flow
1. User uploads media via web interface
2. Web process sends request to backend
3. Backend routes to appropriate worker based on config
4. Worker processes request and sends result back
5. Backend forwards result to web process
6. Web process displays result to user
### Error Handling
- Socket timeouts and reconnections
- Worker registration and health checks
- Graceful degradation when workers unavailable
- File-based result storage for reliability
### Security Considerations
- Local-only TCP sockets (localhost)
- No authentication (single-user assumption)
- File system access restricted to configured directories
- Input validation on all message data
## Deployment
### Development
Use `start.sh` to launch all processes manually for development and debugging.
### Production
Build executables with `build.sh` and deploy the resulting binaries from `dist/`.
### Scaling
- Multiple worker instances can be started for load balancing
- Backend can distribute requests across available workers
- Web interface can be load balanced independently
## Future Enhancements
- Message queue system (Redis/RabbitMQ) for better scalability
- Authentication and multi-user support
- REST API for programmatic access
- Containerization with Docker
- Monitoring and metrics collection
\ No newline at end of file
Flask>=2.0.0
torch>=2.0.0+cu118 --index-url https://download.pytorch.org/whl/cu118
transformers>=4.30.0
opencv-python>=4.5.0
psutil>=5.8.0
pynvml>=11.0.0
flash-attn>=2.0.0
pyinstaller>=5.0.0
\ No newline at end of file
Flask>=2.0.0
torch>=2.0.0+rocm5.6 --index-url https://download.pytorch.org/whl/rocm5.6
transformers>=4.30.0
opencv-python>=4.5.0
psutil>=5.8.0
pynvml>=11.0.0
pyinstaller>=5.0.0
\ No newline at end of file
Flask>=2.0.0
torch>=2.0.0
transformers>=4.30.0
opencv-python>=4.5.0
psutil>=5.8.0
pynvml>=11.0.0
flash-attn>=2.0.0
pyinstaller>=5.0.0
\ No newline at end of file
#!/bin/bash
# Video AI Setup Script
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Setup script for Video AI Analysis Tool
# Creates a virtual environment and installs dependencies
# Parse arguments
TARGET="cpu"
if [ "$1" = "cuda" ]; then
TARGET="cuda"
elif [ "$1" = "rocm" ]; then
TARGET="rocm"
fi
echo "Setting up Video AI Analysis Tool for $TARGET..."
# Create virtual environment
if [ ! -d "venv-$TARGET" ]; then
python3 -m venv venv-$TARGET
echo "Created virtual environment in venv-$TARGET/"
else
echo "Virtual environment venv-$TARGET already exists"
fi
# Activate virtual environment
source venv-$TARGET/bin/activate
# Upgrade pip
pip install --upgrade pip
# Install requirements based on target
REQ_FILE="requirements.txt"
if [ "$TARGET" = "cuda" ] && [ -f "requirements-cuda.txt" ]; then
REQ_FILE="requirements-cuda.txt"
elif [ "$TARGET" = "rocm" ] && [ -f "requirements-rocm.txt" ]; then
REQ_FILE="requirements-rocm.txt"
fi
if [ -f "$REQ_FILE" ]; then
pip install -r $REQ_FILE
echo "Installed dependencies from $REQ_FILE"
else
echo "$REQ_FILE not found"
exit 1
fi
echo "Setup complete for $TARGET!"
echo "To activate the environment: source venv-$TARGET/bin/activate"
echo "To run the application: python vidai.py --help"
\ No newline at end of file
#!/bin/bash
# Video AI Startup Script
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Startup script for Video AI Analysis Tool
# Launches all processes in the correct order
TARGET=${1:-cuda} # Default to cuda
echo "Starting Video AI Analysis Tool for $TARGET..."
# Create result directory
mkdir -p /tmp/vidai_results
# Start backend
echo "Starting backend..."
python vidai/backend.py &
BACKEND_PID=$!
sleep 2
# Start workers
echo "Starting analysis worker..."
python vidai/worker_analysis.py $TARGET &
ANALYSIS_PID=$!
echo "Starting training worker..."
python vidai/worker_training.py $TARGET &
TRAINING_PID=$!
sleep 2
# Start web interface
echo "Starting web interface..."
python vidai/web.py &
WEB_PID=$!
echo "All processes started!"
echo "Web interface available at http://localhost:5000"
echo "Press Ctrl+C to stop all processes"
# Wait for interrupt
trap "echo 'Stopping all processes...'; kill $WEB_PID $TRAINING_PID $ANALYSIS_PID $BACKEND_PID; exit" INT
wait
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<title>VideoModel AI</title>
<style>
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; display: flex; justify-content: center; align-items: flex-start; }
.main { flex: 1; max-width: 800px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-right: 20px; }
.sidebar { width: 300px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
h1 { color: #333; text-align: center; }
nav { text-align: center; margin-bottom: 20px; }
nav a { margin: 0 10px; text-decoration: none; color: #007bff; }
form { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; }
input[type="text"], input[type="file"], textarea { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; }
input[type="submit"] { background: #007bff; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }
input[type="submit"]:hover { background: #0056b3; }
.result { background: #e9ecef; padding: 10px; border-radius: 4px; }
.stats { font-size: 14px; }
</style>
</head>
<body>
<div class="main">
<h1>VideoModel AI Web Interface</h1>
<nav>
<a href="/">Analysis</a> | <a href="/train">Training</a>
</nav>
<h2>Analyze Image/Video</h2>
<form method="post" enctype="multipart/form-data">
<label>Model Path: <input type="text" name="model_path" value="{{ model_path_default }}"></label>
<p><a href="/system">Edit System Prompt</a></p>
<label>Upload File: <input type="file" name="file" accept="image/*,video/*" id="fileInput"></label>
<progress id="uploadProgress" value="0" max="100" style="display:none; width:100%;"></progress>
<div id="progressText"></div>
{% if allowed_dir %}
<label>Or Local Path: <input type="text" name="local_path" id="local_path"> <button type="button" onclick="openFileBrowser()">Browse</button></label>
{% endif %}
<label>Prompt: <textarea name="prompt" rows="5" cols="80">Describe this image.</textarea></label>
<input type="submit" value="Analyze">
<button type="button" onclick="cancelAnalysis()">Cancel Analysis</button>
</form>
<div class="result" id="result_div" style="display:none;"></div>
{% if result %}
<div class="result">
<h3>Result:</h3>
<p>{{ result }}</p>
</div>
{% endif %}
</div>
<div class="sidebar">
<div id="stats" class="stats">Loading stats...</div>
</div>
<script>
function openFileBrowser() {
window.open('/files', 'filebrowser', 'width=600,height=400');
}
async function updateStats() {
try {
const response = await fetch('/stats');
const data = await response.json();
let html = '<h3>GPU Stats</h3>';
html += `<p style="color: ${data.status === 'Idle' ? 'green' : 'orange'};">Status: ${data.status}</p>`;
if (data.elapsed > 0) {
html += `<p>Elapsed: ${data.elapsed.toFixed(1)}s</p>`;
}
if (data.gpu_count > 0) {
data.gpus.forEach((gpu, i) => {
let memPercent = (gpu.memory_used / gpu.memory_total * 100).toFixed(1);
html += `<p>GPU ${i}: ${gpu.name}<br>Memory: <progress value="${gpu.memory_used}" max="${gpu.memory_total}"></progress> ${gpu.memory_used.toFixed(2)} / ${gpu.memory_total.toFixed(2)} GB (${memPercent}%)<br>Utilization: ${gpu.utilization}%</p>`;
});
} else {
html += '<p>No GPUs detected</p>';
}
html += `<p>CPU: ${data.cpu_percent.toFixed(1)}%</p>`;
html += `<p>RAM: ${data.ram_used.toFixed(2)} / ${data.ram_total.toFixed(2)} GB</p>`;
document.getElementById('stats').innerHTML = html;
if (data.result) {
document.getElementById('result_div').innerHTML = '<h3>Result:</h3><p>' + data.result + '</p>';
document.getElementById('result_div').style.display = 'block';
}
} catch (e) {
document.getElementById('stats').innerHTML = '<p>Error loading stats</p>';
}
}
setInterval(updateStats, 5000);
window.onload = updateStats;
function cancelAnalysis() {
fetch('/cancel', {method: 'POST'}).then(() => updateStats());
}
// Upload progress with chunked upload
const form = document.querySelector('form');
if (form) {
form.addEventListener('submit', async function(e) {
e.preventDefault();
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
// Submit form normally if no file
const formData = new FormData(this);
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', function() {
window.location.reload();
});
xhr.open('POST', '/');
xhr.send(formData);
return;
}
const chunkSize = 1024 * 1024; // 1MB
const totalChunks = Math.ceil(file.size / chunkSize);
const uploadId = Date.now().toString();
const concurrency = 3;
let chunksSent = 0;
async function sendChunk(index) {
const start = index * chunkSize;
const end = Math.min(start + chunkSize, file.size);
const chunk = file.slice(start, end);
const formData = new FormData();
formData.append('chunk', chunk);
formData.append('chunk_index', index);
formData.append('total_chunks', totalChunks);
formData.append('file_name', file.name);
formData.append('upload_id', uploadId);
return new Promise((resolve) => {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
const percent = ((chunksSent * chunkSize + e.loaded) / file.size) * 100;
document.getElementById('uploadProgress').value = percent;
document.getElementById('uploadProgress').style.display = 'block';
const speed = (chunksSent * chunkSize + e.loaded) / ((Date.now() - startTime) / 1000);
const remaining = (file.size - (chunksSent * chunkSize + e.loaded)) / speed;
document.getElementById('progressText').innerText = `Uploaded ${((chunksSent * chunkSize + e.loaded) / 1024 / 1024).toFixed(2)} MB of ${(file.size / 1024 / 1024).toFixed(2)} MB (${percent.toFixed(1)}%) - Speed: ${(speed / 1024 / 1024).toFixed(2)} MB/s - ETA: ${Math.round(remaining)}s`;
}
});
xhr.addEventListener('load', function() {
chunksSent++;
resolve();
});
xhr.open('POST', '/upload_chunk');
xhr.send(formData);
});
}
const startTime = Date.now();
for (let i = 0; i < totalChunks; i += concurrency) {
const promises = [];
for (let j = 0; j < concurrency && i + j < totalChunks; j++) {
promises.push(sendChunk(i + j));
}
await Promise.all(promises);
}
// All chunks sent, submit form
const formData2 = new FormData(form);
formData2.append('upload_id', uploadId);
formData2.append('file_name', file.name);
const xhr2 = new XMLHttpRequest();
xhr2.addEventListener('load', function() {
window.location.reload();
});
xhr2.open('POST', '/');
xhr2.send(formData2);
});
}
</script>
</body>
</html>
\ No newline at end of file
#!/usr/bin/env python3
# Video AI Analysis Tool
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Video AI Analysis Tool
A web-based tool for analyzing images and videos using AI models.
Supports frame extraction, activity detection, and video segmentation.
"""
import argparse
import sys
import os
import subprocess
# Add current directory to path for vidai module
sys.path.insert(0, os.path.dirname(__file__))
from vidai.config import (
get_config, set_config, get_default_model, set_default_model,
get_analysis_backend, set_analysis_backend, get_training_backend, set_training_backend,
get_optimize, set_optimize, get_ffmpeg, set_ffmpeg, get_flash, set_flash,
get_host, set_host, get_port, set_port, get_debug, set_debug, get_allowed_dir, set_allowed_dir
)
def main():
parser = argparse.ArgumentParser(
description="Video AI Analysis Tool - Web interface for AI-powered media analysis",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python vidai.py --model Qwen/Qwen2.5-VL-7B-Instruct
python vidai.py --dir /path/to/media --optimize
python vidai.py --flash --ffmpeg
python vidai.py --analysis-backend rocm
"""
)
# Read defaults from config
default_model = get_default_model()
default_analysis_backend = get_analysis_backend()
default_training_backend = get_training_backend()
default_optimize = get_optimize()
default_ffmpeg = get_ffmpeg()
default_flash = get_flash()
default_host = get_host()
default_port = get_port()
default_debug = get_debug()
parser.add_argument(
'--model',
default=default_model,
help=f'Default model path or HuggingFace model name (default: {default_model})'
)
parser.add_argument(
'--dir',
default=get_config('allowed_dir', ''),
help='Allowed directory for local file access'
)
parser.add_argument(
'--optimize',
action='store_true',
default=default_optimize,
help='Optimize frame extraction (resize to 640px width)'
)
parser.add_argument(
'--ffmpeg',
action='store_true',
default=default_ffmpeg,
help='Force use of ffmpeg for frame extraction instead of OpenCV'
)
parser.add_argument(
'--flash',
action='store_true',
default=default_flash,
help='Enable Flash Attention 2 for faster inference (requires flash-attn package)'
)
parser.add_argument(
'--analysis-backend',
choices=['cuda', 'rocm'],
default=default_analysis_backend,
help=f'Backend for analysis (default: {default_analysis_backend})'
)
parser.add_argument(
'--training-backend',
choices=['cuda', 'rocm'],
default=default_training_backend,
help=f'Backend for training (default: {default_training_backend})'
)
parser.add_argument(
'--host',
default=default_host,
help=f'Host to bind the server to (default: {default_host})'
)
parser.add_argument(
'--port',
type=int,
default=default_port,
help=f'Port to bind the server to (default: {default_port})'
)
parser.add_argument(
'--debug',
action='store_true',
default=default_debug,
help='Enable debug mode'
)
args = parser.parse_args()
# Update config with command line values
set_default_model(args.model)
set_allowed_dir(args.dir)
set_optimize(args.optimize)
set_ffmpeg(args.ffmpeg)
set_flash(args.flash)
set_analysis_backend(args.analysis_backend)
set_training_backend(args.training_backend)
set_host(args.host)
set_port(args.port)
set_debug(args.debug)
print("Starting Video AI Analysis Tool...")
print(f"Server will be available at http://{args.host}:{args.port}")
print("Press Ctrl+C to stop")
# Start backend process
backend_cmd = [sys.executable, '-m', 'vidai.backend']
backend_proc = subprocess.Popen(backend_cmd)
# Start web process
web_cmd = [sys.executable, '-m', 'vidai.web']
web_proc = subprocess.Popen(web_cmd)
try:
# Wait for processes
backend_proc.wait()
web_proc.wait()
except KeyboardInterrupt:
print("Shutting down...")
backend_proc.terminate()
web_proc.terminate()
backend_proc.wait()
web_proc.wait()
if __name__ == "__main__":
main()
\ No newline at end of file
# Video AI Package
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Video AI Analysis Tool Package
"""
\ No newline at end of file
# Video AI Backend Process
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Backend process for Video AI.
Manages request routing between web interface and worker processes.
"""
import time
import threading
from .comm import SocketServer, Message
from .config import get_analysis_backend, get_training_backend, set_analysis_backend, set_training_backend
worker_sockets = {} # type: dict
def handle_web_message(message: Message) -> Message:
"""Handle messages from web interface."""
if message.msg_type == 'analyze_request':
backend = get_analysis_backend()
worker_key = f'analysis_{backend}'
if worker_key in worker_sockets:
# Forward to worker
worker_sockets[worker_key].sendall(
f'{{"msg_type": "{message.msg_type}", "msg_id": "{message.msg_id}", "data": {message.data}}}\n'.encode('utf-8')
)
return None # No immediate response
else:
return Message('error', message.msg_id, {'error': f'Worker {worker_key} not available'})
elif message.msg_type == 'train_request':
backend = get_training_backend()
worker_key = f'training_{backend}'
if worker_key in worker_sockets:
worker_sockets[worker_key].sendall(
f'{{"msg_type": "{message.msg_type}", "msg_id": "{message.msg_id}", "data": {message.data}}}\n'.encode('utf-8')
)
return None
else:
return Message('error', message.msg_id, {'error': f'Worker {worker_key} not available'})
elif message.msg_type == 'config_update':
data = message.data
if 'analysis_backend' in data:
set_analysis_backend(data['analysis_backend'])
if 'training_backend' in data:
set_training_backend(data['training_backend'])
return Message('config_response', message.msg_id, {'status': 'updated'})
elif message.msg_type == 'get_config':
return Message('config_response', message.msg_id, {
'analysis_backend': get_analysis_backend(),
'training_backend': get_training_backend()
})
return Message('error', message.msg_id, {'error': 'Unknown message type'})
def handle_worker_message(message: Message, client_sock) -> None:
"""Handle messages from workers."""
if message.msg_type == 'register':
worker_type = message.data.get('type')
if worker_type:
worker_sockets[worker_type] = client_sock
print(f"Worker {worker_type} registered")
elif message.msg_type in ['analyze_response', 'train_response']:
# Forward to web - but since web is connected via different server, need to store or something
# For simplicity, assume web polls for results, but since socket, perhaps have a pending responses dict
# This is getting complex. Perhaps use a shared dict or file for results.
# To keep simple, since web is Flask, it can have a global dict for results, but since separate process, hard.
# Perhaps the backend sends to web via its own connection, but web connects per request.
# For responses, backend can store in a file or database, and web reads from there.
# But to keep self-contained, use a simple JSON file for pending results.
# Web sends request with id, backend processes, stores result in file with id, web polls for result file.
# Yes, that's ad-hoc.
# So, for responses, write to a file.
import os
result_dir = '/tmp/vidai_results'
os.makedirs(result_dir, exist_ok=True)
with open(os.path.join(result_dir, f"{message.msg_id}.json"), 'w') as f:
import json
json.dump({
'msg_type': message.msg_type,
'msg_id': message.msg_id,
'data': message.data
}, f)
def worker_message_handler(message: Message, client_sock) -> None:
"""Handler for worker messages."""
handle_worker_message(message, client_sock)
def backend_process() -> None:
"""Main backend process loop."""
print("Starting Video AI Backend...")
# Start web server on port 5001
web_server = SocketServer(port=5001)
web_server.start(handle_web_message)
# Start worker server on port 5002
worker_server = SocketServer(port=5002)
worker_server.start(worker_message_handler)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Backend shutting down...")
web_server.stop()
worker_server.stop()
if __name__ == "__main__":
backend_process()
\ No newline at end of file
# Video AI Communication Module
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Communication protocol for Video AI multi-process architecture.
Uses sockets for inter-process communication.
"""
import socket
import json
import threading
import time
from typing import Dict, Any, Optional
from dataclasses import dataclass
@dataclass
class Message:
"""Message structure for inter-process communication."""
msg_type: str
msg_id: str
data: Dict[str, Any]
class SocketCommunicator:
"""Handles socket-based communication."""
def __init__(self, host: str = 'localhost', port: int = 5001):
self.host = host
self.port = port
self.sock: Optional[socket.socket] = None
def connect(self) -> None:
"""Connect to the server."""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.host, self.port))
def send_message(self, message: Message) -> None:
"""Send a message."""
if self.sock:
data = json.dumps({
'msg_type': message.msg_type,
'msg_id': message.msg_id,
'data': message.data
}).encode('utf-8')
self.sock.sendall(data + b'\n')
def receive_message(self) -> Optional[Message]:
"""Receive a message."""
if self.sock:
try:
data = self.sock.recv(4096)
if data:
msg_data = json.loads(data.decode('utf-8').strip())
return Message(
msg_type=msg_data['msg_type'],
msg_id=msg_data['msg_id'],
data=msg_data['data']
)
except:
pass
return None
def close(self) -> None:
"""Close the connection."""
if self.sock:
self.sock.close()
class SocketServer:
"""Simple socket server for handling connections."""
def __init__(self, host: str = 'localhost', port: int = 5001):
self.host = host
self.port = port
self.server_sock: Optional[socket.socket] = None
self.running = False
self.message_handler = None
def start(self, message_handler) -> None:
"""Start the server."""
self.message_handler = message_handler
self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_sock.bind((self.host, self.port))
self.server_sock.listen(5)
self.running = True
threading.Thread(target=self._accept_loop, daemon=True).start()
def _accept_loop(self) -> None:
"""Accept incoming connections."""
while self.running:
try:
client_sock, addr = self.server_sock.accept()
threading.Thread(target=self._handle_client, args=(client_sock,), daemon=True).start()
except:
break
def _handle_client(self, client_sock: socket.socket) -> None:
"""Handle a client connection."""
try:
while self.running:
data = client_sock.recv(4096)
if not data:
break
messages = data.decode('utf-8').split('\n')
for msg_str in messages:
if msg_str.strip():
try:
msg_data = json.loads(msg_str)
message = Message(
msg_type=msg_data['msg_type'],
msg_id=msg_data['msg_id'],
data=msg_data['data']
)
response = self.message_handler(message)
if response:
resp_data = json.dumps({
'msg_type': response.msg_type,
'msg_id': response.msg_id,
'data': response.data
}).encode('utf-8')
client_sock.sendall(resp_data + b'\n')
except json.JSONDecodeError:
pass
except:
pass
finally:
client_sock.close()
def stop(self) -> None:
"""Stop the server."""
self.running = False
if self.server_sock:
self.server_sock.close()
\ No newline at end of file
# Video AI Configuration Module
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Configuration management for Video AI.
Handles backend selection for analysis and training.
Uses SQLite database for persistence.
"""
from .database import get_config, set_config, get_all_config, get_system_prompt, set_system_prompt
def get_analysis_backend() -> str:
"""Get the selected backend for analysis."""
return get_config('analysis_backend', 'cuda')
def get_training_backend() -> str:
"""Get the selected backend for training."""
return get_config('training_backend', 'cuda')
def set_analysis_backend(backend: str) -> None:
"""Set the backend for analysis."""
set_config('analysis_backend', backend)
def set_training_backend(backend: str) -> None:
"""Set the backend for training."""
set_config('training_backend', backend)
def get_default_model() -> str:
"""Get the default model path."""
return get_config('default_model', 'Qwen/Qwen2.5-VL-7B-Instruct')
def set_default_model(model: str) -> None:
"""Set the default model path."""
set_config('default_model', model)
def get_frame_interval() -> int:
"""Get the default frame interval."""
return int(get_config('frame_interval', '10'))
def set_frame_interval(interval: int) -> None:
"""Set the default frame interval."""
set_config('frame_interval', str(interval))
def get_system_prompt_content(name: str = 'default') -> str:
"""Get system prompt content."""
return get_system_prompt(name)
def set_system_prompt_content(name: str, content: str) -> None:
"""Set system prompt content."""
set_system_prompt(name, content)
def get_optimize() -> bool:
"""Get optimize setting."""
return get_config('optimize', 'false').lower() == 'true'
def set_optimize(optimize: bool) -> None:
"""Set optimize setting."""
set_config('optimize', 'true' if optimize else 'false')
def get_ffmpeg() -> bool:
"""Get ffmpeg setting."""
return get_config('ffmpeg', 'false').lower() == 'true'
def set_ffmpeg(ffmpeg: bool) -> None:
"""Set ffmpeg setting."""
set_config('ffmpeg', 'true' if ffmpeg else 'false')
def get_flash() -> bool:
"""Get flash setting."""
return get_config('flash', 'false').lower() == 'true'
def set_flash(flash: bool) -> None:
"""Set flash setting."""
set_config('flash', 'true' if flash else 'false')
def get_host() -> str:
"""Get host setting."""
return get_config('host', '0.0.0.0')
def set_host(host: str) -> None:
"""Set host setting."""
set_config('host', host)
def get_port() -> int:
"""Get port setting."""
return int(get_config('port', '5000'))
def set_port(port: int) -> None:
"""Set port setting."""
set_config('port', str(port))
def get_debug() -> bool:
"""Get debug setting."""
return get_config('debug', 'false').lower() == 'true'
def set_debug(debug: bool) -> None:
"""Set debug setting."""
set_config('debug', 'true' if debug else 'false')
def get_allowed_dir() -> str:
"""Get allowed directory."""
return get_config('allowed_dir', '')
def set_allowed_dir(dir_path: str) -> None:
"""Set allowed directory."""
set_config('allowed_dir', dir_path)
def get_all_settings() -> dict:
"""Get all configuration settings."""
config = get_all_config()
return {
'analysis_backend': config.get('analysis_backend', 'cuda'),
'training_backend': config.get('training_backend', 'cuda'),
'default_model': config.get('default_model', 'Qwen/Qwen2.5-VL-7B-Instruct'),
'frame_interval': int(config.get('frame_interval', '10')),
'optimize': config.get('optimize', 'false').lower() == 'true',
'ffmpeg': config.get('ffmpeg', 'false').lower() == 'true',
'flash': config.get('flash', 'false').lower() == 'true',
'host': config.get('host', '0.0.0.0'),
'port': int(config.get('port', '5000')),
'debug': config.get('debug', 'false').lower() == 'true',
'allowed_dir': config.get('allowed_dir', ''),
'system_prompt': get_system_prompt_content()
}
\ No newline at end of file
# Video AI Database Module
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Database management for Video AI.
Uses SQLite for persistent configuration storage.
"""
import sqlite3
import os
from typing import Dict, Any, Optional
DB_PATH = os.path.expanduser("~/.config/vidai/vidai.db")
def get_db_connection() -> sqlite3.Connection:
"""Get database connection, creating database if it doesn't exist."""
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
init_db(conn)
return conn
def init_db(conn: sqlite3.Connection) -> None:
"""Initialize database tables if they don't exist."""
cursor = conn.cursor()
# Configuration table
cursor.execute('''
CREATE TABLE IF NOT EXISTS config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
''')
# System prompts table
cursor.execute('''
CREATE TABLE IF NOT EXISTS system_prompts (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Insert default configurations if not exist
defaults = {
'analysis_backend': 'cuda',
'training_backend': 'cuda',
'default_model': 'Qwen/Qwen2.5-VL-7B-Instruct',
'frame_interval': '10',
'optimize': 'false',
'ffmpeg': 'false',
'flash': 'false',
'host': '0.0.0.0',
'port': '5000',
'debug': 'false',
'allowed_dir': ''
}
for key, value in defaults.items():
cursor.execute('INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)', (key, value))
# Insert default system prompt if not exist
cursor.execute('INSERT OR IGNORE INTO system_prompts (name, content) VALUES (?, ?)',
('default', 'when the action done by the person or persons in the frame changes, or where the scenario change, or where there an active action after a long time of no actions happening'))
conn.commit()
def get_config(key: str, default: str = '') -> str:
"""Get configuration value."""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT value FROM config WHERE key = ?', (key,))
row = cursor.fetchone()
conn.close()
return row['value'] if row else default
def set_config(key: str, value: str) -> None:
"""Set configuration value."""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)', (key, value))
conn.commit()
conn.close()
def get_all_config() -> Dict[str, str]:
"""Get all configuration as dictionary."""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT key, value FROM config')
rows = cursor.fetchall()
conn.close()
return {row['key']: row['value'] for row in rows}
def get_system_prompt(name: str = 'default') -> str:
"""Get system prompt by name."""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT content FROM system_prompts WHERE name = ?', (name,))
row = cursor.fetchone()
conn.close()
return row['content'] if row else ''
def set_system_prompt(name: str, content: str) -> None:
"""Set system prompt."""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO system_prompts (name, content, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
''', (name, content))
conn.commit()
conn.close()
def get_all_system_prompts() -> Dict[str, Dict[str, Any]]:
"""Get all system prompts."""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT id, name, content, created_at, updated_at FROM system_prompts')
rows = cursor.fetchall()
conn.close()
return {row['name']: dict(row) for row in rows}
\ No newline at end of file
# Video AI Web Interface Process
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Web interface process for Video AI.
Serves the web UI and communicates with backend via sockets.
"""
from flask import Flask, request, render_template_string, send_from_directory
import os
import sys
import json
import uuid
import time
from .comm import SocketCommunicator, Message
from .config import get_system_prompt_content, set_system_prompt_content, get_all_settings, set_analysis_backend, set_training_backend, set_default_model, set_frame_interval
app = Flask(__name__)
os.makedirs('static', exist_ok=True)
# Communicator to backend
comm = SocketCommunicator(port=5001)
comm.connect()
def send_to_backend(msg_type: str, data: dict) -> str:
"""Send message to backend and return message id."""
msg_id = str(uuid.uuid4())
message = Message(msg_type, msg_id, data)
comm.send_message(message)
return msg_id
def get_result(msg_id: str) -> dict:
"""Poll for result from backend."""
result_file = f"/tmp/vidai_results/{msg_id}.json"
for _ in range(100): # Poll for 10 seconds
if os.path.exists(result_file):
with open(result_file, 'r') as f:
data = json.load(f)
os.unlink(result_file)
return data
time.sleep(0.1)
return {'error': 'Timeout waiting for result'}
@app.route('/', methods=['GET', 'POST'])
def index():
result = None
if request.method == 'POST':
model_path = request.form.get('model_path', 'Qwen/Qwen2.5-VL-7B-Instruct')
prompt = request.form.get('prompt', 'Describe this image.')
uploaded_file = request.files.get('file')
local_path = request.form.get('local_path')
if uploaded_file and uploaded_file.filename:
# For simplicity, assume file is uploaded, but in real, need to handle
# For now, send path or something
data = {
'model_path': model_path,
'prompt': prompt,
'file_name': uploaded_file.filename,
# In real, upload file to temp and send path
}
msg_id = send_to_backend('analyze_request', data)
result_data = get_result(msg_id)
if 'data' in result_data:
result = result_data['data'].get('result', 'Analysis completed')
else:
result = result_data.get('error', 'Error')
elif local_path:
data = {
'model_path': model_path,
'prompt': prompt,
'local_path': local_path
}
msg_id = send_to_backend('analyze_request', data)
result_data = get_result(msg_id)
if 'data' in result_data:
result = result_data['data'].get('result', 'Analysis completed')
else:
result = result_data.get('error', 'Error')
html = '''
<!DOCTYPE html>
<html>
<head>
<title>VideoModel AI</title>
<style>
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; }
.container { max-width: 800px; margin: auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
h1 { color: #333; text-align: center; }
form { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; }
input[type="text"], input[type="file"] { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; }
input[type="submit"] { background: #007bff; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }
.result { background: #e9ecef; padding: 10px; border-radius: 4px; }
</style>
</head>
<body>
<div class="container">
<h1>VideoModel AI Web Interface</h1>
<nav><a href="/">Analysis</a> | <a href="/train">Training</a> | <a href="/config">Configuration</a></nav>
<h2>Analyze Image/Video</h2>
<form method="post" enctype="multipart/form-data">
<label>Model Path: <input type="text" name="model_path" value="Qwen/Qwen2.5-VL-7B-Instruct"></label>
<p><a href="/system">Edit System Prompt</a></p>
<label>Upload File: <input type="file" name="file" accept="image/*,video/*"></label>
<label>Or Local Path: <input type="text" name="local_path"></label>
<label>Prompt: <textarea name="prompt" rows="3">Describe this image.</textarea></label>
<input type="submit" value="Analyze">
</form>
{% if result %}
<div class="result">
<h3>Result:</h3>
<p>{{ result }}</p>
</div>
{% endif %}
</div>
</body>
</html>
'''
return render_template_string(html, result=result)
@app.route('/train', methods=['GET', 'POST'])
def train():
message = None
if request.method == 'POST':
data = {
'output_model': request.form.get('output_model', './VideoModel'),
'description': request.form.get('description', ''),
'train_dir': request.form.get('train_dir', '')
}
msg_id = send_to_backend('train_request', data)
result_data = get_result(msg_id)
if 'data' in result_data:
message = result_data['data'].get('message', 'Training completed')
else:
message = result_data.get('error', 'Error')
html = '''
<!DOCTYPE html>
<html>
<head>
<title>VideoModel AI - Training</title>
<style>
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; }
.container { max-width: 800px; margin: auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
h1 { color: #333; text-align: center; }
form { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; }
input[type="text"] { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; }
input[type="submit"] { background: #007bff; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }
.message { background: #e9ecef; padding: 10px; border-radius: 4px; }
</style>
</head>
<body>
<div class="container">
<h1>VideoModel AI Web Interface</h1>
<nav><a href="/">Analysis</a> | <a href="/train">Training</a> | <a href="/config">Configuration</a></nav>
<h2>Train Model</h2>
<form method="post">
<label>Output Model Path: <input type="text" name="output_model" value="./VideoModel"></label>
<label>Description: <textarea name="description"></textarea></label>
<label>Training Directory: <input type="text" name="train_dir"></label>
<input type="submit" value="Start Training">
</form>
{% if message %}
<div class="message">
<p>{{ message }}</p>
</div>
{% endif %}
</div>
</body>
</html>
'''
return render_template_string(html, message=message)
@app.route('/config', methods=['GET', 'POST'])
def config():
if request.method == 'POST':
# Update local config
set_analysis_backend(request.form.get('analysis_backend', 'cuda'))
set_training_backend(request.form.get('training_backend', 'cuda'))
set_default_model(request.form.get('default_model', 'Qwen/Qwen2.5-VL-7B-Instruct'))
set_frame_interval(int(request.form.get('frame_interval', 10)))
# Send to backend for routing updates
data = {
'analysis_backend': request.form.get('analysis_backend', 'cuda'),
'training_backend': request.form.get('training_backend', 'cuda')
}
msg_id = send_to_backend('config_update', data)
result_data = get_result(msg_id)
status = result_data.get('data', {}).get('status', 'Error')
# Get current config
current_config = get_all_settings()
html = f'''
<!DOCTYPE html>
<html>
<head>
<title>Configuration</title>
<style>
body {{ font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; }}
.container {{ max-width: 800px; margin: auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }}
h1 {{ color: #333; text-align: center; }}
form {{ margin-bottom: 20px; }}
label {{ display: block; margin-bottom: 5px; }}
select, input[type="text"], input[type="number"] {{ width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; }}
input[type="submit"] {{ background: #007bff; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }}
</style>
</head>
<body>
<div class="container">
<h1>Configuration</h1>
<nav><a href="/">Analysis</a> | <a href="/train">Training</a> | <a href="/config">Configuration</a></nav>
<form method="post">
<label>Analysis Backend:
<select name="analysis_backend">
<option value="cuda" {"selected" if current_config['analysis_backend'] == 'cuda' else ""}>CUDA</option>
<option value="rocm" {"selected" if current_config['analysis_backend'] == 'rocm' else ""}>ROCm</option>
</select>
</label>
<label>Training Backend:
<select name="training_backend">
<option value="cuda" {"selected" if current_config['training_backend'] == 'cuda' else ""}>CUDA</option>
<option value="rocm" {"selected" if current_config['training_backend'] == 'rocm' else ""}>ROCm</option>
</select>
</label>
<label>Default Model: <input type="text" name="default_model" value="{current_config['default_model']}"></label>
<label>Frame Interval (seconds): <input type="number" name="frame_interval" value="{current_config['frame_interval']}" min="1"></label>
<input type="submit" value="Save Configuration">
</form>
</div>
</body>
</html>
'''
return html
@app.route('/system', methods=['GET', 'POST'])
def system_page():
if request.method == 'POST':
system_prompt = request.form.get('system_prompt', '')
set_system_prompt_content('default', system_prompt)
current_prompt = get_system_prompt_content()
html = f'''
<!DOCTYPE html>
<html>
<head>
<title>System Prompt</title>
<style>
body {{ font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; }}
.container {{ max-width: 800px; margin: auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }}
h1 {{ color: #333; text-align: center; }}
textarea {{ width: 100%; height: 200px; }}
input[type="submit"] {{ background: #007bff; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }}
input[type="submit"]:hover {{ background: #0056b3; }}
</style>
</head>
<body>
<div class="container">
<h1>Edit System Prompt</h1>
<form method="post">
<textarea name="system_prompt">{current_prompt}</textarea><br>
<input type="submit" value="Save">
</form>
<a href="/">Back to Analysis</a>
</div>
</body>
</html>
'''
return html
@app.route('/static/<path:filename>')
def serve_static(filename):
return send_from_directory('static', filename)
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
\ No newline at end of file
# Video AI Analysis Worker
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Analysis worker process for Video AI.
Handles image/video analysis requests.
"""
import os
import sys
import torch
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
import tempfile
import subprocess
import json
import cv2
import time
from .comm import SocketCommunicator, Message
from .config import get_system_prompt_content
# Set PyTorch CUDA memory management
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
# GPU delegation
gpu_mem = []
if torch.cuda.is_available():
for i in range(torch.cuda.device_count()):
gpu_mem.append(torch.cuda.get_device_properties(i).total_memory)
max_gpu = gpu_mem.index(max(gpu_mem)) if gpu_mem else 0
min_gpu = gpu_mem.index(min(gpu_mem)) if gpu_mem else 0
else:
max_gpu = min_gpu = 0
# Set OpenCV to smaller GPU if available
try:
if cv2 and hasattr(cv2, 'cuda'):
cv2.cuda.setDevice(min_gpu)
except:
pass
def extract_frames(video_path, interval=10, optimize=False):
if cv2:
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
frame_interval = int(fps * interval)
frames = []
count = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if count % frame_interval == 0:
if optimize:
height, width = frame.shape[:2]
new_width = 640
new_height = int(height * new_width / width)
frame = cv2.resize(frame, (new_width, new_height))
temp_img = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
cv2.imwrite(temp_img.name, frame)
frames.append((temp_img.name, count / fps))
count += 1
cap.release()
return frames, None
else:
output_dir = tempfile.mkdtemp()
vf = f"fps=1/{interval}"
if optimize:
vf += ",scale=640:-1"
cmd = ["ffmpeg", "-i", video_path, "-vf", vf, os.path.join(output_dir, "frame_%04d.jpg")]
subprocess.run(cmd, check=True, capture_output=True)
frames = []
for file in sorted(os.listdir(output_dir)):
if file.endswith('.jpg'):
path = os.path.join(output_dir, file)
frame_num = int(file.split('_')[1].split('.')[0])
ts = (frame_num - 1) * interval
frames.append((path, ts))
return frames, output_dir
def is_video(file_path):
return file_path.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))
def analyze_single_image(image_path, prompt, model, processor):
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": image_path},
{"type": "text", "text": prompt},
],
}
]
inputs = processor.apply_chat_template(
messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt"
)
inputs = {k: v.to(model.device) for k, v in inputs.items()}
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs['input_ids'], generated_ids)
]
output_text = processor.batch_decode(
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
return output_text[0]
def analyze_media(media_path, prompt, model_path, interval=10):
torch.cuda.empty_cache()
if model_path not in model_cache:
kwargs = {"device_map": "auto", "low_cpu_mem_usage": True}
if os.path.exists(model_path):
try:
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(model_path, **kwargs)
proc_path = model_path
except:
model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", **kwargs)
proc_path = "Qwen/Qwen2.5-VL-7B-Instruct"
else:
model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", **kwargs)
proc_path = "Qwen/Qwen2.5-VL-7B-Instruct"
model_cache[model_path] = model
processor_cache[model_path] = AutoProcessor.from_pretrained(proc_path)
else:
model = model_cache[model_path]
proc_path = model_path if os.path.exists(model_path) else "Qwen/Qwen2.5-VL-7B-Instruct"
processor = processor_cache[model_path]
system_prompt = get_system_prompt_content()
full_prompt = system_prompt + " " + prompt if system_prompt else prompt
if is_video(media_path):
frames, output_dir = extract_frames(media_path, interval, optimize=True)
total_frames = len(frames)
descriptions = []
for i, (frame_path, ts) in enumerate(frames):
desc = analyze_single_image(frame_path, full_prompt, model, processor)
descriptions.append(f"At {ts:.2f}s: {desc}")
os.unlink(frame_path)
if output_dir:
import shutil
shutil.rmtree(output_dir)
summary_prompt = f"Summarize the video based on frame descriptions: {' '.join(descriptions)}"
messages = [{"role": "user", "content": [{"type": "text", "text": summary_prompt}]}]
inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt")
inputs = {k: v.to(model.device) for k, v in inputs.items()}
generated_ids = model.generate(**inputs, max_new_tokens=256)
generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs['input_ids'], generated_ids)]
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
summary = output_text[0]
result = f"Frame Descriptions:\n" + "\n".join(descriptions) + f"\n\nSummary:\n{summary}"
return result
else:
result = analyze_single_image(media_path, full_prompt, model, processor)
torch.cuda.empty_cache()
return result
model_cache = {}
processor_cache = {}
def worker_process(backend_type: str):
"""Main worker process."""
print(f"Starting Analysis Worker for {backend_type}...")
comm = SocketCommunicator(port=5002)
comm.connect()
# Register with backend
register_msg = Message('register', 'register', {'type': f'analysis_{backend_type}'})
comm.send_message(register_msg)
while True:
try:
message = comm.receive_message()
if message and message.msg_type == 'analyze_request':
data = message.data
media_path = data.get('local_path', data.get('file_name', ''))
if not media_path:
result = 'No media path provided'
else:
prompt = data.get('prompt', 'Describe this image.')
model_path = data.get('model_path', 'Qwen/Qwen2.5-VL-7B-Instruct')
interval = data.get('interval', 10)
result = analyze_media(media_path, prompt, model_path, interval)
response = Message('analyze_response', message.msg_id, {'result': result})
comm.send_message(response)
time.sleep(0.1)
except Exception as e:
print(f"Worker error: {e}")
time.sleep(1)
if __name__ == "__main__":
backend_type = sys.argv[1] if len(sys.argv) > 1 else 'cuda'
worker_process(backend_type)
\ No newline at end of file
# Video AI Training Worker
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Training worker process for Video AI.
Handles model training requests.
"""
import os
import sys
import subprocess
import tempfile
import shutil
import json
import time
from .comm import SocketCommunicator, Message
def train_model(train_path, output_model, description):
"""Perform training."""
desc_file = os.path.join(train_path, "description.txt")
with open(desc_file, "w") as f:
f.write(description)
# Assume videotrain is available
cmd = ["python", "videotrain", train_path, "--output_dir", output_model]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
return "Training completed!"
else:
return f"Training failed: {result.stderr}"
def worker_process(backend_type: str):
"""Main worker process."""
print(f"Starting Training Worker for {backend_type}...")
comm = SocketCommunicator(port=5002)
comm.connect()
# Register with backend
register_msg = Message('register', 'register', {'type': f'training_{backend_type}'})
comm.send_message(register_msg)
while True:
try:
message = comm.receive_message()
if message and message.msg_type == 'train_request':
data = message.data
output_model = data.get('output_model', './VideoModel')
description = data.get('description', '')
train_dir = data.get('train_dir', '')
if train_dir and os.path.isdir(train_dir):
result = train_model(train_dir, output_model, description)
else:
result = "No valid training directory provided"
response = Message('train_response', message.msg_id, {'message': result})
comm.send_message(response)
time.sleep(0.1)
except Exception as e:
print(f"Worker error: {e}")
time.sleep(1)
if __name__ == "__main__":
backend_type = sys.argv[1] if len(sys.argv) > 1 else 'cuda'
worker_process(backend_type)
\ No newline at end of file
# Video AI Web Interface
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from flask import Flask, request, render_template, render_template_string, send_from_directory
import os
import sys
import torch
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
import tempfile
import subprocess
import shutil
import json
import time
import cv2
import threading
try:
import psutil
psutil_available = True
except ImportError:
psutil_available = False
print("psutil not available, install with: pip install psutil")
# Set PyTorch CUDA memory management
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
try:
import pynvml
pynvml.nvmlInit()
nvml_available = True
except ImportError:
nvml_available = False
print("pynvml not available, install with: pip install pynvml")
try:
import flash_attn
flash_attn_available = True
except ImportError:
flash_attn_available = False
print("flash_attn not available, install with: pip install flash-attn")
force_ffmpeg = '--ffmpeg' in sys.argv
optimize = '--optimize' in sys.argv
flash_attn = '--flash' in sys.argv
model_default = "Qwen/Qwen2.5-VL-7B-Instruct"
if '--model' in sys.argv:
idx = sys.argv.index('--model')
if idx + 1 < len(sys.argv):
model_default = sys.argv[idx + 1]
allowed_dir = None
if '--dir' in sys.argv:
idx = sys.argv.index('--dir')
if idx + 1 < len(sys.argv):
allowed_dir = os.path.abspath(sys.argv[idx + 1])
app = Flask(__name__)
os.makedirs('static', exist_ok=True)
status = "Idle"
start_time = 0
cancel = False
analysis_result = None
analysis_thread = None
model_cache = {}
processor_cache = {}
current_frame = 0
total_frames = 0
# System prompt
config_dir = os.path.expanduser("~/.config/AIVideo")
os.makedirs(config_dir, exist_ok=True)
system_prompt_file = os.path.join(config_dir, "system_prompt.txt")
if os.path.exists(system_prompt_file):
with open(system_prompt_file, "r") as f:
system_prompt = f.read()
else:
system_prompt = "when the action done by the person or persons in the frame changes, or where the scenario change, or where there an active action after a long time of no actions happening"
# GPU delegation
gpu_mem = []
if torch.cuda.is_available():
for i in range(torch.cuda.device_count()):
gpu_mem.append(torch.cuda.get_device_properties(i).total_memory)
max_gpu = gpu_mem.index(max(gpu_mem)) if gpu_mem else 0
min_gpu = gpu_mem.index(min(gpu_mem)) if gpu_mem else 0
else:
max_gpu = min_gpu = 0
# Set OpenCV to smaller GPU if available
try:
if cv2 and hasattr(cv2, 'cuda'):
cv2.cuda.setDevice(min_gpu)
except:
pass
def extract_frames(video_path, interval=10):
global optimize
if cv2 and not force_ffmpeg:
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
frame_interval = int(fps * interval)
frames = []
count = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if count % frame_interval == 0:
if optimize:
height, width = frame.shape[:2]
new_width = 640
new_height = int(height * new_width / width)
frame = cv2.resize(frame, (new_width, new_height))
temp_img = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
cv2.imwrite(temp_img.name, frame)
frames.append((temp_img.name, count / fps))
count += 1
cap.release()
return frames, None
else:
output_dir = tempfile.mkdtemp()
vf = f"fps=1/{interval}"
if optimize:
vf += ",scale=640:-1"
cmd = ["ffmpeg", "-i", video_path, "-vf", vf, os.path.join(output_dir, "frame_%04d.jpg")]
subprocess.run(cmd, check=True, capture_output=True)
frames = []
for file in sorted(os.listdir(output_dir)):
if file.endswith('.jpg'):
path = os.path.join(output_dir, file)
frame_num = int(file.split('_')[1].split('.')[0])
ts = (frame_num - 1) * interval
frames.append((path, ts))
return frames, output_dir
def analyze_media_thread(media_path, prompt, model_path, interval=10):
global analysis_result, cancel, status
analysis_result = analyze_media(media_path, prompt, model_path, interval)
if cancel:
status = "Cancelled"
else:
status = "Completed"
def is_video(file_path):
return file_path.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))
def analyze_single_image(image_path, prompt, model, processor):
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": image_path},
{"type": "text", "text": prompt},
],
}
]
inputs = processor.apply_chat_template(
messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt"
)
inputs = {k: v.to(model.device) for k, v in inputs.items()}
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs['input_ids'], generated_ids)
]
output_text = processor.batch_decode(
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
return output_text[0]
def analyze_media(media_path, prompt, model_path, interval=10):
global status, start_time, model_cache, processor_cache, system_prompt, current_frame, total_frames
torch.cuda.empty_cache()
status = "Loading model"
start_time = time.time()
if model_path not in model_cache:
kwargs = {"device_map": "auto", "low_cpu_mem_usage": True}
if flash_attn:
if flash_attn_available:
kwargs["attn_implementation"] = "flash_attention_2"
kwargs["dtype"] = torch.float16
else:
print("Flash Attention 2 requested but flash_attn not installed. Install with: pip install flash-attn")
if os.path.exists(model_path):
try:
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(model_path, **kwargs)
proc_path = model_path
except:
model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", **kwargs)
proc_path = "Qwen/Qwen2.5-VL-7B-Instruct"
else:
model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", **kwargs)
proc_path = "Qwen/Qwen2.5-VL-7B-Instruct"
model_cache[model_path] = model
processor_cache[model_path] = AutoProcessor.from_pretrained(proc_path)
else:
model = model_cache[model_path]
proc_path = model_path if os.path.exists(model_path) else "Qwen/Qwen2.5-VL-7B-Instruct"
processor = processor_cache[model_path]
status = "Model loaded"
full_prompt = system_prompt + " " + prompt if system_prompt else prompt
if is_video(media_path):
status = "Extracting frames"
frames, output_dir = extract_frames(media_path)
total_frames = len(frames)
status = f"Analyzing frames (0/{total_frames})"
descriptions = []
for i, (frame_path, ts) in enumerate(frames):
if cancel:
break
current_frame = i + 1
status = f"Analyzing frame {current_frame}/{total_frames}"
desc = analyze_single_image(frame_path, full_prompt, model, processor)
descriptions.append(f"At {ts:.2f}s: {desc}")
os.unlink(frame_path) # Remove frame after analysis to save disk space
if output_dir:
shutil.rmtree(output_dir)
status = "Summarizing video"
summary_prompt = f"Summarize the video based on frame descriptions, indicating scene changes and timestamps: {' '.join(descriptions)}"
messages = [{"role": "user", "content": [{"type": "text", "text": summary_prompt}]}]
inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt")
inputs = {k: v.to(model.device) for k, v in inputs.items()}
generated_ids = model.generate(**inputs, max_new_tokens=256)
generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs['input_ids'], generated_ids)]
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
summary = output_text[0]
result = f"Frame Descriptions:\n" + "\n".join(descriptions) + f"\n\nSummary:\n{summary}"
if len(descriptions) > 5:
mid_ts = frames[len(frames)//2][1]
cmd1 = ["ffmpeg", "-y", "-i", media_path, "-ss", "0", "-t", str(mid_ts), "-c", "copy", "static/segment1.mp4"]
subprocess.run(cmd1, check=True)
cmd2 = ["ffmpeg", "-y", "-i", media_path, "-ss", str(mid_ts), "-c", "copy", "static/segment2.mp4"]
subprocess.run(cmd2, check=True)
result += f"\nVideo split into segments: <a href='/static/segment1.mp4'>Segment 1</a>, <a href='/static/segment2.mp4'>Segment 2</a>"
status = "Idle"
return result
else:
result = analyze_single_image(media_path, full_prompt, model, processor)
torch.cuda.empty_cache()
status = "Idle"
current_frame = 0
total_frames = 0
return result
def list_files(directory):
files = []
for root, dirs, filenames in os.walk(directory):
for filename in filenames:
files.append(os.path.join(root, filename))
return files
@app.route('/', methods=['GET', 'POST'])
def index():
global system_prompt, analysis_result
result = None
model_path_default = "./VideoModel" if os.path.exists("./VideoModel") else model_default
if analysis_result is not None:
result = analysis_result
analysis_result = None
if request.method == 'POST':
model_path = request.form.get('model_path', model_path_default)
prompt = request.form.get('prompt', 'Describe this image.')
uploaded_file = request.files.get('file')
local_path = request.form.get('local_path')
upload_id = request.form.get('upload_id')
if upload_id:
file_name = request.form.get('file_name', 'uploaded_file')
media_path = os.path.join(tempfile.gettempdir(), f"{upload_id}_{file_name}")
elif uploaded_file and uploaded_file.filename:
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.filename)[1]) as tmp:
tmp.write(uploaded_file.read())
media_path = tmp.name
elif local_path and os.path.exists(local_path):
if allowed_dir and not os.path.abspath(local_path).startswith(allowed_dir):
result = "Access denied to file"
else:
media_path = local_path
else:
result = "Provide a file or path"
if 'media_path' in locals():
interval = int(request.form.get('interval', 10))
global analysis_thread, cancel
cancel = False
analysis_result = None
analysis_thread = threading.Thread(target=analyze_media_thread, args=(media_path, prompt, model_path, interval))
analysis_thread.start()
result = "Analysis started. Check status for progress."
if uploaded_file:
# Keep file for thread
pass
html = '''
<!DOCTYPE html>
<html>
<head>
<title>VideoModel AI</title>
<style>
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; display: flex; justify-content: center; align-items: flex-start; }
.main { flex: 1; max-width: 800px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-right: 20px; }
.sidebar { width: 300px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
h1 { color: #333; text-align: center; }
nav { text-align: center; margin-bottom: 20px; }
nav a { margin: 0 10px; text-decoration: none; color: #007bff; }
form { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; }
input[type="text"], input[type="file"], textarea { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; }
input[type="submit"] { background: #007bff; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }
input[type="submit"]:hover { background: #0056b3; }
.result { background: #e9ecef; padding: 10px; border-radius: 4px; }
.stats { font-size: 14px; }
</style>
<script>
function openFileBrowser() {
window.open('/files', 'filebrowser', 'width=600,height=400');
}
async function updateStats() {
try {
const response = await fetch('/stats');
const data = await response.json();
let html = '<h3>GPU Stats</h3>';
html += `<p style="color: ${data.status === 'Idle' ? 'green' : 'orange'};">Status: ${data.status}</p>`;
if (data.elapsed > 0) {
html += `<p>Elapsed: ${data.elapsed.toFixed(1)}s</p>`;
}
if (data.gpu_count > 0) {
data.gpus.forEach((gpu, i) => {
let memPercent = (gpu.memory_used / gpu.memory_total * 100).toFixed(1);
html += `<p>GPU ${i}: ${gpu.name}<br>Memory: <progress value="${gpu.memory_used}" max="${gpu.memory_total}"></progress> ${gpu.memory_used.toFixed(2)} / ${gpu.memory_total.toFixed(2)} GB (${memPercent}%)<br>Utilization: ${gpu.utilization}%</p>`;
});
} else {
html += '<p>No GPUs detected</p>';
}
html += `<p>CPU: ${data.cpu_percent.toFixed(1)}%</p>`;
html += `<p>RAM: ${data.ram_used.toFixed(2)} / ${data.ram_total.toFixed(2)} GB</p>`;
document.getElementById('stats').innerHTML = html;
if (data.result) {
document.getElementById('result_div').innerHTML = '<h3>Result:</h3><p>' + data.result + '</p>';
document.getElementById('result_div').style.display = 'block';
}
} catch (e) {
document.getElementById('stats').innerHTML = '<p>Error loading stats</p>';
}
}
setInterval(updateStats, 5000);
window.onload = updateStats;
function cancelAnalysis() {
fetch('/cancel', {method: 'POST'}).then(() => updateStats());
}
// Upload progress
const fileInput = document.getElementById('fileInput');
if (fileInput) {
fileInput.addEventListener('change', function() {
const file = this.files[0];
if (file) {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', file);
const startTime = Date.now();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
document.getElementById('uploadProgress').value = percent;
document.getElementById('uploadProgress').style.display = 'block';
const speed = e.loaded / ((Date.now() - startTime) / 1000);
const remaining = (e.total - e.loaded) / speed;
document.getElementById('progressText').innerText = `Uploaded ${(e.loaded / 1024 / 1024).toFixed(2)} MB of ${(e.total / 1024 / 1024).toFixed(2)} MB (${percent.toFixed(1)}%) - Speed: ${(speed / 1024 / 1024).toFixed(2)} MB/s - ETA: ${Math.round(remaining)}s`;
}
});
xhr.addEventListener('load', function() {
document.getElementById('progressText').innerText = 'Upload complete';
});
xhr.open('POST', '/upload_progress');
xhr.send(formData);
}
});
}
</script>
</head>
<body>
<div class="main">
<h1>VideoModel AI Web Interface</h1>
<nav>
<a href="/">Analysis</a> | <a href="/train">Training</a>
</nav>
<h2>Analyze Image/Video</h2>
<form method="post" enctype="multipart/form-data">
<label>Model Path: <input type="text" name="model_path" value="{{ model_path_default }}"></label>
<p><a href="/system">Edit System Prompt</a></p>
<label>Upload File: <input type="file" name="file" accept="image/*,video/*" id="fileInput"></label>
<progress id="uploadProgress" value="0" max="100" style="display:none; width:100%;"></progress>
<div id="progressText"></div>
{% if allowed_dir %}
<label>Or Local Path: <input type="text" name="local_path" id="local_path"> <button type="button" onclick="openFileBrowser()">Browse</button></label>
{% endif %}
<label>Prompt: <textarea name="prompt" rows="5" cols="80">Describe this image.</textarea></label>
<input type="submit" value="Analyze">
<button type="button" onclick="cancelAnalysis()">Cancel Analysis</button>
</form>
<div class="result" id="result_div" style="display:none;"></div>
{% if result %}
<div class="result">
<h3>Result:</h3>
<p>{{ result }}</p>
</div>
{% endif %}
</div>
<div class="sidebar">
<div id="stats" class="stats">Loading stats...</div>
</div>
</body>
</html>
'''
html = '''
<!DOCTYPE html>
<html>
<head>
<title>VideoModel AI</title>
<style>
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; display: flex; justify-content: center; align-items: flex-start; }
.main { flex: 1; max-width: 800px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-right: 20px; }
.sidebar { width: 300px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
h1 { color: #333; text-align: center; }
nav { text-align: center; margin-bottom: 20px; }
nav a { margin: 0 10px; text-decoration: none; color: #007bff; }
form { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; }
input[type="text"], input[type="file"], textarea { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; }
input[type="submit"] { background: #007bff; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }
input[type="submit"]:hover { background: #0056b3; }
.result { background: #e9ecef; padding: 10px; border-radius: 4px; }
.stats { font-size: 14px; }
</style>
</head>
<body>
<div class="main">
<h1>VideoModel AI Web Interface</h1>
<nav>
<a href="/">Analysis</a> | <a href="/train">Training</a>
</nav>
<h2>Analyze Image/Video</h2>
<form method="post" enctype="multipart/form-data">
<label>Model Path: <input type="text" name="model_path" value="{{ model_path_default }}"></label>
<p><a href="/system">Edit System Prompt</a></p>
<label>Upload File: <input type="file" name="file" accept="image/*,video/*" id="fileInput"></label>
<progress id="uploadProgress" value="0" max="100" style="display:none; width:100%;"></progress>
<div id="progressText"></div>
{% if allowed_dir %}
<label>Or Local Path: <input type="text" name="local_path" id="local_path"> <button type="button" onclick="openFileBrowser()">Browse</button></label>
{% endif %}
<label>Frame Interval (seconds): <input type="number" name="interval" value="10" min="1"></label>
<label>Prompt: <textarea name="prompt" rows="5" cols="80">Describe this image.</textarea></label>
<input type="submit" value="Analyze">
<button type="button" onclick="cancelAnalysis()">Cancel Analysis</button>
</form>
<div class="result" id="result_div" style="display:none;"></div>
{% if result %}
<div class="result">
<h3>Result:</h3>
<p>{{ result }}</p>
</div>
{% endif %}
</div>
<div class="sidebar">
<div id="stats" class="stats">Loading stats...</div>
</div>
<script>
function openFileBrowser() {
window.open('/files', 'filebrowser', 'width=600,height=400');
}
async function updateStats() {
try {
const response = await fetch('/stats');
const data = await response.json();
let html = '<h3>GPU Stats</h3>';
html += `<p style="color: ${data.status === 'Idle' ? 'green' : 'orange'};">Status: ${data.status}</p>`;
if (data.elapsed > 0) {
html += `<p>Elapsed: ${data.elapsed.toFixed(1)}s</p>`;
}
if (data.gpu_count > 0) {
data.gpus.forEach((gpu, i) => {
let memPercent = (gpu.memory_used / gpu.memory_total * 100).toFixed(1);
html += `<p>GPU ${i}: ${gpu.name}<br>Memory: <progress value="${gpu.memory_used}" max="${gpu.memory_total}"></progress> ${gpu.memory_used.toFixed(2)} / ${gpu.memory_total.toFixed(2)} GB (${memPercent}%)<br>Utilization: ${gpu.utilization}%</p>`;
});
} else {
html += '<p>No GPUs detected</p>';
}
html += `<p>CPU: ${data.cpu_percent.toFixed(1)}%</p>`;
html += `<p>RAM: ${data.ram_used.toFixed(2)} / ${data.ram_total.toFixed(2)} GB</p>`;
document.getElementById('stats').innerHTML = html;
if (data.result) {
document.getElementById('result_div').innerHTML = '<h3>Result:</h3><p>' + data.result + '</p>';
document.getElementById('result_div').style.display = 'block';
}
} catch (e) {
document.getElementById('stats').innerHTML = '<p>Error loading stats</p>';
}
}
setInterval(updateStats, 5000);
window.onload = updateStats;
function cancelAnalysis() {
fetch('/cancel', {method: 'POST'}).then(() => updateStats());
}
// Upload progress with chunked upload
const form = document.querySelector('form');
if (form) {
form.addEventListener('submit', async function(e) {
e.preventDefault();
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
// Submit form normally if no file
const formData = new FormData(this);
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', function() {
window.location.reload();
});
xhr.open('POST', '/');
xhr.send(formData);
return;
}
const chunkSize = 1024 * 1024; // 1MB
const totalChunks = Math.ceil(file.size / chunkSize);
const uploadId = Date.now().toString();
const concurrency = 1;
let chunksSent = 0;
async function sendChunk(index) {
const start = index * chunkSize;
const end = Math.min(start + chunkSize, file.size);
const chunk = file.slice(start, end);
const formData = new FormData();
formData.append('chunk', chunk);
formData.append('chunk_index', index);
formData.append('total_chunks', totalChunks);
formData.append('file_name', file.name);
formData.append('upload_id', uploadId);
return new Promise((resolve) => {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
const percent = ((chunksSent * chunkSize + e.loaded) / file.size) * 100;
document.getElementById('uploadProgress').value = percent;
document.getElementById('uploadProgress').style.display = 'block';
const speed = (chunksSent * chunkSize + e.loaded) / ((Date.now() - startTime) / 1000);
const remaining = (file.size - (chunksSent * chunkSize + e.loaded)) / speed;
document.getElementById('progressText').innerText = `Uploaded ${((chunksSent * chunkSize + e.loaded) / 1024 / 1024).toFixed(2)} MB of ${(file.size / 1024 / 1024).toFixed(2)} MB (${percent.toFixed(1)}%) - Speed: ${(speed / 1024 / 1024).toFixed(2)} MB/s - ETA: ${Math.round(remaining)}s`;
}
});
xhr.addEventListener('load', function() {
chunksSent++;
resolve();
});
xhr.open('POST', '/upload_chunk');
xhr.send(formData);
});
}
const startTime = Date.now();
for (let i = 0; i < totalChunks; i += concurrency) {
const promises = [];
for (let j = 0; j < concurrency && i + j < totalChunks; j++) {
promises.push(sendChunk(i + j));
}
await Promise.all(promises);
}
// All chunks sent, reassembling
document.getElementById('progressText').innerText = 'Reassembling file...';
document.getElementById('uploadProgress').value = 100;
// Submit form
const formData2 = new FormData(form);
formData2.append('upload_id', uploadId);
formData2.append('file_name', file.name);
const xhr2 = new XMLHttpRequest();
xhr2.addEventListener('load', function() {
window.location.reload();
});
xhr2.open('POST', '/');
xhr2.send(formData2);
});
}
</script>
</body>
</html>
'''
return render_template_string(html, result=result, model_path_default=model_path_default, allowed_dir=allowed_dir)
@app.route('/train', methods=['GET', 'POST'])
def train():
model_path_default = "./VideoModel" if os.path.exists("./VideoModel") else model_default
message = None
if request.method == 'POST':
uploaded_data = request.files.get('data')
train_dir = request.form.get('train_dir')
description = request.form.get('description')
output_model = request.form.get('output_model', './VideoModel')
if uploaded_data and uploaded_data.filename:
if is_video(uploaded_data.filename):
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_data.filename)[1]) as tmp:
tmp.write(uploaded_data.read())
video_path = tmp.name
train_path = tempfile.mkdtemp()
frames, output_dir = extract_frames(video_path)
for frame_path, ts in frames:
shutil.move(frame_path, os.path.join(train_path, f"frame_{ts:.2f}.jpg"))
if output_dir:
shutil.rmtree(output_dir)
os.unlink(video_path)
else:
with tempfile.TemporaryDirectory() as tmp_dir:
zip_path = os.path.join(tmp_dir, "data.zip")
with open(zip_path, "wb") as f:
f.write(uploaded_data.read())
extract_dir = os.path.join(tmp_dir, "extracted")
shutil.unpack_archive(zip_path, extract_dir)
train_path = extract_dir
elif train_dir and os.path.isdir(train_dir):
if allowed_dir and not os.path.abspath(train_dir).startswith(allowed_dir):
message = "Access denied to directory"
else:
train_path = train_dir
else:
message = "Provide training data"
if 'train_path' in locals():
desc_file = os.path.join(train_path, "description.txt")
with open(desc_file, "w") as f:
f.write(description)
status = "Training"
cmd = ["python", "videotrain", train_path, "--output_dir", output_model]
result = subprocess.run(cmd, capture_output=True, text=True)
status = "Idle"
if result.returncode == 0:
message = "Training completed!"
else:
message = f"Training failed: {result.stderr}"
html = '''
<!DOCTYPE html>
<html>
<head>
<title>VideoModel AI - Training</title>
<style>
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; display: flex; justify-content: center; align-items: flex-start; }
.main { flex: 1; max-width: 800px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-right: 20px; }
.sidebar { width: 300px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
h1 { color: #333; text-align: center; }
nav { text-align: center; margin-bottom: 20px; }
nav a { margin: 0 10px; text-decoration: none; color: #007bff; }
form { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; }
input[type="text"], input[type="file"], textarea { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; }
input[type="submit"] { background: #007bff; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }
input[type="submit"]:hover { background: #0056b3; }
.message { background: #e9ecef; padding: 10px; border-radius: 4px; }
.stats { font-size: 14px; }
</style>
<script>
async function updateStats() {
try {
const response = await fetch('/stats');
const data = await response.json();
let html = '<h3>GPU Stats</h3>';
html += `<p style="color: ${data.status === 'Idle' ? 'green' : 'orange'};">Status: ${data.status}</p>`;
if (data.gpu_count > 0) {
data.gpus.forEach((gpu, i) => {
let memPercent = (gpu.memory_used / gpu.memory_total * 100).toFixed(1);
html += `<p>GPU ${i}: ${gpu.name}<br>Memory: <progress value="${gpu.memory_used}" max="${gpu.memory_total}"></progress> ${gpu.memory_used.toFixed(2)} / ${gpu.memory_total.toFixed(2)} GB (${memPercent}%)<br>Utilization: ${gpu.utilization}%</p>`;
});
} else {
html += '<p>No GPUs detected</p>';
}
html += `<p>CPU: ${data.cpu_percent.toFixed(1)}%</p>`;
html += `<p>RAM: ${data.ram_used.toFixed(2)} / ${data.ram_total.toFixed(2)} GB</p>`;
document.getElementById('stats').innerHTML = html;
if (data.result) {
document.getElementById('result_div').innerHTML = '<h3>Result:</h3><p>' + data.result + '</p>';
document.getElementById('result_div').style.display = 'block';
}
} catch (e) {
document.getElementById('stats').innerHTML = '<p>Error loading stats</p>';
}
}
setInterval(updateStats, 5000);
window.onload = updateStats;
</script>
</head>
<body>
<div class="main">
<h1>VideoModel AI Web Interface</h1>
<nav>
<a href="/">Analysis</a> | <a href="/train">Training</a>
</nav>
<h2>Train Model</h2>
<form method="post" enctype="multipart/form-data">
<label>Model Path: <input type="text" name="model_path" value="{{ model_path_default }}"></label>
<label>Upload Data (ZIP or Video): <input type="file" name="data" accept=".zip,.mp4,.avi"></label>
{% if allowed_dir %}
<label>Or Directory Path: <input type="text" name="train_dir"></label>
{% endif %}
<label>Description: <textarea name="description"></textarea></label>
<label>Output Model Path: <input type="text" name="output_model" value="./VideoModel"></label>
<input type="submit" value="Start Training">
</form>
<div class="message" id="result_div" style="display:none;"></div>
{% if message %}
<div class="message">
<p>{{ message }}</p>
</div>
{% endif %}
</div>
<div class="sidebar">
<div id="stats" class="stats">Loading stats...</div>
</div>
</body>
</html>
'''
return render_template_string(html, message=message, allowed_dir=allowed_dir, model_path_default=model_path_default)
@app.route('/cancel', methods=['POST'])
def cancel_analysis():
global cancel, status
cancel = True
status = "Cancelled"
return 'Analysis cancelled'
@app.route('/upload_chunk', methods=['POST'])
def upload_chunk():
chunk = request.files['chunk']
chunk_index = int(request.form['chunk_index'])
total_chunks = int(request.form['total_chunks'])
file_name = request.form['file_name']
upload_id = request.form['upload_id']
temp_dir = os.path.join(tempfile.gettempdir(), upload_id)
os.makedirs(temp_dir, exist_ok=True)
chunk_path = os.path.join(temp_dir, str(chunk_index))
chunk.save(chunk_path)
if len(os.listdir(temp_dir)) == total_chunks:
final_path = os.path.join(tempfile.gettempdir(), f"{upload_id}_{file_name}")
with open(final_path, 'wb') as f:
for i in range(total_chunks):
with open(os.path.join(temp_dir, str(i)), 'rb') as cf:
f.write(cf.read())
os.unlink(os.path.join(temp_dir, str(i)))
os.rmdir(temp_dir)
return 'OK'
@app.route('/system', methods=['GET', 'POST'])
def system_page():
global system_prompt
if request.method == 'POST':
system_prompt = request.form.get('system_prompt', '')
with open(system_prompt_file, "w") as f:
f.write(system_prompt)
html = f'''
<!DOCTYPE html>
<html>
<head>
<title>System Prompt</title>
<style>
body {{ font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; }}
.container {{ max-width: 800px; margin: auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }}
h1 {{ color: #333; text-align: center; }}
textarea {{ width: 100%; height: 200px; }}
input[type="submit"] {{ background: #007bff; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }}
input[type="submit"]:hover {{ background: #0056b3; }}
</style>
</head>
<body>
<div class="container">
<h1>Edit System Prompt</h1>
<form method="post">
<textarea name="system_prompt">{system_prompt}</textarea><br>
<input type="submit" value="Save">
</form>
<a href="/">Back to Analysis</a>
</div>
</body>
</html>
'''
return html
@app.route('/static/<path:filename>')
def serve_static(filename):
return send_from_directory('static', filename)
@app.route('/stats')
def stats():
global status, start_time, analysis_result
data = {'status': status}
if status != "Idle":
data['elapsed'] = time.time() - start_time
else:
data['elapsed'] = 0
data['result'] = analysis_result.replace('\n', '<br>') if analysis_result else ''
if psutil_available:
data['cpu_percent'] = psutil.cpu_percent()
ram = psutil.virtual_memory()
data['ram_used'] = ram.used / 1024**3
data['ram_total'] = ram.total / 1024**3
else:
data['cpu_percent'] = 0
data['ram_used'] = 0
data['ram_total'] = 0
if torch.cuda.is_available():
data['gpu_count'] = torch.cuda.device_count()
data['gpus'] = []
for i in range(torch.cuda.device_count()):
gpu = {
'name': torch.cuda.get_device_name(i),
'memory_used': torch.cuda.memory_allocated(i) / 1024**3, # GB
'memory_total': torch.cuda.get_device_properties(i).total_memory / 1024**3,
}
if nvml_available:
try:
handle = pynvml.nvmlDeviceGetHandleByIndex(i)
util = pynvml.nvmlDeviceGetHandleByIndex(i)
util = pynvml.nvmlDeviceGetUtilizationRates(handle)
gpu['utilization'] = util.gpu
except:
gpu['utilization'] = 0
data['gpus'].append(gpu)
else:
data['gpu_count'] = 0
return json.dumps(data)
@app.route('/files')
def files():
if not allowed_dir:
return "File browsing not enabled", 403
path = request.args.get('path', allowed_dir)
if not os.path.abspath(path).startswith(allowed_dir):
return "Access denied", 403
try:
items = os.listdir(path)
dirs = [os.path.join(path, i) for i in items if os.path.isdir(os.path.join(path, i))]
files_list = [os.path.join(path, i) for i in items if os.path.isfile(os.path.join(path, i))]
except:
dirs = []
files_list = []
html = f'''
<!DOCTYPE html>
<html>
<head>
<title>File Browser</title>
<style>
body {{ font-family: Arial, sans-serif; }}
ul {{ list-style: none; }}
li {{ margin: 5px 0; }}
a {{ text-decoration: none; color: #007bff; cursor: pointer; }}
a:hover {{ text-decoration: underline; }}
</style>
</head>
<body>
<h2>Files in {path}</h2>
<ul>
'''
for d in dirs:
html += f"<li><a href='/files?path={d}'>{os.path.basename(d)}/</a></li>"
for f in files_list:
html += f"<li><a onclick=\"window.opener.document.getElementById('local_path').value='{f}'; window.close();\">{os.path.basename(f)}</a></li>"
html += '''
</ul>
</body>
</html>
'''
return html
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment