File size: 4,586 Bytes
b751b43
5a6be6b
 
190218a
 
 
5a6be6b
190218a
5a6be6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190218a
 
 
 
 
b6825ca
190218a
 
5a6be6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190218a
 
 
aff93db
5a6be6b
 
 
f905e28
aff93db
5a6be6b
 
190218a
5a6be6b
f905e28
5a6be6b
 
f905e28
5a6be6b
f905e28
5a6be6b
aff93db
5a6be6b
aff93db
5a6be6b
 
aff93db
 
 
 
 
 
5a6be6b
 
 
190218a
5a6be6b
 
 
 
 
 
aff93db
 
190218a
 
 
 
f905e28
 
 
 
190218a
 
 
5a6be6b
190218a
5a6be6b
 
aff93db
5a6be6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aff93db
5a6be6b
 
190218a
5a6be6b
f905e28
5a6be6b
 
 
 
 
 
 
f905e28
190218a
5a6be6b
 
 
190218a
5a6be6b
 
f905e28
5a6be6b
f905e28
5a6be6b
 
f905e28
5a6be6b
f905e28
5a6be6b
 
 
f905e28
5a6be6b
 
f905e28
5a6be6b
 
 
190218a
5a6be6b
f443ce4
5a6be6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import FileResponse
from ultralytics import YOLO
from openai import OpenAI
from gtts import gTTS

import os
import uuid
import requests

app = FastAPI(
    title="Egyptian Talking Artifact API",
    version="1.0"
)

# =====================================
# Folders
# =====================================

os.makedirs("uploads", exist_ok=True)
os.makedirs("outputs", exist_ok=True)

# =====================================
# Models
# =====================================

model = YOLO("best_egypt.pt")

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"]
)

# =====================================
# Wav2Lip API
# =====================================

WAV2LIP_API = "https://fatma812-wav2lip-api.hf.space/generate-video"

# =====================================
# Home
# =====================================

@app.get("/")
def home():
    return {
        "message": "Egyptian Talking Artifact API",
        "docs": "/docs"
    }

# =====================================
# Generate Story + Audio
# =====================================

@app.post("/generate")
async def generate(
    image: UploadFile = File(...),
    language: str = Form(...)
):

    image_name = f"{uuid.uuid4().hex}.jpg"
    image_path = os.path.join("uploads", image_name)

    with open(image_path, "wb") as f:
        f.write(await image.read())

    results = model(image_path)

    if len(results[0].boxes) == 0:
        raise HTTPException(
            status_code=400,
            detail="No artifact detected"
        )

    cls = int(results[0].boxes.cls[0])
    artifact = results[0].names[cls]

    if language == "Arabic":

        prompt = f"""
أنت {artifact}، أثر مصري قديم.

تحدث بصيغة المتكلم.

عرف بنفسك لزوار المتحف.

اذكر معلومة تاريخية قصيرة.

اجعل الكلام مشوقًا.
"""

        tts_lang = "ar"

    else:

        prompt = f"""
You are {artifact}, an ancient Egyptian artifact.

Speak in first person.

Introduce yourself.

Mention one historical fact.

Keep it short.
"""

        tts_lang = "en"

    response = client.chat.completions.create(
        model="openai/gpt-4o-mini",
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ]
    )

    story = response.choices[0].message.content

    audio_name = f"{uuid.uuid4().hex}.mp3"
    audio_path = os.path.join("outputs", audio_name)

    gTTS(
        text=story,
        lang=tts_lang
    ).save(audio_path)

    return {
        "artifact": artifact,
        "story": story,
        "audio_url": f"/audio/{audio_name}",
        "image_url": f"/image/{image_name}"
    }

# =====================================
# Download Audio
# =====================================

@app.get("/audio/{filename}")
def get_audio(filename: str):

    path = os.path.join("outputs", filename)

    if not os.path.exists(path):
        raise HTTPException(404, "Audio not found")

    return FileResponse(
        path,
        media_type="audio/mpeg",
        filename=filename
    )

# =====================================
# Download Image
# =====================================

@app.get("/image/{filename}")
def get_image(filename: str):

    path = os.path.join("uploads", filename)

    if not os.path.exists(path):
        raise HTTPException(404, "Image not found")

    return FileResponse(path)

# =====================================
# Generate Talking Video
# =====================================

@app.post("/generate-video")
async def generate_video(

    image: UploadFile = File(...),
    audio: UploadFile = File(...)
):

    response = requests.post(

        WAV2LIP_API,

        files={
            "image": (
                image.filename,
                await image.read(),
                image.content_type
            ),
            "audio": (
                audio.filename,
                await audio.read(),
                audio.content_type
            )
        },

        timeout=600
    )

    if response.status_code != 200:
        raise HTTPException(
            status_code=500,
            detail=response.text
        )

    video_name = f"{uuid.uuid4().hex}.mp4"
    video_path = os.path.join("outputs", video_name)

    with open(video_path, "wb") as f:
        f.write(response.content)

    return FileResponse(
        video_path,
        media_type="video/mp4",
        filename=video_name
    )