walker11 commited on
Commit
a034e65
·
verified ·
1 Parent(s): a19c40c

Upload 2 files

Browse files
Files changed (2) hide show
  1. routers/__init__.py +0 -0
  2. routers/story.py +157 -0
routers/__init__.py ADDED
File without changes
routers/story.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from fastapi import APIRouter, HTTPException, BackgroundTasks
4
+ from fastapi.responses import FileResponse
5
+ from pathlib import Path
6
+
7
+ from models import StoryConfig, StoryResponse, ChoiceRequest, TTSRequest, TTSResponse, EditRequest, EditResponse
8
+ from ai_service import initialize_story, continue_story, continue_story_with_text, get_complete_story, edit_story
9
+ from tts_service import generate_audio_for_story, get_audio_url
10
+
11
+ # إعداد التسجيل
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ router = APIRouter()
16
+
17
+ # الحصول على مسار تخزين ملفات الصوت
18
+ AUDIO_STORAGE_PATH = os.path.abspath(os.getenv("AUDIO_STORAGE_PATH", "./audio_files"))
19
+ BASE_URL = os.getenv("BASE_URL", "http://localhost:8000")
20
+
21
+ logger.info(f"Audio storage path: {AUDIO_STORAGE_PATH}")
22
+ logger.info(f"Base URL: {BASE_URL}")
23
+
24
+
25
+ @router.post("/initialize", response_model=StoryResponse)
26
+ async def create_story(config: StoryConfig):
27
+ """
28
+ بدء قصة جديدة بناءً على التكوين المقدم
29
+ """
30
+ try:
31
+ # Log the incoming request data
32
+ print(f"Request data: {config.dict()}")
33
+
34
+ response = await initialize_story(config)
35
+ return response
36
+ except Exception as e:
37
+ # Log the error details
38
+ print(f"Error details: {str(e)}")
39
+ raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء إنشاء القصة: {str(e)}")
40
+
41
+
42
+ @router.post("/continue", response_model=StoryResponse)
43
+ async def continue_story_route(request: ChoiceRequest):
44
+ """
45
+ متابعة القصة بناءً على اختيار المستخدم أو إدخال نص مخصص
46
+ """
47
+ try:
48
+ # Log the request for debugging
49
+ logger.info(f"Continuing story with: {request.dict()}")
50
+
51
+ if request.choice_id is not None:
52
+ # استخدام الاختيار المحدد
53
+ response = await continue_story(request.story_id, request.choice_id)
54
+ elif request.custom_text is not None:
55
+ # استخدام النص المخصص
56
+ response = await continue_story_with_text(request.story_id, request.custom_text)
57
+ else:
58
+ # لا يوجد اختيار أو نص مخصص
59
+ raise ValueError("يجب تحديد اختيار أو إدخال نص مخصص")
60
+
61
+ return response
62
+ except ValueError as e:
63
+ logger.error(f"ValueError in continue_story_route: {str(e)}")
64
+ raise HTTPException(status_code=400, detail=str(e))
65
+ except Exception as e:
66
+ logger.error(f"Error in continue_story_route: {str(e)}")
67
+ raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء متابعة القصة: {str(e)}")
68
+
69
+
70
+ @router.get("/story/{story_id}", response_model=str)
71
+ async def get_story(story_id: str):
72
+ """
73
+ الحصول على نص القصة الكامل
74
+ """
75
+ try:
76
+ complete_story = await get_complete_story(story_id)
77
+ return complete_story
78
+ except ValueError as e:
79
+ raise HTTPException(status_code=404, detail=str(e))
80
+ except Exception as e:
81
+ raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء استرجاع القصة: {str(e)}")
82
+
83
+
84
+ @router.post("/tts", response_model=TTSResponse)
85
+ async def generate_tts(request: TTSRequest):
86
+ """
87
+ توليد ملف صوتي للقصة بسرعة محددة
88
+ """
89
+ try:
90
+ logger.info(f"Generating TTS for story ID: {request.story_id} with speed: {request.speed}")
91
+
92
+ # توليد أو استرجاع الملف الصوتي
93
+ audio_filename = await generate_audio_for_story(request.story_id)
94
+ logger.info(f"Audio filename: {audio_filename}")
95
+
96
+ # إنشاء URL للملف الصوتي مع تمرير معلومات السرعة
97
+ audio_url = get_audio_url(audio_filename, request.speed)
98
+ logger.info(f"Audio URL: {audio_url}")
99
+
100
+ return TTSResponse(audio_url=audio_url)
101
+ except ValueError as e:
102
+ logger.error(f"ValueError in generate_tts: {str(e)}")
103
+ raise HTTPException(status_code=404, detail=str(e))
104
+ except Exception as e:
105
+ logger.error(f"Error in generate_tts: {str(e)}")
106
+ raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء توليد الصوت: {str(e)}")
107
+
108
+
109
+ @router.get("/audio/{filename}")
110
+ async def get_audio_file(filename: str):
111
+ """
112
+ استرجاع ملف صوتي محدد
113
+ """
114
+ try:
115
+ file_path = os.path.join(AUDIO_STORAGE_PATH, filename)
116
+ logger.info(f"Attempting to serve audio file: {file_path}")
117
+
118
+ if not Path(file_path).exists():
119
+ logger.error(f"Audio file not found: {file_path}")
120
+ raise HTTPException(status_code=404, detail="الملف الصوتي غير موجود")
121
+
122
+ logger.info(f"Serving audio file: {file_path}")
123
+ return FileResponse(
124
+ path=file_path,
125
+ media_type="audio/mpeg",
126
+ filename=filename
127
+ )
128
+ except HTTPException:
129
+ raise
130
+ except Exception as e:
131
+ logger.error(f"Error serving audio file: {str(e)}")
132
+ raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء استرجاع الملف الصوتي: {str(e)}")
133
+
134
+
135
+ @router.post("/edit", response_model=EditResponse)
136
+ async def edit_story_endpoint(request: EditRequest):
137
+ """
138
+ تعديل القصة بناءً على تعليمات المستخدم
139
+ """
140
+ try:
141
+ logger.info(f"Editing story with ID: {request.story_id}")
142
+ logger.info(f"Edit instructions: {request.edit_instructions}")
143
+
144
+ # استدعاء خدمة التعديل
145
+ edit_result = await edit_story(request.story_id, request.edit_instructions)
146
+
147
+ return EditResponse(
148
+ success=True,
149
+ paragraphs=edit_result["paragraphs"],
150
+ title=edit_result["title"]
151
+ )
152
+ except ValueError as e:
153
+ logger.error(f"ValueError in edit_story_endpoint: {str(e)}")
154
+ raise HTTPException(status_code=404, detail=str(e))
155
+ except Exception as e:
156
+ logger.error(f"Error in edit_story_endpoint: {str(e)}")
157
+ raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء تعديل القصة: {str(e)}")