Spaces:
Sleeping
Sleeping
Upload 60 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- DockerfileAdded+29
- app.pyAdded+13
- requirements.txtAdded+29
- src/.DS_StoreAdded
- src/agents/agent_transcript/__pycache__/flow.cpython-311.pycAdded
- src/agents/agent_transcript/__pycache__/func.cpython-311.pycAdded
- src/agents/agent_transcript/__pycache__/prompt.cpython-311.pycAdded
- src/agents/agent_transcript/__pycache__/tools.cpython-311.pycAdded
- src/agents/agent_transcript/flow.pyAdded+74
- src/agents/agent_transcript/func.pyAdded+182
- src/agents/agent_transcript/prompt.pyAdded+182
- src/agents/agent_transcript/tools.pyAdded+54
- src/agents/base/flow.pyAdded+23
- src/agents/base/func.pyAdded+4
- src/apis/.DS_StoreAdded
- src/apis/__pycache__/create_app.cpython-311.pycAdded
- src/apis/controllers/__pycache__/category_controller.cpython-311.pycAdded
- src/apis/controllers/__pycache__/order_controller.cpython-311.pycAdded
- src/apis/controllers/__pycache__/service_controller.cpython-311.pycAdded
- src/apis/controllers/__pycache__/user_controller.cpython-311.pycAdded
- src/apis/controllers/__pycache__/user_service_controller.cpython-311.pycAdded
- src/apis/create_app.pyAdded+23
- src/apis/interfaces/__pycache__/auth_interface.cpython-311.pycAdded
- src/apis/interfaces/__pycache__/chat_interface.cpython-311.pycAdded
- src/apis/interfaces/__pycache__/file_processing_interface.cpython-311.pycAdded
- src/apis/middlewares/__pycache__/auth_middleware.cpython-311.pycAdded
- src/apis/middlewares/auth_middleware.pyAdded+40
- src/apis/models/BaseDocument.pyAdded+17
- src/apis/models/__pycache__/BaseDocument.cpython-311.pycAdded
- src/apis/models/__pycache__/bot_models.cpython-311.pycAdded
- src/apis/models/__pycache__/category_models.cpython-311.pycAdded
- src/apis/models/__pycache__/grade_models.cpython-311.pycAdded
- src/apis/models/__pycache__/order_models.cpython-311.pycAdded
- src/apis/models/__pycache__/service_model.cpython-311.pycAdded
- src/apis/models/__pycache__/service_provide.cpython-311.pycAdded
- src/apis/models/__pycache__/user_models.cpython-311.pycAdded
- src/apis/providers/__pycache__/jwt_provider.cpython-311.pycAdded
- src/apis/routers/__pycache__/api_testing_router.cpython-311.pycAdded
- src/apis/routers/__pycache__/auth_router.cpython-311.pycAdded
- src/apis/routers/__pycache__/custom_chatbot_router.cpython-311.pycAdded
- src/apis/routers/__pycache__/file_processing_router.cpython-311.pycAdded
- src/apis/routers/__pycache__/gen_script.cpython-311.pycAdded
- src/apis/routers/__pycache__/grade_code_router.cpython-311.pycAdded
- src/apis/routers/__pycache__/graded_assignment_router.cpython-311.pycAdded
- src/apis/routers/__pycache__/image_generation.cpython-311.pycAdded
- src/apis/routers/__pycache__/rag_agent_template.cpython-311.pycAdded
- src/apis/routers/__pycache__/vector_store_router.cpython-311.pycAdded
- src/apis/routers/gen_script.pyAdded+158
- src/config/__pycache__/cloudinary.cpython-311.pycAdded
- src/config/__pycache__/constants.cpython-311.pycAdded
1234567891011121314151617181920212223242526272829FROM python:3.11-slim
RUN apt-get update && \ apt-get install -y --no-install-recommends \ gcc libglib2.0-0 libsm6 libxext6 libxrender-dev \ git \ && rm -rf /var/lib/apt/lists/*
RUN useradd -m -u 1000 userUSER userENV PATH="/home/user/.local/bin:$PATH"WORKDIR /app
# 1. Copy requirementsCOPY --chown=user ./requirements.txt requirements.txt
# 2. Cài pip + dependencies chínhRUN pip install --no-cache-dir --upgrade pip \ && pip install --no-cache-dir --upgrade -r requirements.txt
# # 3. Cài torch bản CPU (bắt buộc, cài trước để các package khác nhận ra)# RUN pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
# # 4. Cài langchain_docling (không kèm torch nữa)# RUN pip install --no-cache-dir langchain_docling
# 5. Copy code vào imageCOPY --chown=user . /appCMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]12345678910111213from dotenv import load_dotenv
load_dotenv(override=True)
from src.apis.create_app import create_app, api_routerimport uvicorn
app = create_app()
app.include_router(api_router)if __name__ == "__main__": uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)1234567891011121314151617181920212223242526272829langgraphlangchainlangchain-communitypython-dotenvfastapimotorlangchain-google-genailangchain-openailangchain-pineconePyMuPDFpytzuvicorn[standard]python-multipartlangchain_experimentalduckduckgo-searchpydantic[email]python_jose==3.3.0pillowpython-docxlangchain-text-splittersPyJWT==2.8.0pymupdf docx2txtgitpythontiktokengoogle-genailangchain-coreyoutube-transcript-apiyoutube-comment-downloader1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374from langgraph.graph import StateGraph, START, ENDfrom .func import ( State, trim_history, extract_transcript_and_comment, script_structure_analyzer, comment_insight_extractor, scientific_fact_finder, script_re_outline, script_writer_init, script_writer_single, should_continue_writing, script_writer_end,)from langgraph.graph.state import CompiledStateGraph
class AgentTranscript: def __init__(self): self.builder = StateGraph(State)
def node(self): self.builder.add_node("trim_history", trim_history) self.builder.add_node( "extract_transcript_and_comment", extract_transcript_and_comment ) self.builder.add_node("script_structure_analyzer", script_structure_analyzer) self.builder.add_node("comment_insight_extractor", comment_insight_extractor) self.builder.add_node("scientific_fact_finder", scientific_fact_finder) self.builder.add_node("script_re_outline", script_re_outline) self.builder.add_node("script_writer_init", script_writer_init) self.builder.add_node("script_writer_single", script_writer_single) self.builder.add_node("script_writer_end", script_writer_end)
def edge(self): self.builder.add_edge(START, "trim_history") self.builder.add_edge("trim_history", "extract_transcript_and_comment") self.builder.add_edge( "extract_transcript_and_comment", "script_structure_analyzer" ) self.builder.add_edge("script_structure_analyzer", "comment_insight_extractor") self.builder.add_edge("comment_insight_extractor", "scientific_fact_finder") self.builder.add_edge("scientific_fact_finder", "script_re_outline") self.builder.add_edge("script_re_outline", "script_writer_init") # Conditional routing for script writing self.builder.add_conditional_edges( "script_writer_init", should_continue_writing, { "script_writer_single": "script_writer_single", "script_writer_end": "script_writer_end" } ) self.builder.add_conditional_edges( "script_writer_single", should_continue_writing, { "script_writer_single": "script_writer_single", "script_writer_end": "script_writer_end" } ) self.builder.add_edge("script_writer_end", END)
def __call__(self) -> CompiledStateGraph: self.node() self.edge()
return self.builder.compile()
script_writer_agent = AgentTranscript()()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182from typing import TypedDict, Optional, Listfrom langchain_core.messages import AnyMessage, ToolMessage, HumanMessage, AIMessagefrom langgraph.graph.message import add_messagesfrom typing import Sequence, Annotatedfrom langchain_core.messages import RemoveMessagefrom langchain_core.documents import Documentfrom src.config.llm import get_llmfrom src.utils.logger import loggerfrom src.utils.helper import extract_transcript, extract_commentfrom .prompt import *import operator
class State(TypedDict): video_link: str messages: Annotated[Sequence[AnyMessage], add_messages] transcript: str comment: str script_structure_analyzer_response: str comment_insight_extractor_response: str research_insight_response: str script_re_outline_response: str script_writer_response: List[str] target_word_count: int script_count: int current_script_index: int
def trim_history(state: State): history = state.get("messages", [])
if len(history) > 20: num_to_remove = len(history) - 20 remove_messages = [ RemoveMessage(id=history[i].id) for i in range(num_to_remove) ] return { "messages": remove_messages, "selected_ids": [], "selected_documents": [], }
return {}
def extract_transcript_and_comment(state: State): transcript = extract_transcript(state["video_link"]) comment = extract_comment(state["video_link"])
# Calculate script count based on target word count # Assume each script is around 200-300 words avg_words_per_script = 1000 script_count = max(1, state.get("target_word_count", 8000) // avg_words_per_script)
return { "transcript": transcript, "comment": comment, "script_count": script_count, "messages": HumanMessage( content=f"Will generate {script_count} scripts for {state.get('target_word_count', 8000)} words target" ), }
def script_structure_analyzer(state: State): transcript = state["transcript"] response = chain_script_structure_analyzer.invoke({"script": transcript}) return { "script_structure_analyzer_response": response.content, "messages": HumanMessage( content="Script Structure Analyzer Response: " + response.content ), }
def comment_insight_extractor(state: State): response = chain_comment_insight_extractor.invoke( { "comment": state["comment"], "script_structure_analyzer_response": state[ "script_structure_analyzer_response" ], } ) return { "comment_insight_extractor_response": response.content, "messages": HumanMessage( content="Comment Insight Extractor Response: " + response.content ), }
def scientific_fact_finder(state: State): input_message = {} input_message["messages"] = [ { "role": "user", "content": f"""Hãy tìm 3-5 nghiên cứu khoa học thực tế (PubMed, JAMA, Circulation, Nutrients…), Tóm tắt số liệu, trích nguồn, gợi ý số liệu phù hợp cho từng đoạn trong script mới. Dựa trên các thông tin sau:Script Structure Analyzer Response: {state["script_structure_analyzer_response"]} Comment Insight Extractor Response: {state["comment_insight_extractor_response"]}""", } ] response = scientific_fact_agent.invoke(input_message) research_insight = response["messages"][-1].content return { "research_insight_response": research_insight, "messages": HumanMessage( content="Scientific Fact Finder Response: " + research_insight ), }
def script_re_outline(state: State): response = chain_script_re_outline.invoke({"messages": state["messages"]}) return { "script_re_outline_response": response.content, "messages": HumanMessage( content="Script Re-Outline Response: " + response.content ), }
def script_writer_init(state: State): """Initialize script writing process""" return { "script_writer_response": [], "current_script_index": 0, "messages": HumanMessage(content="Starting script generation process..."), }
def script_writer_single(state: State): """Generate a single script""" current_index = state.get("current_script_index", 0) script_count = state.get("script_count", 10) target_word_count = state.get("target_word_count", 8000) words_per_script = target_word_count // script_count if script_count > 0 else 1000
# Get existing scripts script_out = list(state.get("script_writer_response", [])) current_messages = list(state["messages"])
# Add word count guidance to the prompt if current_index == 0: word_prompt = f"Hãy viết script đầu tiên với khoảng {words_per_script} từ." else: word_prompt = f"ok, viết cho tôi phần tiếp theo, bám sát cấu trúc, khoảng {words_per_script} từ cho script này, các công thức tạo cảm xúc và đừng quên đối tượng khán giả là người Mỹ,giới tính nữ, trên 20 tuổi, bắt đầu, trình bày thành dạng câu văn liền mạch, dùng để làm văn nói cho video YouTube, không dùng icon"
current_messages.append(HumanMessage(content=word_prompt))
# Generate script response = chain_script_writer.invoke({"messages": current_messages}) script_out.append(response.content)
# Add response to message history current_messages.append(AIMessage(content=response.content))
return { "script_writer_response": script_out, "current_script_index": current_index + 1, "messages": current_messages + [ HumanMessage(content=f"Script {current_index + 1}/{script_count} completed") ], }
def should_continue_writing(state: State): """Check if we should continue writing more scripts""" current_index = state.get("current_script_index", 0) script_count = state.get("script_count", 10) return ( "script_writer_single" if current_index < script_count else "script_writer_end" )
def script_writer_end(state: State): """Finalize script writing""" script_count = len(state.get("script_writer_response", [])) return {"messages": HumanMessage(content=f"All {script_count} scripts completed!")}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182from langchain_core.prompts import ChatPromptTemplatefrom src.config.llm import llm_2_0 as llm, llm_2_5_flash_previewfrom pydantic import BaseModel, Fieldfrom langchain_community.tools import DuckDuckGoSearchResultsfrom langgraph.prebuilt import create_react_agent
duckduckgo_search = DuckDuckGoSearchResults(max_results=10, output_format="json")
script_structure_analyzer_prompt = ChatPromptTemplate.from_messages( [ ( "system", """Vai trò: Bạn là Script Structure Analyzer trong một workflow của một nhóm các agent.Instruction:- Tự động phân tích kịch bản gốc, tách các phần (Mở bài, Thân bài, Điểm chốt, CTA)- Xác định công thức cấu trúc (AIDA, PAS, BFB,...)- Trích xuất hook, câu chuyển đoạn, CTA- Phát hiện điểm mạnh/yếu/chỗ lạc nhịp
Input: Script gốcOutput: - Outline: - Mở bài - Thân bài - Điểm chốt - CTA- Công thức cấu trúc - AIDA: Attention, Interest, Desire, Action - PAS: Problem, Agitation, Solution - BFB: Belief, Feeling, Behavior- Hook- Câu chuyển đoạn- CTA- Điểm mạnh/yếu/chỗ lạc nhịp""", ), ("user", "input script: {script}"), ])
comment_insight_extractor_prompt = ChatPromptTemplate.from_messages( [ ( "system", """Vai trò: Bạn là Comment Insight Extractor trong một workflow của một nhóm các agent phân tích youtube video.Instruction:- Đọc, phân tích tất cả comment, trích xuất insight- lọc ra các câu hỏi lặp lại, nỗi sợ/mong muốn/lợi ích/ngôn ngữ quen thuộc- So sánh insight với script gốc và xác định thiếu sót.
Input: - Output từ Script Structure Analyzer Agent Youtube Video- Comment
Output:- Insights Table: - Insight - Original Comment - Pain or Benefit - Suggest for Script- Missing From Script- Repeated Questions- Audience Language
""", ), ("user", "input comment: {comment}"), ( "user", "input script_structure_analyzer_response: {script_structure_analyzer_response}", ), ])scientific_fact_finder_prompt = ChatPromptTemplate.from_messages( [ ( "system", """Vai trò: Bạn là Scientific Fact Finder trong một workflow của một nhóm các agent phân tích youtube video.Instruction:- Tự động research 3-5 nghiên cứu khoa học thực tế (PubMed, JAMA, Circulation, Nutrients…), tóm tắt số liệu, trích nguồn, gợi ý số liệu phù hợp cho từng đoạn trong script mới.- So sánh fact science với script gốc và xác định thiếu sót.
Input: - Output từ Script Structure Analyzer Agent Youtube Video- Output từ Comment Insight Extractor Agent Youtube Video
Output List:- Title: Tên nghiên cứu- Summary: Tóm tắt nghiên cứu- Source: Nguồn nghiên cứu- Relevant for Section: Relevant cho section nào trong script mới""", ), ("placeholder", "{messages}"), ])
script_re_outline_prompt = ChatPromptTemplate.from_messages( [ ( "system", """Vai trò: Bạn là Script Re-Outline Agent trong một workflow của một nhóm các agent.Instruction:Kết hợp outline cũ, insight từ comment, fact từ research để lập outline mới: Hook mới, thứ tự section mới, CTA mới, các ý chuyển mạch rõ ràng, phân bổ fact/nghiên cứu vào các section.
Input:- Output từ Script Structure Analyzer Agent- Output từ Comment Insight Extractor Agent- Output từ Scientific Fact Finder Agent
Output:
- Outline mới: (Section, summary, suggested length, facts to include) - Hook mở bài - Thân bài 1 - Thân bài 2 - Điểm chốt - CTA- CTA position- Transitions- Order Logic""", ), ("placeholder", "{messages}"), ])
script_writer_prompt = ChatPromptTemplate.from_messages( [ ( "system", """Vai trò: Bạn là Script Writer dựa trên các nội dung, insight được cung cấp.Instruction:- Viết lại từng phần dựa theo outline mới, dữ liệu nghiên cứu, insight comment, giữ văn liền mạch - cảm xúc - kể chuyện, format cho video YouTube (dạng văn nói, không dùng icon, chỉ text).- Viết theo hội thoại chỉ có một người nói, không có người khác.
Input:- Output từ Script Re-Outline Agent (Important)- Output từ Scientific Fact Finder Agent- Output từ Comment Insight Extractor Agent
Processing:- Sau khi viết 1 phần, ngừng ngay.- Output phải liền mạch, không có gạch đầu dòng.- Tone giọng thân thiện, kể truyện, truyền cảm xúc, không dùng icon, chỉ dùng text.- Cài hook cảm xúc, ví dụ thực tế- Kể mở ra CTA hoặc dẫn sang phần tiếp theo.- Có câu hỏi tu từ nhẹ nhàng- Nhắc lại lợi ích quan trọng- So sánh "thay vì... thì..." để khán giả thấy rõ "why"- Không dùng icon, emoji- Kết thúc phải là kết thúc mở đề người dùng có thể yêu cầu viết tiếp thay vì kết thúc sau khi hoàn thành đủ hook, thân bài, điểm chốt, CTA.Output:- Title: Tên của phần nội dung- Content: Script content
Lưu ý: Chỉ gen ra một phần nội dung.- Nếu user nhập 'ok, viết cho tôi phần tiếp theo, bám sát cấu trúc, số lượng từ cho mỗi mục trong outline, các công thức tạo cảm xúc và đừng quên đối tượng khán giả là người Mỹ,giới tính nữ, trên 20 tuổi, bắt đầu, trình bày thành dạng câu văn liền mạch, dùng để làm văn nói cho video YouTube, không dùng icon' thì tiếp tục viết tiếp.
""", ), ("placeholder", "{messages}"), ])
chain_script_structure_analyzer = script_structure_analyzer_prompt | llmchain_comment_insight_extractor = comment_insight_extractor_prompt | llmscientific_fact_agent = create_react_agent( model=llm, tools=[duckduckgo_search], prompt=scientific_fact_finder_prompt,)
chain_script_re_outline = script_re_outline_prompt | llmchain_script_writer = script_writer_prompt | llm_2_5_flash_preview123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# from langchain_core.tools import tool# from src.utils.helper import convert_list_context_source_to_str# from src.utils.logger import logger# from langchain_core.runnables import RunnableConfig# from langchain_experimental.utilities import PythonREPL# from langchain_community.tools import DuckDuckGoSearchRun
# duckduckgo_search = DuckDuckGoSearchRun(max_results=10, output_format="json")
# python_exec = PythonREPL()
# @tool# def retrieve_document(query: str, config: RunnableConfig):# """Ưu tiên truy xuất tài liệu từ vector store nếu câu hỏi liên quan đến vai trò của chatbot.
# Args:# query (str): Câu truy vấn của người dùng bằng tiếng Việt# Returns:# str: Retrieved documents# """# configuration = config.get("configurable", {})# bot_id = configuration.get("bot_id", None)# if not bot_id:# logger.error("Bot ID is not found")# return {"context_str": "", "selected_documents": [], "selected_ids": []}# retriever = test_rag_vector_store.as_retriever(# search_type="similarity_score_threshold",# search_kwargs={"k": 5, "score_threshold": 0.3},# )# documents = retriever.invoke(query, filter={"bot_id": bot_id})# selected_documents = [doc.__dict__ for doc in documents]# selected_ids = [doc["id"] for doc in selected_documents]# context_str = convert_list_context_source_to_str(documents)
# return {# "context_str": context_str,# "selected_documents": selected_documents,# "selected_ids": selected_ids,# }
# @tool# def python_repl(code: str):# """# A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.
# Args:# code (str): Python code to execute# Returns:# str: Output of the Python code# """# return python_exec.run(code)1234567891011121314151617181920212223from langgraph.graph import StateGraph, START, ENDfrom src.config.llm import llm_2_0from .func import Statefrom langgraph.graph.state import CompiledStateGraph
class PrimaryChatBot: def __init__(self): self.builder = StateGraph(State)
@staticmethod def routing(state: State): pass
def node(self): pass
def edge(self): pass def __call__(self) -> CompiledStateGraph: self.node() self.edge() return self.builder.compile()1234from typing import TypedDict
class State(TypedDict): pass1234567891011121314151617181920212223from fastapi import FastAPI, APIRouterfrom fastapi.middleware.cors import CORSMiddlewarefrom src.apis.routers.gen_script import router as gen_script_router
api_router = APIRouter()api_router.include_router(gen_script_router)
def create_app(): app = FastAPI( docs_url="/", title="AI Service ABAOXOMTIEU", ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
return app12345678910111213141516171819202122232425262728293031323334353637383940from typing import Annotated
from fastapi import Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.responses import JSONResponse
from src.apis.providers.jwt_provider import jwt_provider as jwt
from src.apis.models.user_models import get_user
from src.config.mongo import UserCRUD
from bson import ObjectId
from jose import JWTError
from src.utils.logger import logger
security = HTTPBearer()
async def get_current_user(
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
try:
token = credentials.credentials
if not token:
return JSONResponse(
content={"msg": "Authentication failed"}, status_code=401
)
payload = jwt.decrypt(token)
user_id: str = payload["id"]
if not user_id:
return JSONResponse(
content={"msg": "Authentication failed"}, status_code=401
)
user = await UserCRUD.read_one({"_id": ObjectId(user_id)})
user_email = user.get("email", None)
logger.info(f"Request of user: {user_email}")
if not user:
return JSONResponse(
content={"msg": "Authentication failed"}, status_code=401
)
return get_user(user)
except JWTError:
return JSONResponse(content={"msg": "Authentication failed"}, status_code=401)1234567891011121314151617from pydantic import BaseModel, Fieldfrom typing import Optionalfrom datetime import datetimefrom src.utils.logger import get_date_time
class BaseDocument(BaseModel): created_at: Optional[datetime] = Field( default_factory=lambda: get_date_time().replace(tzinfo=None) ) updated_at: Optional[datetime] = Field( default_factory=lambda: get_date_time().replace(tzinfo=None) ) expire_at: Optional[datetime] = None
class Config: arbitrary_types_allowed = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158from fastapi import APIRouterfrom fastapi.responses import StreamingResponsefrom langchain_core.messages import AIMessageChunkfrom langchain_core.runnables import RunnableConfigfrom src.agents.agent_transcript.flow import script_writer_agentfrom src.utils.logger import loggerfrom pydantic import BaseModelimport jsonimport asyncio
class GenScriptRequest(BaseModel): video_link: str target_word_count: int = 50000 # Default 2500 words
router = APIRouter()
async def message_generator( input_graph: dict, config: RunnableConfig,): try: last_output_state = None
try: async for event in script_writer_agent.astream( input=input_graph, stream_mode=["messages", "values"], config=config ): try: event_type, event_message = event logger.info(f"Event type: {event_type}")
if event_type == "messages": message, metadata = event_message if isinstance(message, AIMessageChunk): # Stream AI message chunks node = metadata.get("node") chunk_data = { "type": "message_chunk", "content": message.content, "metadata": metadata, "node_step": node, } logger.info(f"Chunk data: {chunk_data}") yield f"data: {json.dumps(chunk_data)}\n\n"
elif event_type == "values": # Stream state updates state_data = {"type": "state_update", "state": event_message} last_output_state = event_message # Handle specific data extractions if "transcript" in event_message and event_message["transcript"]: transcript_data = { "type": "transcript_extracted", "transcript": event_message["transcript"][:500] + "..." if len(event_message["transcript"]) > 500 else event_message["transcript"], "full_length": len(event_message["transcript"]) } yield f"data: {json.dumps(transcript_data)}\n\n" if "comment" in event_message and event_message["comment"]: comment_data = { "type": "comment_extracted", "comment": event_message["comment"][:500] + "..." if len(event_message["comment"]) > 500 else event_message["comment"], "full_length": len(event_message["comment"]) } yield f"data: {json.dumps(comment_data)}\n\n" if "script_count" in event_message: script_count_data = { "type": "script_count_calculated", "script_count": event_message["script_count"], "target_word_count": event_message.get("target_word_count", 8000) } yield f"data: {json.dumps(script_count_data)}\n\n" # Handle individual script updates if "script_writer_response" in event_message and "current_script_index" in event_message: current_scripts = event_message["script_writer_response"] current_index = event_message["current_script_index"] script_count = event_message.get("script_count", 10) if current_scripts: individual_script_data = { "type": "individual_script", "script_index": current_index, "script_content": current_scripts[-1] if current_scripts else "", "progress": f"{current_index}/{script_count}", "scripts": current_scripts } yield f"data: {json.dumps(individual_script_data)}\n\n" yield f"data: {json.dumps(state_data, default=str)}\n\n"
except Exception as e: logger.error(f"Error processing event: {e}") error_data = {"type": "error", "message": str(e)} yield f"data: {json.dumps(error_data)}\n\n"
except Exception as e: logger.error(f"Error in streaming: {e}") error_data = {"type": "error", "message": str(e)} yield f"data: {json.dumps(error_data)}\n\n"
# Send final result if last_output_state: final_data = { "type": "final_result", "scripts": last_output_state.get("script_writer_response", []), "total_scripts": len( last_output_state.get("script_writer_response", []) ), } yield f"data: {json.dumps(final_data, default=str)}\n\n"
except Exception as e: logger.error(f"Fatal error in message_generator: {e}") yield f"data: {json.dumps({'type': 'fatal_error', 'message': str(e)})}\n\n"
@router.post("/gen-script")async def gen_script(request: GenScriptRequest): """ Generate scripts with streaming response """ config = RunnableConfig() input_graph = { "video_link": request.video_link, "target_word_count": request.target_word_count }
return StreamingResponse( message_generator(input_graph, config), media_type="text/plain", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "Content-Type": "text/event-stream", }, )
@router.post("/gen-script-sync")def gen_script_sync(request: GenScriptRequest): """ Generate scripts with synchronous response (non-streaming) """ response = script_writer_agent.invoke({ "video_link": request.video_link, "target_word_count": request.target_word_count }) return { "scripts": response.get("script_writer_response", []), "total_scripts": len(response.get("script_writer_response", [])), "full_response": response, }DockerfileAdded+29
app.pyAdded+13
requirements.txtAdded+29
src/.DS_StoreAdded
src/agents/agent_transcript/__pycache__/flow.cpython-311.pycAdded
src/agents/agent_transcript/__pycache__/func.cpython-311.pycAdded
src/agents/agent_transcript/__pycache__/prompt.cpython-311.pycAdded
src/agents/agent_transcript/__pycache__/tools.cpython-311.pycAdded
src/agents/agent_transcript/flow.pyAdded+74
src/agents/agent_transcript/func.pyAdded+182
src/agents/agent_transcript/prompt.pyAdded+182
src/agents/agent_transcript/tools.pyAdded+54
src/agents/base/flow.pyAdded+23
src/agents/base/func.pyAdded+4
src/apis/.DS_StoreAdded
src/apis/__pycache__/create_app.cpython-311.pycAdded
src/apis/controllers/__pycache__/category_controller.cpython-311.pycAdded
src/apis/controllers/__pycache__/order_controller.cpython-311.pycAdded
src/apis/controllers/__pycache__/service_controller.cpython-311.pycAdded
src/apis/controllers/__pycache__/user_controller.cpython-311.pycAdded
src/apis/controllers/__pycache__/user_service_controller.cpython-311.pycAdded
src/apis/create_app.pyAdded+23
src/apis/interfaces/__pycache__/auth_interface.cpython-311.pycAdded
src/apis/interfaces/__pycache__/chat_interface.cpython-311.pycAdded
src/apis/interfaces/__pycache__/file_processing_interface.cpython-311.pycAdded
src/apis/middlewares/__pycache__/auth_middleware.cpython-311.pycAdded
src/apis/middlewares/auth_middleware.pyAdded+40
src/apis/models/BaseDocument.pyAdded+17
src/apis/models/__pycache__/BaseDocument.cpython-311.pycAdded
src/apis/models/__pycache__/bot_models.cpython-311.pycAdded
src/apis/models/__pycache__/category_models.cpython-311.pycAdded
src/apis/models/__pycache__/grade_models.cpython-311.pycAdded
src/apis/models/__pycache__/order_models.cpython-311.pycAdded
src/apis/models/__pycache__/service_model.cpython-311.pycAdded
src/apis/models/__pycache__/service_provide.cpython-311.pycAdded
src/apis/models/__pycache__/user_models.cpython-311.pycAdded
src/apis/providers/__pycache__/jwt_provider.cpython-311.pycAdded
src/apis/routers/__pycache__/api_testing_router.cpython-311.pycAdded
src/apis/routers/__pycache__/auth_router.cpython-311.pycAdded
src/apis/routers/__pycache__/custom_chatbot_router.cpython-311.pycAdded
src/apis/routers/__pycache__/file_processing_router.cpython-311.pycAdded
src/apis/routers/__pycache__/gen_script.cpython-311.pycAdded
src/apis/routers/__pycache__/grade_code_router.cpython-311.pycAdded
src/apis/routers/__pycache__/graded_assignment_router.cpython-311.pycAdded
src/apis/routers/__pycache__/image_generation.cpython-311.pycAdded
src/apis/routers/__pycache__/rag_agent_template.cpython-311.pycAdded
src/apis/routers/__pycache__/vector_store_router.cpython-311.pycAdded
src/apis/routers/gen_script.pyAdded+158
src/config/__pycache__/cloudinary.cpython-311.pycAdded
src/config/__pycache__/constants.cpython-311.pycAdded