repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,256 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+/**
+ * @file Pointer utilities
+ */
+
+#pragma once
+
+#include <cheri.hh>
+#include <concepts>
+
+namespace ds::pointer
+{
+
+ /**
+ * Offset a pointer by an unsigned number of bytes. The return type must be
+ * explicitly specified by the caller.
+ */
+ template<typename T, typename U>
+ static inline __always_inline T *offset(U *base, size_t diff)
+ {
+ return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(base) + diff); | ```suggestion
CHERI::Capability c{base};
c.address() += diff;
return c;
``` |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,256 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+/**
+ * @file Pointer utilities
+ */
+
+#pragma once
+
+#include <cheri.hh>
+#include <concepts>
+
+namespace ds::pointer
+{
+
+ /**
+ * Offset a pointer by an unsigned number of bytes. The return type must be
+ * explicitly specified by the caller.
+ */
+ template<typename T, typename U>
+ static inline __always_inline T *offset(U *base, size_t diff)
+ {
+ return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(base) + diff);
+ }
+
+ /**
+ * Offset a pointer by a signed number of bytes. The return type must be
+ * explicitly specified by the caller.
+ */
+ template<typename T, typename U>
+ static inline __always_inline T *offset_signed(U *base, ptrdiff_t diff) | Is this not a different overload for the second parameter? Does it need a different name? Are there cases where it's ambiguous whether the `size_t` or `ptrdiff_t` version is intended at the call site (if so, please add a comment)? |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,256 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+/**
+ * @file Pointer utilities
+ */
+
+#pragma once
+
+#include <cheri.hh>
+#include <concepts>
+
+namespace ds::pointer
+{
+
+ /**
+ * Offset a pointer by an unsigned number of bytes. The return type must be
+ * explicitly specified by the caller.
+ */
+ template<typename T, typename U>
+ static inline __always_inline T *offset(U *base, size_t diff)
+ {
+ return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(base) + diff);
+ }
+
+ /**
+ * Offset a pointer by a signed number of bytes. The return type must be
+ * explicitly specified by the caller.
+ */
+ template<typename T, typename U>
+ static inline __always_inline T *offset_signed(U *base, ptrdiff_t diff)
+ {
+ return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(base) + diff);
+ }
+
+ /**
+ * Compute the unsigned difference in bytes between two pointers' target
+ * addresses. To be standards-compliant, cursor must be part of the same
+ * allocation as base and at a higher address.
+ */
+ static inline __always_inline size_t diff(const void *base,
+ const void *cursor)
+ {
+ return static_cast<size_t>(reinterpret_cast<const char *>(cursor) -
+ reinterpret_cast<const char *>(base));
+ }
+
+ namespace proxy
+ {
+
+ /**
+ * Proxies<P,T> if P is a proxy object for T*-s.
+ */
+ template<typename P, typename T>
+ concept Proxies = std::same_as<T, typename P::Type> &&
+ requires(P &proxy, T *ptr)
+ {
+ /*
+ * XXX: These are probably none of necessary,
+ * sufficient, or correct.
+ */
+
+ /* Probe for operator=(T*) */
+ {
+ proxy = ptr
+ } -> std::same_as<P &>;
+
+ /* Probe for operator T*() */
+ {
+ ptr == proxy
+ } -> std::same_as<bool>;
+
+ /* TODO: How to probe for operator-> ? */
+ };
+
+ /**
+ * Pointer references are pointer proxies, shockingly enough.
+ */
+ template<typename T>
+ class Pointer
+ {
+ T *&ref;
+
+ __always_inline void set(T *p)
+ {
+ ref = p;
+ }
+
+ public:
+ using Type = T;
+
+ __always_inline Pointer(T *&r) : ref(r) {}
+
+ __always_inline operator T *()
+ {
+ return ref;
+ }
+
+ __always_inline T *operator->()
+ {
+ return *this;
+ }
+
+ __always_inline Pointer<T> &operator=(T *t)
+ {
+ set(t);
+ return *this;
+ }
+
+ __always_inline Pointer<T> &operator=(Pointer const &p)
+ {
+ set(p.ref);
+ return *this;
+ }
+
+ __always_inline bool operator==(Pointer &p)
+ {
+ return this->ref == p.ref;
+ }
+
+ __always_inline auto operator<=>(Pointer &p)
+ {
+ return this->ref <=> p.ref;
+ }
+ };
+ static_assert(Proxies<Pointer<void>, void>);
+
+ /**
+ * Equipped with a context for bounds, an address reference can be a
+ * proxy for a pointer.
+ */
+ template<typename T>
+ class PtrAddr
+ {
+ CHERI::Capability<void> ctx;
+ ptraddr_t &ref;
+
+ public:
+ using Type = T;
+
+ __always_inline PtrAddr(void *c, ptraddr_t &r) : ctx(c), ref(r) {}
+
+ __always_inline operator T *()
+ {
+ return reinterpret_cast<T *>((ctx.address() = ref).ptr());
+ }
+
+ __always_inline T *operator->()
+ {
+ return *this;
+ }
+
+ __always_inline PtrAddr &operator=(T *p)
+ {
+ ref = CHERI::Capability{p}.address();
+ return *this;
+ }
+
+ __always_inline PtrAddr &operator=(PtrAddr const &p)
+ {
+ ref = p.ref;
+ return *this;
+ }
+
+ /*
+ * Since the context is used only for bounds, don't bother
+ * implicitly converting both proxies up to T*
+ */
+
+ __always_inline bool operator==(PtrAddr &p)
+ {
+ return ref == p.ref;
+ }
+
+ __always_inline auto operator<=>(PtrAddr &p)
+ {
+ return ref <=> p.ref;
+ }
+ };
+ static_assert(Proxies<PtrAddr<void>, void>);
+
+ /**
+ * Deduction gude for the common enough case where the context
+ * type and the represented type are equal.
+ */
+ template<typename T>
+ PtrAddr(T *, ptraddr_t) -> PtrAddr<T>;
+
+ /**
+ * Like the above, but with a constant offset on the interpretation of
+ * its addresss fields. This is useful for building points-to-container
+ * data structures (rather than points-to-member as with the above two).
+ * The container_of and address-taking operations that move back and
+ * forth between container and link member should fuse away with the
+ * offsetting operations herein. You may prefer this if your common or
+ * fast-paths involve lots of container_of operations.
+ */
+ template<ptrdiff_t Offset, typename T>
+ class OffsetPtrAddr
+ {
+ CHERI::Capability<void> ctx;
+ ptraddr_t &ref;
+
+ public:
+ using Type = T;
+
+ __always_inline OffsetPtrAddr(void *c, ptraddr_t &r)
+ : ctx(c), ref(r)
+ {
+ }
+
+ __always_inline operator T *()
+ {
+ return reinterpret_cast<T *>( | Can you add a usable `cast<>` method on `CHERI::Capability` if the existing one doesn't work here? |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,75 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+//
+// Imported from snmalloc 4f9d991449380ed7d881a25ba02cc5668c1ff394.
+
+#pragma once
+
+#include <cstdint>
+#include <cstdlib>
+
+namespace ds::xoroshiro
+{
+ namespace detail
+ {
+ template<typename STATE, typename RESULT, STATE A, STATE B, STATE C> | clang-tidy should tell you not to use these names, please can you check why not and fix it? UPPERCASE should be reserved for MACROs (which may have side effects). |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,75 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+//
+// Imported from snmalloc 4f9d991449380ed7d881a25ba02cc5668c1ff394.
+
+#pragma once
+
+#include <cstdint>
+#include <cstdlib>
+
+namespace ds::xoroshiro
+{
+ namespace detail
+ {
+ template<typename STATE, typename RESULT, STATE A, STATE B, STATE C>
+ class XorOshiro
+ {
+ private:
+ static constexpr unsigned StateBits = 8 * sizeof(STATE);
+ static constexpr unsigned ResultBits = 8 * sizeof(RESULT);
+
+ static_assert(StateBits >= ResultBits,
+ "STATE must have at least as many bits as RESULT");
+
+ STATE x;
+ STATE y;
+
+ static inline STATE rotl(STATE x, STATE k)
+ {
+ return (x << k) | (x >> (StateBits - k));
+ }
+
+ public:
+ XorOshiro(STATE x = 5489, STATE y = 0) : x(x), y(y)
+ {
+ // If both zero, then this does not work
+ if (x == 0 && y == 0)
+ abort();
+
+ next();
+ }
+
+ void set_state(STATE nx, STATE ny = 0)
+ {
+ // If both zero, then this does not work
+ if (nx == 0 && ny == 0)
+ abort();
+
+ x = nx;
+ y = ny;
+ next();
+ }
+
+ RESULT next()
+ {
+ STATE r = x + y;
+ y ^= x;
+ x = rotl(x, A) ^ y ^ (y << B);
+ y = rotl(y, C);
+ // If both zero, then this does not work
+ if (x == 0 && y == 0)
+ abort();
+ return r >> (StateBits - ResultBits);
+ }
+ };
+ } // namespace detail
+
+ using P128R64 = detail::XorOshiro<uint64_t, uint64_t, 55, 14, 36>; | What are all of these? Please give them doc comments. |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | mjp41 | @@ -0,0 +1,171 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+/**
+ * @file Ring/circular buffer state machine.
+ */
+
+#pragma once
+
+#include <cdefs.h>
+#include <type_traits>
+
+namespace ds::ring_buffer
+{
+ /**
+ * A statically-sized, non-atomic ring buffer state machine. The actual
+ * element storage must be provided externally; all this does is manage the
+ * cursors. This representation uses an explicit empty flag, rather than
+ * considering equal cursors to be empty, so as to not need an extra element
+ * of store Capacity-many items.
+ *
+ * The type of the cursors is parametric, but must be unsigned.
+ *
+ * The consumer workflow is:
+ * - use head_get() to test emptiness and, if nonempty, read the index
+ * of the head element
+ * - make use of the element in the (external!) storage at that index
+ * - call head_advance() to discard the head element
+ *
+ * The producer workflow is:
+ * - use tail_next() to retrieve the index for the next element,
+ * if there is room
+ * - populate the element in the (external!) storage at that index
+ * - call tail_advance() to make that element available to the
+ * consumer
+ */
+ template<typename Debug, std::size_t Capacity, typename _Ix = std::size_t>
+ class Cursors
+ {
+ static_assert(std::is_arithmetic_v<_Ix> && std::is_unsigned_v<_Ix>,
+ "Ring buffer cursor type must be unsigned arithmetic");
+
+ template<typename... Args>
+ using Assert = typename Debug::template Assert<Args...>;
+
+ public:
+ using Ix = _Ix;
+
+ private:
+ Ix head;
+ Ix tail;
+ bool empty;
+
+ Ix advance(Ix v)
+ {
+ if constexpr ((Capacity & (Capacity - 1)) == 0)
+ {
+ /* For power of two sizes, we can rely on bit masking. */
+ return (v - 1) & (Capacity - 1);
+ }
+ else
+ {
+ /*
+ * For non-power-of-two, we can use unsigned underflow and
+ * signed arithmetic right shift to avoid branching. mask is
+ * all zeros if next is non-negative and all ones otherwise.
+ */
+ Ix next = v - 1;
+ using SIx = std::make_signed_t<Ix>;
+ Ix mask = static_cast<SIx>(next) >> (8 * sizeof(SIx) - 1);
+ return (mask & (Capacity - 1)) | (~mask & next); | It's is unclear to me if this is fast than
```C++
return (v == 0 ? Capacity : v) - 1
```
Is there a conditional move on this platform? |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | mjp41 | @@ -0,0 +1,171 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+/**
+ * @file Ring/circular buffer state machine.
+ */
+
+#pragma once
+
+#include <cdefs.h>
+#include <type_traits>
+
+namespace ds::ring_buffer
+{
+ /**
+ * A statically-sized, non-atomic ring buffer state machine. The actual
+ * element storage must be provided externally; all this does is manage the
+ * cursors. This representation uses an explicit empty flag, rather than
+ * considering equal cursors to be empty, so as to not need an extra element
+ * of store Capacity-many items.
+ *
+ * The type of the cursors is parametric, but must be unsigned.
+ *
+ * The consumer workflow is:
+ * - use head_get() to test emptiness and, if nonempty, read the index
+ * of the head element
+ * - make use of the element in the (external!) storage at that index
+ * - call head_advance() to discard the head element
+ *
+ * The producer workflow is:
+ * - use tail_next() to retrieve the index for the next element,
+ * if there is room
+ * - populate the element in the (external!) storage at that index
+ * - call tail_advance() to make that element available to the
+ * consumer
+ */
+ template<typename Debug, std::size_t Capacity, typename _Ix = std::size_t>
+ class Cursors
+ {
+ static_assert(std::is_arithmetic_v<_Ix> && std::is_unsigned_v<_Ix>,
+ "Ring buffer cursor type must be unsigned arithmetic");
+
+ template<typename... Args>
+ using Assert = typename Debug::template Assert<Args...>;
+
+ public:
+ using Ix = _Ix;
+
+ private:
+ Ix head;
+ Ix tail;
+ bool empty;
+
+ Ix advance(Ix v)
+ {
+ if constexpr ((Capacity & (Capacity - 1)) == 0)
+ {
+ /* For power of two sizes, we can rely on bit masking. */
+ return (v - 1) & (Capacity - 1);
+ }
+ else
+ {
+ /*
+ * For non-power-of-two, we can use unsigned underflow and
+ * signed arithmetic right shift to avoid branching. mask is
+ * all zeros if next is non-negative and all ones otherwise.
+ */
+ Ix next = v - 1;
+ using SIx = std::make_signed_t<Ix>;
+ Ix mask = static_cast<SIx>(next) >> (8 * sizeof(SIx) - 1);
+ return (mask & (Capacity - 1)) | (~mask & next);
+ }
+ }
+
+ public:
+ /**
+ * Reset cursors to an empty state.
+ */
+ void reset()
+ {
+ tail = 0;
+ head = advance(tail);
+ empty = true;
+ }
+
+ /**
+ * Is this ring empty?
+ */
+ __always_inline bool is_empty()
+ {
+ return empty;
+ }
+
+ /**
+ * Try to retrieve the head index; returns true if available and
+ * false otherwise.
+ */
+ bool head_get(Ix &v)
+ {
+ if (is_empty())
+ {
+ return false;
+ }
+
+ v = head;
+ return true;
+ }
+
+ /**
+ * Discard the element at the index returned by head_get().
+ *
+ * Do not call this unless there was a matching call to
+ * head_get() that has returned true.
+ */
+ __always_inline void head_advance()
+ {
+ Assert<>(!empty, "Cannot advance head of empty ring buffer!");
+ if (head == tail)
+ {
+ empty = true;
+ }
+ head = advance(head);
+ }
+
+ /**
+ * Try to retrieve the index of the tail, if nonempty.
+ */
+ bool tail_get(Ix &v)
+ {
+ if (is_empty())
+ {
+ return false;
+ }
+
+ v = tail;
+ return true;
+ }
+
+ /**
+ * Try to retrieve the index beyond the tail, if there is room.
+ * Returns true and sets the index if so, or returns false if
+ * not.
+ */
+
+ bool tail_next(Ix &v) | Not sure I like this name. It reads like an action or getter, not a predicate. |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,268 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+/**
+ * @file Pointer utilities
+ */
+
+#pragma once
+
+#include <cheri.hh>
+#include <concepts>
+
+namespace ds::pointer
+{
+
+ /**
+ * Offset a pointer by a number of bytes. The return type must be
+ * explicitly specified by the caller. The type of the displacement offset
+ * (Offset) is templated so that we can accept both signed and unsigned
+ * offsets.
+ */
+ template<typename T, typename Offset = size_t, typename U>
+ static inline __always_inline T *offset(U *base, Offset offset)
+ {
+ CHERI::Capability c{base};
+ c.address() += offset;
+ return c;
+ }
+
+ /**
+ * Compute the unsigned difference in bytes between two pointers' target
+ * addresses. To be standards-compliant, cursor must be part of the same
+ * allocation as base and at a higher address.
+ */
+ static inline __always_inline size_t diff(const void *base,
+ const void *cursor)
+ {
+ return static_cast<size_t>(reinterpret_cast<const char *>(cursor) -
+ reinterpret_cast<const char *>(base));
+ }
+
+ namespace proxy
+ {
+
+ /**
+ * Proxies<P,T> if P is a proxy object for T*-s.
+ */
+ template<typename P, typename T>
+ concept Proxies = std::same_as<T, typename P::Type> &&
+ requires(P &proxy, P &proxy2, T *ptr)
+ {
+ /* Probe for operator=(T*) */
+ {
+ proxy = ptr
+ } -> std::same_as<P &>;
+
+ /* Probe for operator T*() */
+ {
+ ptr == proxy
+ } -> std::same_as<bool>;
+
+ /* TODO: How to probe for operator-> ? */
+
+ /* Probe for operator==(T*) */
+ {
+ proxy == ptr
+ } -> std::same_as<bool>;
+
+ /* Probe for operator==(P&) */
+ {
+ proxy == proxy2
+ } -> std::same_as<bool>;
+
+ /* Probe for operator<=>(T*) */
+ {
+ proxy <=> ptr
+ } -> std::same_as<std::strong_ordering>;
+
+ /* Probe for operator<=>(P) */
+ {
+ proxy <=> proxy2
+ } -> std::same_as<std::strong_ordering>;
+ };
+
+ /**
+ * Pointer references are pointer proxies, shockingly enough.
+ */
+ template<typename T>
+ class Pointer
+ {
+ T *&ref;
+
+ __always_inline void set(T *p) | This looks redundant. In the proxies in cheri.hh we use a `set` method like this to simplify subclasses, but this is private (not protected) so looks like it's an unnecessary layer of indirection. |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,268 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+/**
+ * @file Pointer utilities
+ */
+
+#pragma once
+
+#include <cheri.hh>
+#include <concepts>
+
+namespace ds::pointer
+{
+
+ /**
+ * Offset a pointer by a number of bytes. The return type must be
+ * explicitly specified by the caller. The type of the displacement offset
+ * (Offset) is templated so that we can accept both signed and unsigned
+ * offsets.
+ */
+ template<typename T, typename Offset = size_t, typename U>
+ static inline __always_inline T *offset(U *base, Offset offset) | ```suggestion
template<typename T, typename U>
static inline __always_inline T *offset(U *base, std::integral auto offset)
```
Not sure if we have the `std::integral` concept, if not then it can be dropped. |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | JerryHsia-MS | @@ -130,53 +127,328 @@ static inline size_t leftshifted_val_msb(size_t val)
// the size of the smallest chunk held in bin with index i
static inline size_t minsize_for_tree_index(BIndex i)
{
- return (1U << ((i >> 1) + TREEBIN_SHIFT)) |
- ((1U & i) << ((i >> 1) + TREEBIN_SHIFT - 1));
+ return (1U << ((i >> 1) + TreeBinShift)) |
+ ((1U & i) << ((i >> 1) + TreeBinShift - 1));
}
-// Isolate the least set bit of a bitmap.
-#define least_bit(x) ((x) & -(x))
-// mask with all bits to left of least bit of x on
-#define left_bits(x) ((x << 1) | -(x << 1))
-// mask with all bits to left of or equal to least bit of x on
-#define same_or_left_bits(x) ((x) | -(x))
-
/**
* The index of the small bin this size should live in.
- * Size 1 to MALLOC_ALIGNMENT live in bin 0, MALLOC_ALIGNMENT + 1 to
- * 2 * MALLOC_ALIGNMENT live in bin 1, etc.
+ * Size 1 to MallocAlignment live in bin 0, MallocAlignment + 1 to
+ * 2 * MallocAlignment live in bin 1, etc.
*/
static inline BIndex small_index(size_t s)
{
- return (s - 1) >> SMALLBIN_SHIFT;
+ return (s - 1) >> SmallBinShift;
}
// Is this a smallbin size?
static inline bool is_small(size_t s)
{
- return small_index(s) < NSMALLBINS;
+ return small_index(s) < NSmallBins;
}
// Convert smallbin index to the size it contains.
static inline size_t small_index2size(BIndex i)
{
- return (static_cast<size_t>(i) + 1) << SMALLBIN_SHIFT;
+ return (static_cast<size_t>(i) + 1) << SmallBinShift;
}
+namespace displacement_proxy
+{
+
+ template<auto F, typename D>
+ concept Decoder = requires(D d)
+ {
+ {
+ F(d)
+ } -> std::same_as<size_t>;
+ };
+
+ template<auto F, typename D>
+ concept Encoder = requires(size_t s)
+ {
+ {
+ F(s)
+ } -> std::same_as<D>;
+ };
+
+ /**
+ * Equipped with a context for bounds, a reference to a displacement can be
+ * a proxy for a pointer.
+ */
+ template<typename T, typename D, bool Positive, auto Decode, auto Encode>
+ requires Decoder<Decode, D> && Encoder<Encode, D>
+ class Proxy
+ {
+ CHERI::Capability<void> ctx;
+ D &d;
+
+ __always_inline void set(T *p)
+ {
+ size_t diff =
+ Positive ? ds::pointer::diff(ctx, p) : ds::pointer::diff(p, ctx);
+ d = Encode(diff);
+ }
+
+ public:
+ using Type = T;
+
+ __always_inline Proxy(void *c, D &r) : ctx(c), d(r) {}
+
+ __always_inline operator T *() const
+ {
+ size_t disp = Decode(d);
+
+ auto p = CHERI::Capability{ctx};
+ auto a = p.address();
+
+ if constexpr (Positive)
+ {
+ a += disp;
+ }
+ else
+ {
+ a -= disp;
+ }
+
+ return reinterpret_cast<T *>(a.ptr());
+ }
+
+ __always_inline T *operator->()
+ {
+ return *this;
+ }
+
+ __always_inline operator ptraddr_t()
+ {
+ return *this;
+ }
+
+ __always_inline Proxy &operator=(T *p)
+ {
+ set(p);
+ return *this;
+ }
+
+ __always_inline Proxy &operator=(Proxy const &p)
+ {
+ set(p);
+ return *this;
+ }
+
+ __always_inline bool operator==(Proxy const &p) const
+ {
+ return static_cast<T *>(*this) == static_cast<T *>(p);
+ }
+
+ __always_inline auto operator<=>(Proxy const &p) const
+ {
+ return static_cast<T *>(*this) <=> static_cast<T *>(p);
+ }
+ };
+
+ static_assert(ds::pointer::proxy::Proxies<
+ Proxy<void, SmallSize, false, head2size, size2head>,
+ void>);
+
+} // namespace displacement_proxy
+
/**
- * When chunks are not in use, they are treated as nodes of either
+ * Every chunk, in use or not, includes a minimal header. That is, this is a
+ * classic malloc, not something like a slab or sizeclass allocator or a
+ * "BIBOP"-inspired design.
+ *
+ * This header uses relative displacements to refer to the address-order
+ * predecessor and successor adjacent headers. The details of encoding are
+ * encapsulated using the displacement_proxy::Proxy above and the
+ * cell_{next,prev} methods herein.
+ *
+ * Chunks are in one of three states:
+ *
+ * - Allocated / "In Use" by the application
+ *
+ * - Not indexed by any other structures in the MState
+ *
+ * - Quarantined (until revocation scrubs inward pointers from the system)
+ *
+ * - Collected in a quarantine ring using the MChunk::ring linkages
+ *
+ * - Free for allocation
+ *
+ * - Collected in a smallbin ring (using MChunk::ring) or in a treebin
+ * ring (using either/both the TChunk and MChunk::ring links).
+ */
+struct __packed __aligned(MallocAlignment)
+MChunkHeader
+{
+ /**
+ * Compressed size of the predecessor chunk. See cell_prev().
+ */
+ SmallSize sprev; | Very nit: `sprev` and `shead` used to contain both size and other metadata bits. Now they are just sizes, we can give them better names like `prevSize` and `currSize` if it doesn't require too many changes. |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | JerryHsia-MS | @@ -130,53 +127,328 @@ static inline size_t leftshifted_val_msb(size_t val)
// the size of the smallest chunk held in bin with index i
static inline size_t minsize_for_tree_index(BIndex i)
{
- return (1U << ((i >> 1) + TREEBIN_SHIFT)) |
- ((1U & i) << ((i >> 1) + TREEBIN_SHIFT - 1));
+ return (1U << ((i >> 1) + TreeBinShift)) |
+ ((1U & i) << ((i >> 1) + TreeBinShift - 1));
}
-// Isolate the least set bit of a bitmap.
-#define least_bit(x) ((x) & -(x))
-// mask with all bits to left of least bit of x on
-#define left_bits(x) ((x << 1) | -(x << 1))
-// mask with all bits to left of or equal to least bit of x on
-#define same_or_left_bits(x) ((x) | -(x))
-
/**
* The index of the small bin this size should live in.
- * Size 1 to MALLOC_ALIGNMENT live in bin 0, MALLOC_ALIGNMENT + 1 to
- * 2 * MALLOC_ALIGNMENT live in bin 1, etc.
+ * Size 1 to MallocAlignment live in bin 0, MallocAlignment + 1 to
+ * 2 * MallocAlignment live in bin 1, etc.
*/
static inline BIndex small_index(size_t s)
{
- return (s - 1) >> SMALLBIN_SHIFT;
+ return (s - 1) >> SmallBinShift;
}
// Is this a smallbin size?
static inline bool is_small(size_t s)
{
- return small_index(s) < NSMALLBINS;
+ return small_index(s) < NSmallBins;
}
// Convert smallbin index to the size it contains.
static inline size_t small_index2size(BIndex i)
{
- return (static_cast<size_t>(i) + 1) << SMALLBIN_SHIFT;
+ return (static_cast<size_t>(i) + 1) << SmallBinShift;
}
+namespace displacement_proxy
+{
+
+ template<auto F, typename D>
+ concept Decoder = requires(D d)
+ {
+ {
+ F(d)
+ } -> std::same_as<size_t>;
+ };
+
+ template<auto F, typename D>
+ concept Encoder = requires(size_t s)
+ {
+ {
+ F(s)
+ } -> std::same_as<D>;
+ };
+
+ /**
+ * Equipped with a context for bounds, a reference to a displacement can be
+ * a proxy for a pointer.
+ */
+ template<typename T, typename D, bool Positive, auto Decode, auto Encode>
+ requires Decoder<Decode, D> && Encoder<Encode, D>
+ class Proxy
+ {
+ CHERI::Capability<void> ctx;
+ D &d;
+
+ __always_inline void set(T *p)
+ {
+ size_t diff =
+ Positive ? ds::pointer::diff(ctx, p) : ds::pointer::diff(p, ctx);
+ d = Encode(diff);
+ }
+
+ public:
+ using Type = T;
+
+ __always_inline Proxy(void *c, D &r) : ctx(c), d(r) {}
+
+ __always_inline operator T *() const
+ {
+ size_t disp = Decode(d);
+
+ auto p = CHERI::Capability{ctx};
+ auto a = p.address();
+
+ if constexpr (Positive)
+ {
+ a += disp;
+ }
+ else
+ {
+ a -= disp;
+ }
+
+ return reinterpret_cast<T *>(a.ptr());
+ }
+
+ __always_inline T *operator->()
+ {
+ return *this;
+ }
+
+ __always_inline operator ptraddr_t()
+ {
+ return *this;
+ }
+
+ __always_inline Proxy &operator=(T *p)
+ {
+ set(p);
+ return *this;
+ }
+
+ __always_inline Proxy &operator=(Proxy const &p)
+ {
+ set(p);
+ return *this;
+ }
+
+ __always_inline bool operator==(Proxy const &p) const
+ {
+ return static_cast<T *>(*this) == static_cast<T *>(p);
+ }
+
+ __always_inline auto operator<=>(Proxy const &p) const
+ {
+ return static_cast<T *>(*this) <=> static_cast<T *>(p);
+ }
+ };
+
+ static_assert(ds::pointer::proxy::Proxies<
+ Proxy<void, SmallSize, false, head2size, size2head>,
+ void>);
+
+} // namespace displacement_proxy
+
/**
- * When chunks are not in use, they are treated as nodes of either
+ * Every chunk, in use or not, includes a minimal header. That is, this is a
+ * classic malloc, not something like a slab or sizeclass allocator or a
+ * "BIBOP"-inspired design.
+ *
+ * This header uses relative displacements to refer to the address-order
+ * predecessor and successor adjacent headers. The details of encoding are
+ * encapsulated using the displacement_proxy::Proxy above and the
+ * cell_{next,prev} methods herein.
+ *
+ * Chunks are in one of three states:
+ *
+ * - Allocated / "In Use" by the application
+ *
+ * - Not indexed by any other structures in the MState
+ *
+ * - Quarantined (until revocation scrubs inward pointers from the system)
+ *
+ * - Collected in a quarantine ring using the MChunk::ring linkages
+ *
+ * - Free for allocation
+ *
+ * - Collected in a smallbin ring (using MChunk::ring) or in a treebin
+ * ring (using either/both the TChunk and MChunk::ring links).
+ */
+struct __packed __aligned(MallocAlignment)
+MChunkHeader
+{
+ /**
+ * Compressed size of the predecessor chunk. See cell_prev().
+ */
+ SmallSize sprev;
+ /**
+ * Compressed size of this chunk. See cell_next().
+ */
+ SmallSize shead;
+
+ bool isPrevInUse : 1;
+ bool isCurrInUse : 1;
+
+ /* There are 30 bits free in the header here for future use */
+
+ public:
+ __always_inline auto cell_prev()
+ {
+ return displacement_proxy::
+ Proxy<MChunkHeader, SmallSize, false, head2size, size2head>(this,
+ sprev);
+ }
+
+ __always_inline auto cell_next()
+ {
+ return displacement_proxy::
+ Proxy<MChunkHeader, SmallSize, true, head2size, size2head>(this,
+ shead);
+ }
+
+ /**
+ * Erase the header fields
+ */
+ __always_inline void clear()
+ {
+ /*
+ * This is spelled slightly oddly as using memset results in a call
+ * rather than a single store instruction.
+ */
+ static_assert(sizeof(*this) == sizeof(uintptr_t));
+ *reinterpret_cast<uintptr_t *>(this) = 0;
+ }
+
+ bool is_in_use()
+ {
+ return isCurrInUse;
+ }
+
+ bool is_prev_in_use()
+ {
+ return isPrevInUse;
+ }
+
+ // size of the previous chunk
+ size_t prevsize_get()
+ {
+ return head2size(sprev);
+ }
+
+ // size of this chunk
+ size_t size_get()
+ {
+ return head2size(shead);
+ }
+
+ void mark_in_use()
+ {
+ isCurrInUse = true;
+ cell_next()->isPrevInUse = true;
+ }
+
+ void mark_free()
+ {
+ isCurrInUse = false;
+ cell_next()->isPrevInUse = false;
+ }
+
+ /**
+ * Land a new header somewhere within an existing chunk.
+ *
+ * The resulting header inherits its in-use status from this one, which
+ * leaves consistent the "previous in use" bits of both this new header and
+ * the successor header, but this can violate other invariants of the
+ * system. In particular, if this is a free chunk, then the result will be
+ * two free chunks in a row; the caller is expected to fix this by
+ * marking at least one of the two split chunks as in-use.
+ */
+ MChunkHeader *split(size_t offset)
+ {
+ auto newnext = ds::pointer::offset<MChunkHeader>(this, offset);
+
+ newnext->clear();
+
+ ds::linked_list::emplace_after(this, newnext);
+ newnext->isCurrInUse = newnext->isPrevInUse = isCurrInUse;
+
+ return newnext;
+ }
+
+ /**
+ * Build an initial pair of chunk headers. The returned header is at the
+ * indicated base and is suitable for installation into a free list (or
+ * tree). The other header is a sentinel of sorts, at the end of the
+ * indicated span of memory. To prevent the system from attempting to walk
+ * beyond these bounds, ficitious "in use" bits are set true: the first
+ * chunk claims that its predecessor is in use and the second claims that
+ * it itself is.
+ *
+ * This function is marked always-inlined as it is called exactly once.
+ */
+ __always_inline static MChunkHeader *make(void *base, size_t size)
+ {
+ size -= sizeof(MChunkHeader);
+
+ auto first = static_cast<MChunkHeader *>(base);
+ first->clear();
+ first->shead = size2head(size); | Does this overflow into the header word right after `base + size`, instead of placing the fake footer header at the end of `base + size`? |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | JerryHsia-MS | @@ -423,53 +680,63 @@ class __packed __aligned(MALLOC_ALIGNMENT) MChunk
}
#endif
- // Write the revocation epoch into the header.
- void epoch_write()
+ /**
+ * Erase the MChunk-specific metadata of this chunk (specifically, ring)
+ * without changing its header.
+ */
+ void metadata_clear()
{
- epoch_enq = revoker.system_epoch_get();
+ static_assert(sizeof(*this) == sizeof(MChunkHeader) + sizeof(ring));
+ /*
+ * This is spelled slightly oddly as using memset results in a call
+ * rather than a single store instruction.
+ */
+ static_assert(sizeof(ring) == sizeof(uintptr_t));
+ *reinterpret_cast<uintptr_t *>(&this->ring) = 0; | Does `capaligned_zero()` help? I wonder if the compiler is clever enough to collapse it into a single cap store. |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | JerryHsia-MS | @@ -489,24 +757,127 @@ class __packed __aligned(MALLOC_ALIGNMENT) TChunk : public MChunk
TChunk *parent;
// the tree index this chunk is in
BIndex index;
+ /*
+ * There's padding to alignment here, so if we needed more metadata, it
+ * could be "free", in spatial terms.
+ *
+ * This padding doesn't break our targeted zeroing in metadata_clear()
+ * because said padding will be zeroed before we view the chunk as a TChunk
+ * and we won't store to it.
+ */
+
+ TChunk *leftmost_child()
+ {
+ if (child[0] != nullptr)
+ return child[0];
+ return child[1];
+ }
+
+ static constexpr uintptr_t RingParent = 0;
+ static constexpr uintptr_t RootParent = 1;
+
+ bool is_root()
+ {
+ return reinterpret_cast<uintptr_t>(parent) == RootParent;
+ }
+ void mark_root()
+ {
+ parent = reinterpret_cast<TChunk *>(RootParent);
+ }
+
+ bool is_tree_ring()
+ {
+ return parent == reinterpret_cast<TChunk *>(RingParent);
+ }
+ void mark_tree_ring() | Nit: could benefit from more comments here (although the comments before this PR were already lacking). I think this is called for tree chunks that are not the direct child of a parent? |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | JerryHsia-MS | @@ -1618,57 +2009,103 @@ class MState
*
* Note that this chunk does not have to come from quarantine, because it
* can come from initialisation or splitting a free chunk.
+ *
+ * Initializes the linkages of p.
*/
void mspace_free_internal(MChunk *p)
{
ok_in_use_chunk(p);
- size_t psize = 0, psizeold = 0;
- if (RTCHECK(ok_address(p->ptr()) && p->ok_in_use()))
- {
- // Clear the shadow bits.
- revoker.shadow_paint_range(
- chunk2mem(p).address(), p->chunk_next()->ptr(), false);
- psize = p->size_get();
- psizeold = psize;
- MChunk *current = p;
- MChunk *next = p->chunk_next();
- if (!p->is_prev_in_use())
+
+ // Clear the shadow bits.
+ revoker.shadow_paint_range(
+ chunk2mem(p).address(), p->chunk_next()->ptr(), false);
+
+ heapFreeSize += p->size_get();
+
+ if (!p->is_prev_in_use())
+ {
+ // Consolidate backward
+ MChunk *prev = p->chunk_prev();
+ unlink_chunk(prev, prev->size_get());
+ ds::linked_list::unsafe_remove_link(&prev->header, &p->header);
+ p->header.clear();
+ p = prev;
+ }
+
+ MChunk *next = p->chunk_next(); | At this point, if `prev` is not in use, have we updated the size field to include both `p` and `prev` so that `p->chunk_next()` can work?
If not, I think we should move this line above `is_prev_in_use()` so that `chunk_next()` is valid. |
cheriot-rtos | github_2023 | cpp | 1 | CHERIoT-Platform | JerryHsia-MS | @@ -1618,57 +2009,103 @@ class MState
*
* Note that this chunk does not have to come from quarantine, because it
* can come from initialisation or splitting a free chunk.
+ *
+ * Initializes the linkages of p.
*/
void mspace_free_internal(MChunk *p)
{
ok_in_use_chunk(p);
- size_t psize = 0, psizeold = 0;
- if (RTCHECK(ok_address(p->ptr()) && p->ok_in_use()))
- {
- // Clear the shadow bits.
- revoker.shadow_paint_range(
- chunk2mem(p).address(), p->chunk_next()->ptr(), false);
- psize = p->size_get();
- psizeold = psize;
- MChunk *current = p;
- MChunk *next = p->chunk_next();
- if (!p->is_prev_in_use())
+
+ // Clear the shadow bits.
+ revoker.shadow_paint_range(
+ chunk2mem(p).address(), p->chunk_next()->ptr(), false);
+
+ heapFreeSize += p->size_get();
+
+ if (!p->is_prev_in_use())
+ {
+ // Consolidate backward
+ MChunk *prev = p->chunk_prev();
+ unlink_chunk(prev, prev->size_get());
+ ds::linked_list::unsafe_remove_link(&prev->header, &p->header);
+ p->header.clear();
+ p = prev;
+ }
+
+ MChunk *next = p->chunk_next();
+ if (!next->is_in_use())
+ {
+ // Consolidate forward
+ unlink_chunk(next, next->size_get());
+ ds::linked_list::unsafe_remove_link(&p->header, &next->header);
+ next->header.clear();
+ }
+
+ p->in_use_clear();
+ insert_chunk(p, p->size_get());
+ ok_free_chunk(p);
+ }
+
+ /**
+ * Move a pending quarantine ring whose epoch is now past onto the finished
+ * quarantine ring.
+ */
+ void quarantine_pending_to_finished()
+ {
+ if (quarantinePendingRing.is_empty())
+ {
+ for (size_t ix = 0; ix < QuarantineRings; ix++)
{
- size_t prevsize = p->prevsize_get();
- MChunk *prev = p->chunk_prev();
- psize += prevsize;
- p = prev;
- if (RTCHECK(ok_address(prev->ptr())))
- { // Consolidate backward.
- unlink_chunk(p, prevsize);
- metadata_zero<true>(current);
- }
- else
- {
- goto erroraction;
- }
+ Debug::Assert(quarantine_pending_get(ix)->is_empty(),
+ "Empty quarantine with non-empty ring!");
}
+ }
- if (RTCHECK(p->ok_next(next) && next->ok_prev_in_use()))
- {
- if (!next->is_in_use()) // Consolidate forward.
- {
- size_t nsize = next->size_get();
- psize += nsize;
- unlink_chunk(next, nsize);
- metadata_zero<true>(next);
- }
- p->free_chunk_set(psize);
+ decltype(quarantinePendingRing)::Ix oldestPendingIx;
+ if (!quarantinePendingRing.head_get(oldestPendingIx))
+ {
+ return;
+ }
- insert_chunk(p, psize);
- ok_free_chunk(p);
- goto postaction;
- }
+ if (!revoker.has_revocation_finished_for_epoch(
+ quarantinePendingEpoch[oldestPendingIx]))
+ {
+ return;
}
- erroraction:
- corruption_error_action();
- postaction:
- heapFreeSize += psizeold;
+
+ auto qring = quarantine_pending_get(oldestPendingIx);
+
+ /*
+ * It can happen that this ring is empty, because everything that was | Is this still true? |
cheriot-rtos | github_2023 | others | 10 | CHERIoT-Platform | rmn30 | @@ -333,10 +336,10 @@ exception_entry_asm:
LoadCapPCC cs0, compartment_switcher_sealing_key
// ca2 at this point was loaded by .Lpop_trusted_stack_frame from the pcc | Looks like this comment is now out of date. Should it say `cra` instead? |
cheriot-rtos | github_2023 | others | 491 | CHERIoT-Platform | davidchisnall | @@ -24,7 +24,7 @@ namespace Ibex
{
class HardwareRevoker
{
- private:
+ public: | I don’t like making these fields public just for a benchmark. What API are we missing? |
ghidra-emotionengine-reloaded | github_2023 | java | 62 | chaoticgd | VelocityRa | @@ -0,0 +1,422 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.emotionengine;
+
+import java.math.BigInteger;
+
+import ghidra.app.services.*;
+import ghidra.app.util.importer.MessageLog;
+import ghidra.program.disassemble.Disassembler;
+import ghidra.program.model.address.*;
+import ghidra.program.model.lang.Processor;
+import ghidra.program.model.lang.Register;
+import ghidra.program.model.listing.*;
+import ghidra.program.model.mem.MemoryAccessException;
+import ghidra.program.model.mem.MemoryBlock;
+import ghidra.program.model.scalar.Scalar;
+import ghidra.program.model.symbol.FlowType;
+import ghidra.util.Msg;
+import ghidra.util.exception.CancelledException;
+import ghidra.util.task.TaskMonitor;
+
+public class MipsR5900PreAnalyzer extends AbstractAnalyzer { | does this file need to be copy-pasted from upstream btw? seems maybe you could just inherit `MipsR5900PreAnalyzer` and override `canAnalyze` |
pg2 | github_2023 | java | 45 | igrishaev | jgdavey | @@ -1108,26 +1111,65 @@ private void handlePortalSuspended (final PortalSuspended msg, final Result res)
}
private void handlerCall (final IFn f, final Object arg) {
- if (f != null) {
- Agent.soloExecutor.submit(() -> {
- f.invoke(arg);
- });
- }
+ config.executor().submit(() -> {
+ f.invoke(arg);
+ });
}
private void handleNotificationResponse (final NotificationResponse msg, final Result res) {
+ res.incNotificationCount();
// Sometimes, it's important to know whether a notification
// was triggered by the current connection or another.
final boolean isSelf = msg.pid() == pid;
- res.incNotificationCount();
- handlerCall(
- config.fnNotification(),
- msg.toClojure().assoc(KW.self_QMARK, isSelf)
- );
+ final Object obj = msg.toClojure().assoc(KW.self_QMARK, isSelf);
+ final IFn handler = config.fnNotification();
+ if (handler == null) {
+ notifications.add(obj);
+ } else {
+ handlerCall(handler, obj);
+ }
}
private void handleNoticeResponse (final NoticeResponse msg) {
- handlerCall(config.fnNotice(), msg.toClojure());
+ final IFn handler = config.fnNotice();
+ final Object obj = msg.toClojure();
+ if (handler == null) {
+ notices.add(obj);
+ } else {
+ handlerCall(handler, obj);
+ }
+ }
+
+ @SuppressWarnings("unused")
+ public boolean hasNotifications() {
+ try (final TryLock ignored = lock.get()) {
+ return !notifications.isEmpty();
+ }
+ }
+
+ @SuppressWarnings("unused")
+ public boolean hasNotices() {
+ try (final TryLock ignored = lock.get()) {
+ return !notices.isEmpty();
+ }
+ }
+
+ @SuppressWarnings("unused")
+ public IPersistentVector drainNotifications() {
+ try (final TryLock ignored = lock.get()) {
+ final IPersistentVector result = PersistentVector.create(notifications);
+ notifications = Collections.emptyList(); | I believe that `emptyList` returns an immutable list. We'd probably want to use `notifications.clear()` here. |
pg2 | github_2023 | java | 45 | igrishaev | jgdavey | @@ -1366,6 +1408,14 @@ public void notify (final String channel, final String message) {
}
}
+ @SuppressWarnings("unused")
+ public void notifyJSON (final String channel, final Object data) {
+ try (TryLock ignored = lock.get()) {
+ final String payload = JSON.writeValueToString(config.objectMapper(), data);
+ notify(channel, payload);
+ }
+ }
+ | This will be very convenient! |
pg2 | github_2023 | java | 45 | igrishaev | jgdavey | @@ -1108,26 +1111,65 @@ private void handlePortalSuspended (final PortalSuspended msg, final Result res)
}
private void handlerCall (final IFn f, final Object arg) {
- if (f != null) {
- Agent.soloExecutor.submit(() -> {
- f.invoke(arg);
- });
- }
+ config.executor().submit(() -> {
+ f.invoke(arg);
+ });
}
private void handleNotificationResponse (final NotificationResponse msg, final Result res) {
+ res.incNotificationCount(); | I wonder if we'll still care about this after the new notify stuff is in place? |
pg2 | github_2023 | java | 45 | igrishaev | jgdavey | @@ -1108,26 +1111,65 @@ private void handlePortalSuspended (final PortalSuspended msg, final Result res)
}
private void handlerCall (final IFn f, final Object arg) {
- if (f != null) {
- Agent.soloExecutor.submit(() -> {
- f.invoke(arg);
- });
- }
+ config.executor().submit(() -> {
+ f.invoke(arg);
+ });
}
private void handleNotificationResponse (final NotificationResponse msg, final Result res) {
+ res.incNotificationCount();
// Sometimes, it's important to know whether a notification
// was triggered by the current connection or another.
final boolean isSelf = msg.pid() == pid;
- res.incNotificationCount();
- handlerCall(
- config.fnNotification(),
- msg.toClojure().assoc(KW.self_QMARK, isSelf)
- );
+ final Object obj = msg.toClojure().assoc(KW.self_QMARK, isSelf);
+ final IFn handler = config.fnNotification();
+ if (handler == null) {
+ notifications.add(obj);
+ } else {
+ handlerCall(handler, obj);
+ } | Yeah, this seems like a good pattern to me. |
pg2 | github_2023 | java | 36 | igrishaev | igrishaev | @@ -11,11 +12,16 @@
public class SocketTool {
| Here, there is a thing that looks so-so: coupling SocketTool and Config classes. Is that possible to fix it such that SocketTool accepts options as primitives?
|
pg2 | github_2023 | java | 39 | igrishaev | igrishaev | @@ -141,7 +141,7 @@ private void setInputStream(final InputStream in) {
private void setOutputStream(final OutputStream out) {
final int len = config.outStreamBufSize(); | A minor issue I spotted while working on this branch. |
pg2 | github_2023 | java | 39 | igrishaev | igrishaev | @@ -0,0 +1,17 @@
+package org.pg.error; | @jgdavey Sorry for letting you wait for such long. The PR looks good, and I made a small change. Briefly, I'd like `PGError` class to be the root of all `PG...` exceptions. Second, I renamed `PGIOException` to `PGErrorIO`, because it follows the pattern: `PGError<Subdomain>`, for example `PGErrorResponse` = `PGError` + `Response`. |
pg2 | github_2023 | java | 35 | igrishaev | igrishaev | @@ -49,6 +51,7 @@ public final class Connection implements AutoCloseable {
private String unixSocketPath;
private InputStream inStream;
private OutputStream outStream;
+ private AsynchronousSocketChannel sockCh; | I might be wrong, but it looks like the `sockCh` field is not needed here. We store both input and output streams, and a raw socket object for possible SSL upgrade. So I think this reference can be skipped.
|
pg2 | github_2023 | java | 35 | igrishaev | igrishaev | @@ -140,10 +143,12 @@ private void setOutputStream(final OutputStream out) {
outStream = new BufferedOutputStream(out, len);
}
- private SocketChannel connectSocket(final SocketAddress address) {
- final SocketChannel channel = SocketTool.open(address);
+ private AsynchronousSocketChannel connectSocket(final SocketAddress address) {
+ final AsynchronousSocketChannel channel = SocketTool.open(address);
+ setSocketOptions(channel, config);
setInputStream(Channels.newInputStream(channel));
setOutputStream(Channels.newOutputStream(channel));
+ this.sockCh = channel; | (the same) |
pg2 | github_2023 | java | 35 | igrishaev | igrishaev | @@ -204,13 +209,13 @@ private void initTypeMapping() {
}
- private static void setSocketOptions(final Socket socket, final Config config) {
+ private static void setSocketOptions(final AsynchronousSocketChannel channel, final Config config) {
try {
- socket.setTcpNoDelay(config.SOTCPnoDelay());
- socket.setSoTimeout(config.SOTimeout());
- socket.setKeepAlive(config.SOKeepAlive());
- socket.setReceiveBufferSize(config.SOReceiveBufSize());
- socket.setSendBufferSize(config.SOSendBufSize());
+ channel.setOption(StandardSocketOptions.TCP_NODELAY, config.SOTCPnoDelay());
+ //channel.setOption(StandardSocketOptions., config.SOTimeout()); | I tried AsyncSocket object in the past, and it confused me that there is no a timeout option (see below). |
pg2 | github_2023 | java | 35 | igrishaev | igrishaev | @@ -5,14 +5,20 @@
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
+import java.util.concurrent.Future;
+import java.util.concurrent.ExecutionException;
+import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.SocketChannel;
public class SocketTool {
- public static SocketChannel open (final SocketAddress address) {
+ public static AsynchronousSocketChannel open (final SocketAddress address) {
try {
- return SocketChannel.open(address);
- } catch (IOException e) {
+ final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+ Future result = ch.connect(address);
+ result.get(); | Since there is no a timeout option for async channel, it looks like we need to `.get` by timeout passing an amount ms, for example:
`result.get(config.SOTimeout(), TimeUnits/MILLISECONDS)`
This will imitate a socket timeout behaviour.
|
pg2 | github_2023 | java | 35 | igrishaev | igrishaev | @@ -1412,4 +1414,15 @@ public int pollNotifications() {
}
}
| Hm, this method looks a bit strange to me. There is already a method called `pollNotifications` in the Connection class and its Clojure wrapper in `pg.core`. This method does the same but without an endless loop.
The question is, if someone runs this method, how will he or she exit from it? The only answer is to press Ctrl-C or send any kind of a posix signal, which is a bit strange.
Also, an endless loop that fires empty queries without a timeout is not good for the server. I do believe that notifications should be checked periodically, say 1 time each 15-30 seconds but not as fast as JVM allows it.
I think, the same can be achieved by running
```
(while true
(pg/poll-notifications conn))
```
in REPL, but again, it's a bit questionable.
|
pg2 | github_2023 | java | 35 | igrishaev | igrishaev | @@ -5,14 +5,20 @@
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
+import java.util.concurrent.Future;
+import java.util.concurrent.ExecutionException;
+import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.SocketChannel;
public class SocketTool {
- public static SocketChannel open (final SocketAddress address) {
+ public static AsynchronousSocketChannel open (final SocketAddress address) {
try {
- return SocketChannel.open(address);
- } catch (IOException e) {
+ final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+ Future result = ch.connect(address);
+ result.get();
+ return ch;
+ } catch (IOException | InterruptedException | ExecutionException e) {
throw new PGError(e, "cannot open socket, address: %s", address); | The last comment about performance. I tried async sockets before, but they not even showed much benefit, but rather slowed down performance. I'm not an expert in Java IO either, but it looks like plain sockets may gain more performance in blocking mode.
I run some benchmarks on master and this branch on two machines, and this is what I got:
```
------------------------------
pg select many fields NO ASSOC
------------------------------
Macbook M3 pro ARM
--------------
master:
Execution time mean 92.434045, 95.042204, 95.122389 ms
async-io
Execution time mean 96.308774, 96.334104, 97.116729 ms
Macbook core i5 Intel
---------------------
master
Execution time mean 169.48, 195.069, 164.71 ms
async-io
Execution time mean 206.72, 173.86, 192.81 ms
```
|
pg2 | github_2023 | others | 34 | igrishaev | igrishaev | @@ -0,0 +1,145 @@
+(ns pg.connection-uri | I had a draft version of URI parser in my drafts, and I pushed it here just for context. |
pg2 | github_2023 | others | 34 | igrishaev | igrishaev | @@ -0,0 +1,145 @@
+(ns pg.connection-uri
+ (:require
+ [clojure.string :as str])
+ (:import
+ (java.net URI)))
+
+(set! *warn-on-reflection* true)
+
+(defmacro error! [template & args]
+ `(throw (new Exception (format ~template ~@args))))
+
+(defn parse-query-bool ^Boolean [^String line]
+ (case (str/lower-case line)
+ "" nil
+ ("true" "on" "1" "yes") true
+ ("false" "off" "0" "no") false
+ (error! "cannot parse boolean value: %s" line)))
+
+(defn parse-query-long ^Long [^String line]
+ (case line
+ "" nil
+ (try
+ (Long/parseLong line)
+ (catch Exception e
+ (error! "cannot parse long value: %s, reason: %s"
+ line (ex-message e))))))
+ | This function does most of the things. I thing we only need to extend it with query options. |
pg2 | github_2023 | others | 34 | igrishaev | igrishaev | @@ -263,10 +263,12 @@
(defn ->config
"
- Turn a Clojure map into an instance of Config.Builder.
+ Turn a Clojure map into an instance of Config via Config.Builder
"
- ^Config$Builder [params]
-
+ ^Config [params] | I think it's OK to have both URI and other params at once, no need to throw an error. My idea was to parse the URI, if it passed, and get a map of config from it. And then, merge it with the rest of the top-level config, or vice versa.
|
pg2 | github_2023 | others | 34 | igrishaev | igrishaev | @@ -0,0 +1,88 @@
+(ns pg.config-test | Thank you for adding tests, very appreciated.
|
pg2 | github_2023 | java | 34 | igrishaev | igrishaev | @@ -107,6 +114,98 @@ public Builder(final String user, final String database) {
this.pgParams.put("application_name", Const.APP_NAME);
}
+ | My main concern is the following: in your PR, we build a Config object either from a URI line, or from a Clojure map. But I'm afraid that it's not possible to pass all the objects through the URI. Thus, maybe it's better to merge settings, namely:
1. if connection-uri is passed, parse it and get a map;
2. merge it with the rest options;
3. pass the final map into the `->config` function.
|
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -74,54 +72,38 @@ are plain strings:
(pg/connect config+))
~~~
-## Connection parameters
-
-The following table describes all the possible connection options with the
-possible values and semantics. Only the two first options are requred. All the
-rest have predefined values.
-
-| Field | Type | Default | Comment |
-|------------------------|--------------|--------------------|---------------------------------------------------------------------------------|
-| `:user` | string | **required** | the name of the DB user |
-| `:database` | string | **required** | the name of the database |
-| `:host` | string | 127.0.0.1 | IP or hostname |
-| `:port` | integer | 5432 | port number |
-| `:password` | string | "" | DB user password |
-| `:pg-params` | map | {} | A map of session params like {string string} |
-| `:binary-encode?` | bool | false | Whether to use binary data encoding |
-| `:binary-decode?` | bool | false | Whether to use binary data decoding |
-| `:read-only?` | bool | false | Whether to initiate this connection in READ ONLY mode (see below) |
-| `:in-stream-buf-size` | integer | 0xFFFF | Size of the input buffered socket stream |
-| `:out-stream-buf-size` | integer | 0xFFFF | Size of the output buffered socket stream |
-| `:fn-notification` | 1-arg fn | logging fn | A function to handle notifications |
-| `:fn-protocol-version` | 1-arg fn | logging fn | A function to handle negotiation version protocol event |
-| `:fn-notice` | 1-arg fn | logging fn | A function to handle notices |
-| `:use-ssl?` | bool | false | Whether to use SSL connection |
-| `:ssl-context` | SSLContext | nil | An custom instance of `SSLContext` class to wrap a socket |
-| `:so-keep-alive?` | bool | true | Socket KeepAlive value |
-| `:so-tcp-no-delay?` | bool | true | Socket TcpNoDelay value |
-| `:so-timeout` | integer | 15.000 | Socket timeout value, in ms |
-| `:so-recv-buf-size` | integer | 0xFFFF | Socket receive buffer size |
-| `:so-send-buf-size` | integer | 0xFFFF | Socket send buffer size |
-| `:cancel-timeout-ms` | integer | 5.000 | Default value for the `with-timeout` macro, in ms |
-| `:protocol-version` | integer | 196608 | Postgres protocol version |
-| `:object-mapper` | ObjectMapper | JSON.defaultMapper | An instance of ObjectMapper for custom JSON processing (see the "JSON" section) |
-
-### Parameter notes
-
-#### Read Only Mode
-
-The `:read-only?` connection parameter does two things under the hood:
-
-1. It appends the `default_transaction_read_only` parameter to the startup
- message set to `on`. Thus, any transaction gets started on `READ ONLY` mode.
-
-2. It prevents the `:read-only?` flag from overriding in the `with-tx`
- macro. Say, even if the macro is called like this:
-
-~~~clojure
-(pg/with-tx [conn {:read-only? false}] ;; try to mute the global :read-only? flag
- (pg/query conn "delete from students"))
-~~~
-
-The transaction will be in `READ ONLY` mode anyway. | Personally I wouldn't like to drop out this fragment. Can you get it back please? The phrasing you proposed is too short and I'm afraid the context will be lost.
|
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -1,23 +1,23 @@
# Arrays support
-In JDBC, arrays have always been a pain. Every time you're about to pass an | Here and below: I don't think these commas should be removed. The "In JDBC" clause in the introductory, and thus must be separated with comma. That's the number 2 point from this guide:
https://www.brandeis.edu/writing-program/resources/students/academic/style-grammar/comma-rules.html
But can you change my mind?
|
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -1,39 +1,30 @@
-# PG2: A *Fast* PostgreSQL Driver For Clojure | Why did you remove A? It relates to the "Driver" noun which is mentioned the first time.
|
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -1,39 +1,30 @@
-# PG2: A *Fast* PostgreSQL Driver For Clojure
+# PG2: *Fast* PostgreSQL driver for Clojure
-[pg]: https://github.com/igrishaev/pg
+`PG2` is a JDBC-free PostgreSQL client library.
-PG2 is a client library for PostgreSQL server. It succeeds [PG(one)][pg] -- my
-early attempt to make a JDBC-free client. Comparing to it, PG2 has the following
-features:
+**It's fast**: [benchmarks](/docs/benchmarks.md) prove up to 3 times performance boost compared to
+`next.jdbc`. Simple HTTP application reading from the database and
+serving JSON handles 2 times more RPS.
-**It's fast.** Benchmarks prove up to 3 times performance boost compared to
-Next.JDBC. A simple HTTP application which reads data from the database and
-responds with JSON handles 2 times more RPS. For details, see the "benchmarks"
-below.
-
-**It's written in Java** with a Clojure layer on top of it. Unfortunately, | Unfortunately,
comma is needed here |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -1,23 +1,23 @@
# Arrays support
-In JDBC, arrays have always been a pain. Every time you're about to pass an
-array to the database and read it back, you've got to wrap your data in various
-Java classes, extend protocols, and multimethods. In Postgres, the array type is
+In `JDBC` arrays have always been a pain. Every time you're about to pass
+array to the database and read it back, you have to wrap your data in various
+Java classes, extend protocols, and multimethods. In Postgres the array type is
quite powerful yet underestimated due to poor support of drivers. This is one
more reason for running this project: to bring easy access to Postgres arrays.
-PG2 tries its best to provide seamless connection between Clojure vectors and
-Postgres arrays. When reading an array, you get a Clojure vector. And vice
+`PG2` tries its best to provide seamless connection between Clojure vectors and
+Postgres arrays. When reading an array you get a Clojure vector. And vice
versa: to pass an array object into a query, just submit a vector.
-PG2 supports arrays of any type: not only primitives like numbers and strings
-but `uuid`, `numeric`, `timestamp(tz)`, `json(b)`, and more as well.
+`PG2` supports arrays of any type: not only primitives like numbers and strings
+but `uuid`, `numeric`, `timestamp(tz)`, `json(b)`, and more.
-Arrays might have more than one dimension. Nothing prevents you from having a 3D
+Arrays can have more than one dimension. Nothing prevents you from having a 3D
array of integers like `cube::int[][][]`, and it becomes a nested vector when
-fetched by PG2.
+fetched by `PG2`.
-*A technical note: PG2 supports both encoding and decoding of arrays in both
+*Technical note: `PG2` supports both encoding and decoding of arrays in both | A article must be preserved, I think |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -34,7 +34,7 @@ Insert a simple item:
{:params [["one" "two" "three"]]})
~~~
-In arrays, some elements might be NULL: | Comma is needed (try this sentence in Grammarly or similar service) |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -51,7 +51,7 @@ Now let's check what we've got so far:
{:id 2 :text_arr ["foo" nil "bar"]}]
~~~
-Postgres supports plenty of operators for arrays. Say, the `&&` one checks if
+Postgres supports plenty of operators for arrays. Say `&&` checks if | Comma is needed |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -92,8 +92,8 @@ Here is how you insert a matrix:
{:inserted 1}
~~~
-Pay attention: each number can be NULL but you cannot have NULL for an entire
-sub-array. This will trigger an error response from Postgres.
+Pay attention: each number can be NULL but you can't have NULL for an entire | I'd prefer `cannot` rather than can't (and you know why, all know) |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -1,12 +1,11 @@
# Authentication
-The library suppors the following authentication types and pipelines:
+`PG2` supports the following authentication types and pipelines:
-- No password (for trusted clients);
+- No password (for trusted clients) | I'd keep `;` at the end. It should be either `.` or `;` at the end of each item. |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -5,7 +5,7 @@
[bench3]: https://grishaev.me/en/pg2-bench-3
[bench4]: https://grishaev.me/en/pg-0-1-12
-For benchmarks, see the following posts in my blog: | I'd keep the old phrasing: For benchmarks, see ...
because when you have only "see", it sounds unclear: see for what?
|
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -1,7 +1,6 @@
# Connecting to the server
-To connect the server, define a config map and pass it into the `connect`
-function:
+Call `connect` with the config map: | It has become too short: call connect for what? |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -17,24 +16,24 @@ function:
(pg/connect config))
~~~
-The `conn` is an instance of the `org.pg.Connection` class.
+`conn` is an instance of the `org.pg.Connection` class.
-The `:host`, `:port`, and `:password` config fields have default values and
-might be skipped (the password is an empty string by default). Only the `:user`
-and `:database` fields are required when connecting. See the list of possible
-fields and their values in a separate section.
+`:host`, `:port`, and `:password` have default values and
+can be skipped (password is an empty string by default). Only `:user`
+and `:database` are required. See the list of possible
+options below.
-To close a connection, pass it into the `close` function: | comma is needed |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -17,24 +16,24 @@ function:
(pg/connect config))
~~~
-The `conn` is an instance of the `org.pg.Connection` class. | "the" is needed |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -17,24 +16,24 @@ function:
(pg/connect config))
~~~
-The `conn` is an instance of the `org.pg.Connection` class.
+`conn` is an instance of the `org.pg.Connection` class.
-The `:host`, `:port`, and `:password` config fields have default values and
-might be skipped (the password is an empty string by default). Only the `:user`
-and `:database` fields are required when connecting. See the list of possible
-fields and their values in a separate section.
+`:host`, `:port`, and `:password` have default values and
+can be skipped (password is an empty string by default). Only `:user`
+and `:database` are required. See the list of possible
+options below.
-To close a connection, pass it into the `close` function:
+To close the connection call `close` with it: | comma is needed |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -1,7 +1,6 @@
# Connection state
-There are some function to track the connection state. In Postgres, the state of
-a connection might be one of these:
+In Postgres the connection state might be one of these: | comma is needed |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -56,9 +59,9 @@ The connection is in the error state now:
true
~~~
-When state is error, the connection doesn't accept any new queries. Each of them
+When state is error the connection doesn't accept any new queries. Each of them | comma |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -56,9 +59,9 @@ The connection is in the error state now:
true
~~~
-When state is error, the connection doesn't accept any new queries. Each of them
+When state is error the connection doesn't accept any new queries. Each of them
will be rejected with a message saying that the connection is in the error
-state. To recover from an error, rollback the current transaction:
+state. To recover from an error rollback the current transaction: | comma |
pg2 | github_2023 | others | 20 | igrishaev | igrishaev | @@ -74,54 +72,38 @@ are plain strings:
(pg/connect config+))
~~~
-## Connection parameters
-
-The following table describes all the possible connection options with the
-possible values and semantics. Only the two first options are requred. All the
-rest have predefined values.
-
-| Field | Type | Default | Comment |
-|------------------------|--------------|--------------------|---------------------------------------------------------------------------------|
-| `:user` | string | **required** | the name of the DB user |
-| `:database` | string | **required** | the name of the database |
-| `:host` | string | 127.0.0.1 | IP or hostname |
-| `:port` | integer | 5432 | port number |
-| `:password` | string | "" | DB user password |
-| `:pg-params` | map | {} | A map of session params like {string string} |
-| `:binary-encode?` | bool | false | Whether to use binary data encoding |
-| `:binary-decode?` | bool | false | Whether to use binary data decoding |
-| `:read-only?` | bool | false | Whether to initiate this connection in READ ONLY mode (see below) |
-| `:in-stream-buf-size` | integer | 0xFFFF | Size of the input buffered socket stream |
-| `:out-stream-buf-size` | integer | 0xFFFF | Size of the output buffered socket stream |
-| `:fn-notification` | 1-arg fn | logging fn | A function to handle notifications |
-| `:fn-protocol-version` | 1-arg fn | logging fn | A function to handle negotiation version protocol event |
-| `:fn-notice` | 1-arg fn | logging fn | A function to handle notices |
-| `:use-ssl?` | bool | false | Whether to use SSL connection |
-| `:ssl-context` | SSLContext | nil | An custom instance of `SSLContext` class to wrap a socket |
-| `:so-keep-alive?` | bool | true | Socket KeepAlive value |
-| `:so-tcp-no-delay?` | bool | true | Socket TcpNoDelay value |
-| `:so-timeout` | integer | 15.000 | Socket timeout value, in ms |
-| `:so-recv-buf-size` | integer | 0xFFFF | Socket receive buffer size |
-| `:so-send-buf-size` | integer | 0xFFFF | Socket send buffer size |
-| `:cancel-timeout-ms` | integer | 5.000 | Default value for the `with-timeout` macro, in ms |
-| `:protocol-version` | integer | 196608 | Postgres protocol version |
-| `:object-mapper` | ObjectMapper | JSON.defaultMapper | An instance of ObjectMapper for custom JSON processing (see the "JSON" section) |
-
-### Parameter notes
-
-#### Read Only Mode
-
-The `:read-only?` connection parameter does two things under the hood:
-
-1. It appends the `default_transaction_read_only` parameter to the startup
- message set to `on`. Thus, any transaction gets started on `READ ONLY` mode.
-
-2. It prevents the `:read-only?` flag from overriding in the `with-tx`
- macro. Say, even if the macro is called like this:
-
-~~~clojure
-(pg/with-tx [conn {:read-only? false}] ;; try to mute the global :read-only? flag
- (pg/query conn "delete from students"))
-~~~
-
-The transaction will be in `READ ONLY` mode anyway.
+## Connection Parameters
+
+The following table describes all possible connection options.
+Only `:user` and `:database` are requred, others have default values.
+
+| Field | Type | Default | Comment |
+|------------------------|--------------|----------------------|-------------------------------------------------------------------------------------------|
+| `:user` | string | **required** | DB user name |
+| `:database` | string | **required** | database name |
+| `:host` | string | `"127.0.0.1"` | IP or hostname |
+| `:port` | integer | `5432` | port number |
+| `:password` | string | `""` | DB user password |
+| `:pg-params` | map | `{}` | Map of session params like {string string} |
+| `:binary-encode?` | bool | `false` | Whether to use binary data encoding |
+| `:binary-decode?` | bool | `false` | Whether to use binary data decoding |
+| `:read-only?` | bool | `false` | Whether to initiate this connection in READ ONLY mode (see below) |
+| `:in-stream-buf-size` | integer | `0xFFFF` | Size of the input buffered socket stream |
+| `:out-stream-buf-size` | integer | `0xFFFF` | Size of the output buffered socket stream |
+| `:fn-notification` | 1-arg fn | logging fn | Function to handle notifications |
+| `:fn-protocol-version` | 1-arg fn | logging fn | Function to handle negotiation version protocol event |
+| `:fn-notice` | 1-arg fn | logging fn | Function to handle notices |
+| `:use-ssl?` | bool | `false` | Whether to use SSL connection |
+| `:ssl-context` | SSLContext | `nil` | Custom instance of `SSLContext` class to wrap a socket |
+| `:so-keep-alive?` | bool | `true` | Socket KeepAlive value |
+| `:so-tcp-no-delay?` | bool | `true` | Socket TcpNoDelay value |
+| `:so-timeout` | integer | `15.000` | Socket timeout value (in ms) |
+| `:so-recv-buf-size` | integer | `0xFFFF` | Socket receive buffer size |
+| `:so-send-buf-size` | integer | `0xFFFF` | Socket send buffer size |
+| `:cancel-timeout-ms` | integer | `5000` | Default value for the `with-timeout` macro (in ms) |
+| `:protocol-version` | integer | `196608` | Postgres protocol version |
+| `:object-mapper` | ObjectMapper | `JSON.defaultMapper` | Instance of `ObjectMapper` for custom JSON processing (see [JSON support](/docs/json.md)) |
+
+### read-only mode
+ | (duplicate): keep the origin block of code with examples here |
pg2 | github_2023 | others | 15 | igrishaev | jeaye | @@ -123,7 +123,31 @@
mig/parse-url)]
(is (= nil
- (dissoc res :url)))))
+ (dissoc res :url))))
+
+ (testing "no leading path"
+ (let [res
+ (-> "003.hello.prev.sql"
+ io/file
+ io/as-url
+ mig/parse-url)]
+
+ (is (= {:id 3
+ :slug "hello"
+ :direction :prev}
+ (dissoc res :url)))))
+ | Looks great! I've tested this locally and it fixed the issue. Thank you!
After merging, if you wouldn't mind publishing a new release for this, that would be superb. |
pg2 | github_2023 | others | 5 | igrishaev | igrishaev | @@ -0,0 +1,29 @@
+# Local pg-ragtime postgresql database
+#
+# I wasn't able to use the toplevel `docker-compose.yaml` out of the box.
+#
+# Maybe `.docker/postgres/initdb.d` is missing?
+#
+# Anyway, I'm adding a local compose file for now to get a REPL to run my
+# code.
+#
+# We probably want to delete this file when I understand how to run the
+# toplevel docker-compose.yaml.
+#
+# Connect with `psql`:
+#
+# $ psql -d "postgresql://localhost:10170/test?user=test&password=test"
+
+
+version: "3.6"
+
+services:
+ pg16-ragtime:
+ image: postgres:16
+ hostname: pg16-ragtime
+ ports:
+ - "10170:5432"
+ environment:
+ - POSTGRES_DB=test
+ - POSTGRES_PASSWORD=test
+ - POSTGRES_USER=test | Hm, that's a bit strange. Do you use Linux, by the way? It might be related to permissions with that hidden .docker directory.
|
pg2 | github_2023 | others | 3 | igrishaev | igrishaev | @@ -0,0 +1,29 @@
+(ns pg.ragtime | The draft looks solid, thank you. Just a note: you can borrow most of the code from here: https://github.com/weavejester/ragtime/blob/master/next-jdbc/src/ragtime/next_jdbc.clj |
pg2 | github_2023 | others | 3 | igrishaev | igrishaev | @@ -0,0 +1,29 @@
+(ns pg.ragtime
+ (:require
+ [ragtime.core :as ragtime]
+ [ragtime.strategy]
+ [ragtime.protocols]
+ [pg.core :as pg])
+ (:import org.pg.Connection))
+
+(defn ensure-migrations-table!
+ [conn]
+ (pg/query conn "
+create table if not exists ragtime_migrations( | Here, the name of the table is hardcoded. We can keep it as is for now but later on, it should be a configuration parameter.
|
pg2 | github_2023 | others | 3 | igrishaev | igrishaev | @@ -0,0 +1,29 @@
+(ns pg.ragtime
+ (:require
+ [ragtime.core :as ragtime]
+ [ragtime.strategy]
+ [ragtime.protocols]
+ [pg.core :as pg])
+ (:import org.pg.Connection))
+
+(defn ensure-migrations-table!
+ [conn]
+ (pg/query conn "
+create table if not exists ragtime_migrations(
+ id text primary key,
+ timestamp timestamp default current_timestamp
+)"))
+
+(defn dangerously-delete-migrations-table!!
+ [conn]
+ (pg/query conn "drop table ragtime_migrations"))
+
+(extend-type Connection
+ ragtime.protocols/DataStore
+ (add-migration-id [conn id]
+ (pg/execute conn "insert into ragtime_migrations(id) values ($1)" {:params [id]}))
+ (remove-migration-id [conn id]
+ (pg/execute conn "delete from ragtime_migrations where id = $1", {:params [id]}))
+ (applied-migration-ids [conn]
+ (->> (pg/query conn "select id from ragtime_migrations")
+ (map :id)))) | Could you also create 2-3 test migrations please and put them into the tests/migrations directory? Something like create a table `users` and then adding a column. Like this: https://github.com/weavejester/ragtime/tree/master/next-jdbc/test/migrations
Then, we can prepare tests that ensure migrations work.
|
polars_ds_extension | github_2023 | others | 84 | abstractqqq | abstractqqq | @@ -27,14 +27,15 @@ inflections = "1.1.1"
kdtree = {git = "https://github.com/mrhooray/kdtree-rs.git"}
petgraph = "0.6.4"
ordered-float = "4.2.0"
+pyo3-build-config = "0.20.2" | Do you know where is this needed? |
polars_ds_extension | github_2023 | python | 84 | abstractqqq | abstractqqq | @@ -1066,3 +1066,43 @@ def _haversine(
is_elementwise=True,
cast_to_supertypes=True,
)
+
+ def knn_entropy(self, *others: pl.Expr, k=2):
+ """
+ Multivariate estimation of entropy through a k-nearest neighbor query
+
+ Reference
+ ---------
+ https://arxiv.org/pdf/1506.06501v1.pdf
+ """
+ from scipy.special import digamma
+ from math import pi, gamma, log
+ (N, d) = pl.len(), len(others) + 1 # d has to include self
+ g1 = digamma(N) - digamma(k)
+ knn = pl.col('row_nr').num.knn_ptwise(*others, dist='euclidean', k=k).list.get(k) | Right now I think dist = 'l2' is available, but l2 is actually squared Euclidean. But that won't change the output because sqrt preserves order..
Also I think pl.col("row_nr") should be self._expr? |
polars_ds_extension | github_2023 | python | 84 | abstractqqq | abstractqqq | @@ -1066,3 +1066,43 @@ def _haversine(
is_elementwise=True,
cast_to_supertypes=True,
)
+
+ def knn_entropy(self, *others: pl.Expr, k=2):
+ """
+ Multivariate estimation of entropy through a k-nearest neighbor query
+
+ Reference
+ ---------
+ https://arxiv.org/pdf/1506.06501v1.pdf
+ """
+ from scipy.special import digamma | I think I might have a rust digamma function available somewhere already in the Rust codebase. If not, we can use the digamma implemented here: https://github.com/statrs-dev/statrs/blob/5411ba74b427b992dd1410d699052a0b41dc2b5c/src/function/gamma.rs#L353.
One of my goal is to reduce dependency on other packages as much as possible. (But I personally admit the crime that I have way tooooo many packages installed in my env...) |
polars_ds_extension | github_2023 | python | 84 | abstractqqq | abstractqqq | @@ -1066,3 +1066,42 @@ def _haversine(
is_elementwise=True,
cast_to_supertypes=True,
)
+
+ def knn_entropy(self, *others: pl.Expr, k=2):
+ """
+ Multivariate estimation of entropy through a k-nearest neighbor query
+
+ Reference
+ ---------
+ https://arxiv.org/pdf/1506.06501v1.pdf
+ """
+ from scipy.special import digamma
+ from math import pi, gamma, log
+ (N, d) = pl.len(), len(others) + 1 # d has to include self
+ g1 = digamma(N) - digamma(k)
+ index = pl.int_range(N, dtype=pl.UInt32).alias("_idx")
+ neighbor = index.num.knn_ptwise(self._expr, *others, dist='l1', k=k).list.get(k)
+ # euclidean distance computation for now. But others can be used
+ dists = pl.sum_horizontal(pl.exclude('_idx').sub(pl.exclude('_idx').gather(neighbor)).pow(2)).sqrt()
+ logd = dists.mul(2).log().mul(d).truediv(N).sum()
+ cd = pi ** (d / 2) / 2 ** d / gamma(1 + d / 2)
+ return (g1 + log(cd) + logd)
+
+
+ def copula_entropy(self, *others, k=2): | Please add types to all funtions and eventually add some comments and references when you are done. Thanks |
polars_ds_extension | github_2023 | others | 84 | abstractqqq | abstractqqq | @@ -14,7 +14,7 @@ pyo3 = {version = "*", features = ["extension-module"]}
pyo3-polars = {version = "0.11", features = ["derive"]}
polars = {version = "0.37", features = ["performant", "lazy", "dtype-array", "array_count", "ndarray","log","nightly"]}
num = "0.4.1"
-faer = {version = "0.16", features = ["ndarray", "nightly"]}
+faer = {version = "0.17.1", features = ["ndarray", "nightly"]} | Let's not upgrade Faer right now. I am having trouble building it. We don't need anything from 0.17 yet. |
polars_ds_extension | github_2023 | python | 84 | abstractqqq | abstractqqq | @@ -1064,6 +1074,66 @@ def _haversine(
)
+ def conditional_independence(self, y: pl.Expr, z: pl.Expr, k: int = 2):
+ """
+ Test independance of `self` (considered as `x`) and `y`, conditioned on `z`
+
+ Reference
+ ---------
+ Jian Ma. Multivariate Normality Test with Copula Entropy. arXiv preprint arXiv:2206.05956, 2022.
+ """
+ xyz = copula_entropy(self._expr, y, z, k=k)
+ yz = copula_entropy(y, z, k=k)
+ xz = copula_entropy(self._expr, z, k=k)
+ return xyz - yz - xz
+
+
+ def transfer_entropy(self, source: pl.Expr, lag = 1, k = 2):
+ """
+ Estimating transfer entropy from `source` to `self` with a lag
+
+ Reference
+ ---------
+ Jian Ma. Estimating Transfer Entropy via Copula Entropy. arXiv preprint arXiv:1910.04375, 2019.
+ """
+ x1 = self._expr.slice(0, pl.len() - lag)
+ x2 = self._expr.slice(lag, pl.len())
+ source = source.slice(0, pl.len() - lag)
+ return x2.num.conditional_independence(source, x1, k=k)
+
+
+def knn_entropy(*expr: Union[str, pl.Expr], k=2):
+ """
+ Multivariate estimation of entropy through a k-nearest neighbor query
+
+ Reference
+ ---------
+ https://arxiv.org/pdf/1506.06501v1.pdf
+ """
+ for _expr in expr:
+ if isinstance(expr, pl.Expr):
+ assert not _expr.meta.has_multiple_outputs(), "Please pass expressions independently"
+ N, d, pi = pl.len(), pl.lit(len(expr)), pl.lit(math.pi) # d has to include self
+ g1 = N.num.digamma() - pl.lit(k).num.digamma()
+ index = pl.int_range(N, dtype=pl.UInt32).alias("_idx")
+ neighbor = query_knn_ptwise(*expr, index=index, dist='l1', k=k).list.get(k)
+ # euclidean distance computation for now. But others can be used
+ dists = pl.sum_horizontal(pl.exclude('_idx').sub(pl.exclude('_idx').gather(neighbor)).pow(2)).sqrt() | Can you write this line in more compact math notation? I am having trouble understanding the point of exclude and gather.. Thanks |
wordcab-transcribe | github_2023 | python | 283 | Wordcab | aleksandr-smechov | @@ -776,7 +777,10 @@ async def remote_diarization(
data: DiarizationRequest,
) -> DiarizationOutput:
"""Remote diarization method."""
- async with aiohttp.ClientSession() as session:
+ # Set the timeout according to the env value of the REMOTE_DIARIZE_SERVER_REQUEST_TIMEOUT_SEC variable
+
+ specifictimeout = aiohttp.ClientTimeout(total=int(os.getenv("REMOTE_DIARIZE_SERVER_REQUEST_TIMEOUT_SEC", 300))) | You'd need to add the env variable to https://github.com/Wordcab/wordcab-transcribe/blob/main/.env
Then the appropriate lines [in the config file](https://github.com/Wordcab/wordcab-transcribe/blob/main/src/wordcab_transcribe/config.py) for the Settings class on lines 35 and 236 (this is where you'd set a default)
Afterwards import the `config` in `asr_service` like so: `from wordcab_transcribe.config import settings` and use `settings.remote_diarization_request_timeout`.
[Run tests locally](https://github.com/Wordcab/wordcab-transcribe/tree/8c967bd0fdb29a8496ab9d32caa6d6c9a7649c03#run-the-api-using-docker) and then launch the container locally to see if it works as expected.
`specifictimeout` => `diarization_timeout` for readability |
wordcab-transcribe | github_2023 | others | 283 | Wordcab | aleksandr-smechov | @@ -8,7 +8,7 @@
# The name of the project, used for API documentation.
PROJECT_NAME="Wordcab Transcribe"
# The version of the project, used for API documentation.
-VERSION="0.5.1"
+VERSION="0.5.2.1" | No version increment |
wordcab-transcribe | github_2023 | others | 283 | Wordcab | aleksandr-smechov | @@ -115,4 +115,6 @@ TRANSCRIBE_SERVER_URLS=
# e.g. SERVER_URLS="http://1.2.3.4:8000,http://4.3.2.1:8000"
DIARIZE_SERVER_URLS=
#
+# Timeout for connection and waiting for result from remote diarize server. 300 sec is default value
+REMOTE_DIARIZE_SERVER_REQUEST_TIMEOUT_SEC=300 | Just `REMOTE_DIARIZATION_REQUEST_TIMEOUT=300`
to keep things consistent |
wordcab-transcribe | github_2023 | python | 283 | Wordcab | aleksandr-smechov | @@ -19,4 +19,4 @@
# and limitations under the License.
"""Main module of the Wordcab ASR API."""
-__version__ = "0.5.2"
+__version__ = "0.5.2.1" | No increment |
wordcab-transcribe | github_2023 | python | 283 | Wordcab | aleksandr-smechov | @@ -272,4 +274,5 @@ def __post_init__(self):
# Remote servers configuration
transcribe_server_urls=transcribe_server_urls,
diarize_server_urls=diarize_server_urls,
+ remote_diarization_request_timeout=int(os.getenv("REMOTE_DIARIZE_SERVER_REQUEST_TIMEOUT_SEC", 300)), | `remote_diarization_request_timeout=getenv("REMOTE_DIARIZATION_REQUEST_TIMEOUT", 300),` |
wordcab-transcribe | github_2023 | python | 283 | Wordcab | aleksandr-smechov | @@ -300,6 +301,9 @@ def __init__(
"You provided URLs for remote diarization server, no local model will"
" be used."
)
+ logger.info(
+ f"remote diarization server timeout is {settings.remote_diarization_request_timeout}" | `f"Remote diarization server timeout set to {settings.remote_diarization_request_timeout}"` |
wordcab-transcribe | github_2023 | python | 283 | Wordcab | aleksandr-smechov | @@ -776,7 +780,11 @@ async def remote_diarization(
data: DiarizationRequest,
) -> DiarizationOutput:
"""Remote diarization method."""
- async with aiohttp.ClientSession() as session:
+ # Set the timeout according to the env value of the REMOTE_DIARIZE_SERVER_REQUEST_TIMEOUT_SEC variable
+ logger.info(f"settings.remote_diarization_request_timeout={settings.remote_diarization_request_timeout} secs") | Can remove lines 783-785 |
wordcab-transcribe | github_2023 | python | 282 | Wordcab | karmi | @@ -776,7 +776,10 @@ async def remote_diarization(
data: DiarizationRequest,
) -> DiarizationOutput:
"""Remote diarization method."""
- async with aiohttp.ClientSession() as session:
+ # Set the timeout to 12 hours for several hours long audio files
+ verylongtimeout = ClientTimeout(total=12 * 60 * 60)
+
+ async with aiohttp.ClientSession(timeout=verylongtimeout) as session: | I think that @aleksandr-smechov is only asking to make the timeout configurable. As far as I understand, it's as simple as this?
```suggestion
timeout = int(os.getenv("REQUEST_TIMEOUT", 300))
async with aiohttp.ClientSession(timeout=timeout) as session:
```
Of course, as part of the PR, a change should be done in the `.env` file as well. Also, `os` should be imported in the file. |
wordcab-transcribe | github_2023 | python | 225 | Wordcab | chainyo | @@ -272,82 +272,93 @@ async def process_input(
"process_times": {},
}
- # Pick the first available GPU for the task
- gpu_index = await self.gpu_handler.get_device() if self.device == "cuda" else 0
- logger.info(f"Using GPU {gpu_index} for the task")
+ gpu_index = -1 # Placeholder to track if GPU is acquired
- start_process_time = time.time()
+ try:
+ # If GPU is required, acquire one
+ if self.device == "cuda":
+ gpu_index = await self.gpu_handler.get_device()
+ logger.info(f"Using GPU {gpu_index} for the task")
- asyncio.get_event_loop().run_in_executor(
- None,
- functools.partial(
- self.process_transcription, task, gpu_index, self.debug_mode
- ),
- )
+ start_process_time = time.time()
- if diarization and dual_channel is False:
asyncio.get_event_loop().run_in_executor(
None,
functools.partial(
- self.process_diarization, task, gpu_index, self.debug_mode
+ self.process_transcription, task, gpu_index, self.debug_mode
),
)
- else:
- task["process_times"]["diarization"] = None
- task["diarization_done"].set()
-
- await task["transcription_done"].wait()
- await task["diarization_done"].wait()
- if isinstance(task["diarization_result"], Exception):
- self.gpu_handler.release_device(gpu_index)
- return task["diarization_result"]
-
- if diarization and task["diarization_result"] is None:
- # Empty audio early return
- return early_return(duration=duration)
-
- if isinstance(task["transcription_result"], Exception):
- self.gpu_handler.release_device(gpu_index)
- return task["transcription_result"]
- else:
- if alignment and dual_channel is False:
+ if diarization and dual_channel is False:
asyncio.get_event_loop().run_in_executor(
None,
functools.partial(
- self.process_alignment, task, gpu_index, self.debug_mode
+ self.process_diarization, task, gpu_index, self.debug_mode
),
)
else:
- task["process_times"]["alignment"] = None
- task["alignment_done"].set()
+ task["process_times"]["diarization"] = None
+ task["diarization_done"].set()
- await task["alignment_done"].wait()
+ await task["transcription_done"].wait()
+ await task["diarization_done"].wait()
- if isinstance(task["alignment_result"], Exception):
- logger.error(f"Alignment failed: {task['alignment_result']}")
- # Failed alignment should not fail the whole request anymore, as not critical
- # So we keep processing the request and return the transcription result
- # return task["alignment_result"]
+ if isinstance(task["diarization_result"], Exception):
+ self.gpu_handler.release_device(gpu_index)
+ return task["diarization_result"]
- self.gpu_handler.release_device(gpu_index) # Release the GPU
+ if diarization and task["diarization_result"] is None:
+ # Empty audio early return
+ return early_return(duration=duration)
- asyncio.get_event_loop().run_in_executor(
- None, functools.partial(self.process_post_processing, task)
- )
+ if isinstance(task["transcription_result"], Exception):
+ self.gpu_handler.release_device(gpu_index)
+ return task["transcription_result"]
+ else:
+ if alignment and dual_channel is False:
+ asyncio.get_event_loop().run_in_executor(
+ None,
+ functools.partial(
+ self.process_alignment, task, gpu_index, self.debug_mode
+ ),
+ )
+ else:
+ task["process_times"]["alignment"] = None
+ task["alignment_done"].set()
- await task["post_processing_done"].wait()
+ await task["alignment_done"].wait()
- if isinstance(task["post_processing_result"], Exception):
- return task["post_processing_result"]
+ if isinstance(task["alignment_result"], Exception):
+ logger.error(f"Alignment failed: {task['alignment_result']}")
+ # Failed alignment should not fail the whole request anymore, as not critical
+ # So we keep processing the request and return the transcription result
+ # return task["alignment_result"]
- result: List[dict] = task.pop("post_processing_result")
- process_times: Dict[str, float] = task.pop("process_times")
- process_times["total"]: float = time.time() - start_process_time
+ self.gpu_handler.release_device(gpu_index) # Release the GPU
+
+ asyncio.get_event_loop().run_in_executor(
+ None, functools.partial(self.process_post_processing, task)
+ )
- del task # Delete the task to free up memory
+ await task["post_processing_done"].wait()
- return result, process_times, duration
+ if isinstance(task["post_processing_result"], Exception):
+ return task["post_processing_result"]
+
+ result: List[dict] = task.pop("post_processing_result")
+ process_times: Dict[str, float] = task.pop("process_times")
+ process_times["total"]: float = time.time() - start_process_time
+
+ del task # Delete the task to free up memory
+
+ return result, process_times, duration
+ except Exception as e:
+ logger.error(f"Error processing input: {e}")
+ return e | ```suggestion
except Exception as e:
return e
```
The errors are already logged in the API endpoints:
<img width="494" alt="CleanShot 2023-08-31 at 08 24 28@2x" src="https://github.com/Wordcab/wordcab-transcribe/assets/50595514/7a641541-5f30-4afc-8797-7abc2338bf33">
|
wordcab-transcribe | github_2023 | python | 225 | Wordcab | chainyo | @@ -272,82 +272,93 @@ async def process_input(
"process_times": {},
}
- # Pick the first available GPU for the task
- gpu_index = await self.gpu_handler.get_device() if self.device == "cuda" else 0
- logger.info(f"Using GPU {gpu_index} for the task")
+ gpu_index = -1 # Placeholder to track if GPU is acquired
- start_process_time = time.time()
+ try:
+ # If GPU is required, acquire one
+ if self.device == "cuda":
+ gpu_index = await self.gpu_handler.get_device()
+ logger.info(f"Using GPU {gpu_index} for the task")
- asyncio.get_event_loop().run_in_executor(
- None,
- functools.partial(
- self.process_transcription, task, gpu_index, self.debug_mode
- ),
- )
+ start_process_time = time.time()
- if diarization and dual_channel is False:
asyncio.get_event_loop().run_in_executor(
None,
functools.partial(
- self.process_diarization, task, gpu_index, self.debug_mode
+ self.process_transcription, task, gpu_index, self.debug_mode
),
)
- else:
- task["process_times"]["diarization"] = None
- task["diarization_done"].set()
-
- await task["transcription_done"].wait()
- await task["diarization_done"].wait()
- if isinstance(task["diarization_result"], Exception):
- self.gpu_handler.release_device(gpu_index)
- return task["diarization_result"]
-
- if diarization and task["diarization_result"] is None:
- # Empty audio early return
- return early_return(duration=duration)
-
- if isinstance(task["transcription_result"], Exception):
- self.gpu_handler.release_device(gpu_index)
- return task["transcription_result"]
- else:
- if alignment and dual_channel is False:
+ if diarization and dual_channel is False:
asyncio.get_event_loop().run_in_executor(
None,
functools.partial(
- self.process_alignment, task, gpu_index, self.debug_mode
+ self.process_diarization, task, gpu_index, self.debug_mode
),
)
else:
- task["process_times"]["alignment"] = None
- task["alignment_done"].set()
+ task["process_times"]["diarization"] = None
+ task["diarization_done"].set()
- await task["alignment_done"].wait()
+ await task["transcription_done"].wait()
+ await task["diarization_done"].wait()
- if isinstance(task["alignment_result"], Exception):
- logger.error(f"Alignment failed: {task['alignment_result']}")
- # Failed alignment should not fail the whole request anymore, as not critical
- # So we keep processing the request and return the transcription result
- # return task["alignment_result"]
+ if isinstance(task["diarization_result"], Exception):
+ self.gpu_handler.release_device(gpu_index)
+ return task["diarization_result"] | ```suggestion
if isinstance(task["diarization_result"], Exception):
self.gpu_handler.release_device(gpu_index)
gpu_index = -1
return task["diarization_result"]
``` |
wordcab-transcribe | github_2023 | python | 225 | Wordcab | chainyo | @@ -272,82 +272,93 @@ async def process_input(
"process_times": {},
}
- # Pick the first available GPU for the task
- gpu_index = await self.gpu_handler.get_device() if self.device == "cuda" else 0
- logger.info(f"Using GPU {gpu_index} for the task")
+ gpu_index = -1 # Placeholder to track if GPU is acquired
- start_process_time = time.time()
+ try:
+ # If GPU is required, acquire one
+ if self.device == "cuda":
+ gpu_index = await self.gpu_handler.get_device()
+ logger.info(f"Using GPU {gpu_index} for the task")
- asyncio.get_event_loop().run_in_executor(
- None,
- functools.partial(
- self.process_transcription, task, gpu_index, self.debug_mode
- ),
- )
+ start_process_time = time.time()
- if diarization and dual_channel is False:
asyncio.get_event_loop().run_in_executor(
None,
functools.partial(
- self.process_diarization, task, gpu_index, self.debug_mode
+ self.process_transcription, task, gpu_index, self.debug_mode
),
)
- else:
- task["process_times"]["diarization"] = None
- task["diarization_done"].set()
-
- await task["transcription_done"].wait()
- await task["diarization_done"].wait()
- if isinstance(task["diarization_result"], Exception):
- self.gpu_handler.release_device(gpu_index)
- return task["diarization_result"]
-
- if diarization and task["diarization_result"] is None:
- # Empty audio early return
- return early_return(duration=duration)
-
- if isinstance(task["transcription_result"], Exception):
- self.gpu_handler.release_device(gpu_index)
- return task["transcription_result"]
- else:
- if alignment and dual_channel is False:
+ if diarization and dual_channel is False:
asyncio.get_event_loop().run_in_executor(
None,
functools.partial(
- self.process_alignment, task, gpu_index, self.debug_mode
+ self.process_diarization, task, gpu_index, self.debug_mode
),
)
else:
- task["process_times"]["alignment"] = None
- task["alignment_done"].set()
+ task["process_times"]["diarization"] = None
+ task["diarization_done"].set()
- await task["alignment_done"].wait()
+ await task["transcription_done"].wait()
+ await task["diarization_done"].wait()
- if isinstance(task["alignment_result"], Exception):
- logger.error(f"Alignment failed: {task['alignment_result']}")
- # Failed alignment should not fail the whole request anymore, as not critical
- # So we keep processing the request and return the transcription result
- # return task["alignment_result"]
+ if isinstance(task["diarization_result"], Exception):
+ self.gpu_handler.release_device(gpu_index)
+ return task["diarization_result"]
- self.gpu_handler.release_device(gpu_index) # Release the GPU
+ if diarization and task["diarization_result"] is None:
+ # Empty audio early return
+ return early_return(duration=duration)
- asyncio.get_event_loop().run_in_executor(
- None, functools.partial(self.process_post_processing, task)
- )
+ if isinstance(task["transcription_result"], Exception):
+ self.gpu_handler.release_device(gpu_index)
+ return task["transcription_result"] | ```suggestion
if isinstance(task["transcription_result"], Exception):
self.gpu_handler.release_device(gpu_index)
gpu_index = -1
return task["transcription_result"]
``` |
wordcab-transcribe | github_2023 | python | 225 | Wordcab | chainyo | @@ -272,82 +272,93 @@ async def process_input(
"process_times": {},
}
- # Pick the first available GPU for the task
- gpu_index = await self.gpu_handler.get_device() if self.device == "cuda" else 0
- logger.info(f"Using GPU {gpu_index} for the task")
+ gpu_index = -1 # Placeholder to track if GPU is acquired
- start_process_time = time.time()
+ try:
+ # If GPU is required, acquire one
+ if self.device == "cuda":
+ gpu_index = await self.gpu_handler.get_device()
+ logger.info(f"Using GPU {gpu_index} for the task")
- asyncio.get_event_loop().run_in_executor(
- None,
- functools.partial(
- self.process_transcription, task, gpu_index, self.debug_mode
- ),
- )
+ start_process_time = time.time()
- if diarization and dual_channel is False:
asyncio.get_event_loop().run_in_executor(
None,
functools.partial(
- self.process_diarization, task, gpu_index, self.debug_mode
+ self.process_transcription, task, gpu_index, self.debug_mode
),
)
- else:
- task["process_times"]["diarization"] = None
- task["diarization_done"].set()
-
- await task["transcription_done"].wait()
- await task["diarization_done"].wait()
- if isinstance(task["diarization_result"], Exception):
- self.gpu_handler.release_device(gpu_index)
- return task["diarization_result"]
-
- if diarization and task["diarization_result"] is None:
- # Empty audio early return
- return early_return(duration=duration)
-
- if isinstance(task["transcription_result"], Exception):
- self.gpu_handler.release_device(gpu_index)
- return task["transcription_result"]
- else:
- if alignment and dual_channel is False:
+ if diarization and dual_channel is False:
asyncio.get_event_loop().run_in_executor(
None,
functools.partial(
- self.process_alignment, task, gpu_index, self.debug_mode
+ self.process_diarization, task, gpu_index, self.debug_mode
),
)
else:
- task["process_times"]["alignment"] = None
- task["alignment_done"].set()
+ task["process_times"]["diarization"] = None
+ task["diarization_done"].set()
- await task["alignment_done"].wait()
+ await task["transcription_done"].wait()
+ await task["diarization_done"].wait()
- if isinstance(task["alignment_result"], Exception):
- logger.error(f"Alignment failed: {task['alignment_result']}")
- # Failed alignment should not fail the whole request anymore, as not critical
- # So we keep processing the request and return the transcription result
- # return task["alignment_result"]
+ if isinstance(task["diarization_result"], Exception):
+ self.gpu_handler.release_device(gpu_index)
+ return task["diarization_result"]
- self.gpu_handler.release_device(gpu_index) # Release the GPU
+ if diarization and task["diarization_result"] is None:
+ # Empty audio early return
+ return early_return(duration=duration)
- asyncio.get_event_loop().run_in_executor(
- None, functools.partial(self.process_post_processing, task)
- )
+ if isinstance(task["transcription_result"], Exception):
+ self.gpu_handler.release_device(gpu_index)
+ return task["transcription_result"]
+ else:
+ if alignment and dual_channel is False:
+ asyncio.get_event_loop().run_in_executor(
+ None,
+ functools.partial(
+ self.process_alignment, task, gpu_index, self.debug_mode
+ ),
+ )
+ else:
+ task["process_times"]["alignment"] = None
+ task["alignment_done"].set()
- await task["post_processing_done"].wait()
+ await task["alignment_done"].wait()
- if isinstance(task["post_processing_result"], Exception):
- return task["post_processing_result"]
+ if isinstance(task["alignment_result"], Exception):
+ logger.error(f"Alignment failed: {task['alignment_result']}")
+ # Failed alignment should not fail the whole request anymore, as not critical
+ # So we keep processing the request and return the transcription result
+ # return task["alignment_result"]
- result: List[dict] = task.pop("post_processing_result")
- process_times: Dict[str, float] = task.pop("process_times")
- process_times["total"]: float = time.time() - start_process_time
+ self.gpu_handler.release_device(gpu_index) # Release the GPU
+
+ asyncio.get_event_loop().run_in_executor(
+ None, functools.partial(self.process_post_processing, task)
+ ) | ```suggestion
self.gpu_handler.release_device(gpu_index)
gpu_index = -1
asyncio.get_event_loop().run_in_executor(
None, functools.partial(self.process_post_processing, task)
)
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -60,7 +61,66 @@
"₿",
]
+# run API for youtube video endpoint
+def run_api_youtube(url : str, sourceLang = "en", timestamps = "s", wordTimestamps = False): | Two essential things for the functions:
* Never use CamelCase in Python. Could you go with the snake case for function parameters? Only a class has uppercase letters, e.g. `ASRService`.
* The functions are missing some parameters like `alignment`, `diarization`, or `dual_channel` for the audio file endpoint. |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -60,7 +61,66 @@
"₿",
]
+# run API for youtube video endpoint
+def run_api_youtube(url : str, sourceLang = "en", timestamps = "s", wordTimestamps = False):
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": True, # Longer processing time but better timestamps
+ "diarization": True, # Longer processing time but speaker segment attribution
+ "source_lang": sourceLang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": wordTimestamps, # optional, default is False
+ }
+
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ )
+
+ r_json = response.json()
+
+ with open("youtube_video_output.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+ # run API for audio file endpoint
+ def run_api_audioFile(file : str, sourceLang = "en", timestamps = "s", wordTimestamps = False):
+ filepath = file # or any other convertible format by ffmpeg
+ data = {
+ "alignment": True, # Longer processing time but better timestamps
+ "diarization": True, # Longer processing time but speaker segment attribution
+ "dual_channel": False, # Only for stereo audio files with one speaker per channel
+ "source_lang": sourceLang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": wordTimestamps, # optional, default is False
+ }
+
+ with open(filepath, "rb") as f:
+ files = {"file": f}
+ response = requests.post(
+ "http://localhost:5001/api/v1/audio",
+ files=files,
+ data=data,
+ )
+ r_json = response.json()
+
+ filename = filepath.split(".")[0]
+ with open(f"{filename}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+# run API function that will delegate to other functions based on the endpoint
+def run_api (url : str, endpoint: str, sourceLang = "en", timestamps = "s", wordTimestamps = False)
+ if endpoint == "youtube":
+ run_api_youtube(url, sourceLang, timestamps, wordTimestamps)
+ elif endpoint == "audioFile":
+ run_api_audioFile(url, sourceLang, timestamps, wordTimestamps)
+
+ | Could you also add the `audio_url_endpoint`? This endpoint is similar to the `audio_file_endpoint` but downloads the file from a signed URL.
All the endpoints are in the following folder: [`wordcab_transcribe/router/v1/`](https://github.com/Wordcab/wordcab-transcribe/tree/main/wordcab_transcribe/router/v1)
The [`audio_url_endpoint`](https://github.com/Wordcab/wordcab-transcribe/blob/main/wordcab_transcribe/router/v1/audio_url_endpoint.py) file. |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -60,7 +61,66 @@
"₿",
]
+# run API for youtube video endpoint
+def run_api_youtube(url : str, sourceLang = "en", timestamps = "s", wordTimestamps = False):
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": True, # Longer processing time but better timestamps
+ "diarization": True, # Longer processing time but speaker segment attribution
+ "source_lang": sourceLang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": wordTimestamps, # optional, default is False
+ }
+
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ )
+
+ r_json = response.json()
+ | A response status check should ensure you get a `200` response. If `200`, you can return the JSON response. If not, you'll need to tell the user. Check the endpoints to see the `500` status |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,122 @@
+import requests
+import json
+
+def run_api_youtube(
+ url:str,
+ source_lang:str = "en",
+ timestamps:str = "s",
+ word_timestamps:bool = False,
+ alignment:bool = False,
+ diarization:bool = False,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang = language of the URL source (defaulted to English)
+ timestamps = time unit of the timestamps (defaulted to seconds)
+ word_timestamps = associated words and their timestamps (defaulted to False)
+ alignment = re-align timestamps (defaulted to False)
+ diarization = speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ )
+
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+
+ with open("youtube_video_output.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+ | Could you make this dynamic? (Based on the youtube URL) |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,122 @@
+import requests
+import json
+
+def run_api_youtube(
+ url:str,
+ source_lang:str = "en",
+ timestamps:str = "s",
+ word_timestamps:bool = False,
+ alignment:bool = False,
+ diarization:bool = False,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang = language of the URL source (defaulted to English)
+ timestamps = time unit of the timestamps (defaulted to seconds)
+ word_timestamps = associated words and their timestamps (defaulted to False)
+ alignment = re-align timestamps (defaulted to False)
+ diarization = speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ )
+
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+
+ with open("youtube_video_output.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_api_audioFile( | ```suggestion
def run_api_audiofile(
```
Removing the camelcase. |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None", | ```suggestion
server_url: Optional[str] = None,
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns: | ```suggestion
diarization: speaker labels for utterances (defaulted to False)
server_url: the URL used to reach out the API.
Returns:
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ } | ```suggestion
data = {
"alignment": alignment,
"diarization": diarization,
"source_lang": source_lang,
"timestamps": timestamps,
"word_timestamps": word_timestamps,
}
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None": | ```suggestion
if server_url is None:
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ ) | ```suggestion
response = requests.post(
f"{server_url}/api/v1/youtube",
headers=headers,
params=params,
data=json.dumps(data),
timeout=timeout,
)
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None", | ```suggestion
server_url: Optional[str] = None,
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en", | This function lacks the `vocab` parameter. |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ } | ```suggestion
data = {
"alignment": alignment,
"diarization": diarization,
"source_lang": source_lang,
"timestamps": timestamps,
"word_timestamps": word_timestamps,
"dual_channel": dual_channel,
}
if vocab:
data["vocab"] = vocab
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "https://wordcab.com/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"https://wordcab.com/api/{server_url}", | ```suggestion
f"{server_url}/api/v1/audio-url",
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1] | ```suggestion
url_name = url.split("https://")[-1]
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "https://wordcab.com/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"https://wordcab.com/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1] | ```suggestion
url_name = url.split("https://")[-1]
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "https://wordcab.com/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"https://wordcab.com/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_api_audio_file(
+ file: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None", | ```suggestion
server_url: Optional[str] = None,
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "https://wordcab.com/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"https://wordcab.com/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_api_audio_file(
+ file: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio files.
+
+ Args:
+ file (str): file source of the audio file.
+ source_lang: language of the source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 900 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ filepath = file # or any other convertible format by ffmpeg
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ } | ```suggestion
data = {
"alignment": alignment,
"diarization": diarization,
"source_lang": source_lang,
"timestamps": timestamps,
"word_timestamps": word_timestamps,
"dual_channel": dual_channel,
}
if vocab:
data["vocab"] = vocab
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "https://wordcab.com/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"https://wordcab.com/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_api_audio_file(
+ file: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio files.
+
+ Args:
+ file (str): file source of the audio file.
+ source_lang: language of the source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 900 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ filepath = file # or any other convertible format by ffmpeg
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ with open(filepath, "rb") as f:
+ files = {"file": f}
+ if server_url == "None": | ```suggestion
if server_url is None:
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "https://wordcab.com/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"https://wordcab.com/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_api_audio_file(
+ file: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio files.
+
+ Args:
+ file (str): file source of the audio file.
+ source_lang: language of the source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 900 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ filepath = file # or any other convertible format by ffmpeg
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ with open(filepath, "rb") as f:
+ files = {"file": f}
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/audio",
+ files=files,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}", | ```suggestion
f"{server_url}/api/v1/audio",
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "https://wordcab.com/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"https://wordcab.com/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_api_audio_file(
+ file: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio files.
+
+ Args:
+ file (str): file source of the audio file.
+ source_lang: language of the source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 900 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ filepath = file # or any other convertible format by ffmpeg
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ with open(filepath, "rb") as f:
+ files = {"file": f}
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/audio",
+ files=files,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ files=files,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ filename = filepath.split(".")[0]
+ with open(f"{filename}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+# run API function that will delegate to other functions based on the endpoint
+def run_api(
+ endpoint: str,
+ source: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None", | ```suggestion
server_url: Optional[str] = None,
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,309 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: str = "None",
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "dual_channel": dual_channel,
+ }
+
+ if server_url == "None":
+ response = requests.post(
+ "https://wordcab.com/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"https://wordcab.com/api/{server_url}",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[1]
+
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_api_audio_file(
+ file: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio files.
+
+ Args:
+ file (str): file source of the audio file.
+ source_lang: language of the source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 900 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ filepath = file # or any other convertible format by ffmpeg
+ if vocab:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ "vocab": vocab,
+ }
+ else:
+ data = {
+ "alignment": alignment, # Longer processing time but better timestamps
+ "diarization": diarization, # Longer processing time but speaker segment attribution
+ "dual_channel": dual_channel, # Only for stereo audio files with one speaker per channel
+ "source_lang": source_lang, # optional, default is "en"
+ "timestamps": timestamps, # optional, default is "s". Can be "s", "ms" or "hms".
+ "word_timestamps": word_timestamps, # optional, default is False
+ }
+
+ with open(filepath, "rb") as f:
+ files = {"file": f}
+ if server_url == "None":
+ response = requests.post(
+ "http://localhost:5001/api/v1/audio",
+ files=files,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"http://localhost:5001/api/{server_url}",
+ files=files,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ filename = filepath.split(".")[0]
+ with open(f"{filename}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+# run API function that will delegate to other functions based on the endpoint
+def run_api(
+ endpoint: str,
+ source: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: str = "None",
+ vocab: Optional[List[str]] = None,
+):
+ """
+ Automated function for API calls for 3 endpoints: audio files, youtube videos, and audio URLs.
+
+ Args:
+ endpoint (str): audio_file or youtube or audioURL
+ source: source of the endpoint (either a URL or a filepath)
+ source_lang: language of the source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 900 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ if endpoint == "youtube":
+ run_api_youtube(
+ source,
+ source_lang,
+ timestamps,
+ word_timestamps,
+ alignment,
+ diarization,
+ server_url,
+ )
+ elif endpoint == "audio_file":
+ run_api_audio_file(
+ source,
+ source_lang,
+ timestamps,
+ word_timestamps,
+ alignment,
+ diarization,
+ dual_channel,
+ server_url,
+ vocab,
+ )
+ elif endpoint == "audioURL": | ```suggestion
elif endpoint == "audio_url":
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,292 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: Optional[str] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ server_url: the URL used to reach out the API.
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment,
+ "diarization": diarization,
+ "source_lang": source_lang,
+ "timestamps": timestamps,
+ "word_timestamps": word_timestamps,
+ }
+
+ if server_url is None:
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"{server_url}/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[-1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: Optional[str] = None,
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ data = {
+ "alignment": alignment,
+ "diarization": diarization,
+ "source_lang": source_lang,
+ "timestamps": timestamps,
+ "word_timestamps": word_timestamps,
+ "dual_channel": dual_channel,
+ }
+ if vocab:
+ data["vocab"] = vocab
+
+ if server_url == "None": | ```suggestion
if server_url is None:
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.