garvitcpp commited on
Commit
75f8bfc
·
verified ·
1 Parent(s): 822078e

Upload 34 files

Browse files
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
app/__init__.py ADDED
File without changes
app/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (163 Bytes). View file
 
app/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (151 Bytes). View file
 
app/api/__init__.py ADDED
File without changes
app/api/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (167 Bytes). View file
 
app/api/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (155 Bytes). View file
 
app/api/__pycache__/routes.cpython-311.pyc ADDED
Binary file (2.13 kB). View file
 
app/api/__pycache__/routes.cpython-312.pyc ADDED
Binary file (1.88 kB). View file
 
app/api/routes.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException
2
+ from app.models.request_models import StoryRequest, StoryResponse
3
+ from app.services.story_generator import StoryGenerator
4
+ from app.services.story_refinement import clean_text, refine_story
5
+ import logging
6
+
7
+ # Create the router instance
8
+ router = APIRouter()
9
+ logger = logging.getLogger(__name__)
10
+
11
+ @router.post("/generate_story", response_model=StoryResponse)
12
+ async def generate_story(request: StoryRequest):
13
+ try:
14
+ # Initialize generator and generate initial story
15
+ generator = StoryGenerator()
16
+ initial_story = generator.generate_story(
17
+ request.prompt,
18
+ request.max_length,
19
+ request.temperature
20
+ )
21
+
22
+ # Clean the initial story
23
+ cleaned_story = clean_text(initial_story)
24
+
25
+ try:
26
+ # Try to get the refined story
27
+ final_story = await refine_story(cleaned_story)
28
+ except Exception as e:
29
+ logger.error(f"Refinement failed: {str(e)}")
30
+ final_story = cleaned_story # Use cleaned story if refinement fails
31
+
32
+ return StoryResponse(story=final_story)
33
+
34
+ except Exception as e:
35
+ logger.error(f"Story generation failed: {str(e)}")
36
+ raise HTTPException(
37
+ status_code=500,
38
+ detail=f"Story generation failed: {str(e)}"
39
+ )
app/core/__init__.py ADDED
File without changes
app/core/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (168 Bytes). View file
 
app/core/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (156 Bytes). View file
 
app/core/__pycache__/config.cpython-311.pyc ADDED
Binary file (964 Bytes). View file
 
app/core/__pycache__/config.cpython-312.pyc ADDED
Binary file (822 Bytes). View file
 
app/core/config.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ load_dotenv()
5
+
6
+ class Settings:
7
+ PROJECT_NAME: str = "Story Generator API"
8
+ MODEL_PATH: str = "best_model.pt"
9
+ GOOGLE_API_KEY: str = os.getenv('GEMINI_API_KEY')
10
+
11
+ if not GOOGLE_API_KEY:
12
+ raise ValueError("Gemini API Key is not set in the environment variable GEMINI_API_KEY")
13
+
14
+ settings = Settings()
app/models/__init__.py ADDED
File without changes
app/models/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (170 Bytes). View file
 
app/models/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (158 Bytes). View file
 
app/models/__pycache__/request_models.cpython-311.pyc ADDED
Binary file (1.04 kB). View file
 
app/models/__pycache__/request_models.cpython-312.pyc ADDED
Binary file (857 Bytes). View file
 
app/models/request_models.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+
3
+ class StoryRequest(BaseModel):
4
+ prompt: str
5
+ max_length: int = Field(default=200, ge=1, le=1000)
6
+ temperature: float = Field(default=0.7, ge=0.1, le=1.0)
7
+
8
+ class StoryResponse(BaseModel):
9
+ story: str
app/services/__init__.py ADDED
File without changes
app/services/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (172 Bytes). View file
 
app/services/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (160 Bytes). View file
 
app/services/__pycache__/story_generator.cpython-311.pyc ADDED
Binary file (3.5 kB). View file
 
app/services/__pycache__/story_generator.cpython-312.pyc ADDED
Binary file (3.32 kB). View file
 
app/services/__pycache__/story_refinement.cpython-311.pyc ADDED
Binary file (3.3 kB). View file
 
app/services/__pycache__/story_refinement.cpython-312.pyc ADDED
Binary file (3.03 kB). View file
 
app/services/story_generator.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel, GPT2Config
3
+ from app.core.config import settings
4
+
5
+ class StoryGenerator:
6
+ def __init__(self, model_path=settings.MODEL_PATH):
7
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
8
+ print(f"Using device: {self.device}")
9
+
10
+ self.tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
11
+ self.tokenizer.pad_token = self.tokenizer.eos_token
12
+
13
+ self.config = GPT2Config(
14
+ vocab_size=self.tokenizer.vocab_size,
15
+ n_positions=256,
16
+ n_ctx=256,
17
+ n_embd=256,
18
+ n_layer=4,
19
+ n_head=8
20
+ )
21
+
22
+ self.model = GPT2LMHeadModel(self.config)
23
+ self.load_model(model_path)
24
+ self.model.to(self.device)
25
+ self.best_loss = float('inf')
26
+
27
+ def load_model(self, path):
28
+ checkpoint = torch.load(path, map_location=self.device)
29
+ self.model.load_state_dict(checkpoint['model_state_dict'])
30
+
31
+ def generate_story(self, prompt, max_length=200, temperature=0.7):
32
+ self.model.eval()
33
+ input_ids = self.tokenizer.encode(prompt, return_tensors='pt').to(self.device)
34
+
35
+ with torch.no_grad():
36
+ output_ids = self.model.generate(
37
+ input_ids,
38
+ max_length=max_length,
39
+ num_return_sequences=1,
40
+ do_sample=True,
41
+ top_k=50,
42
+ top_p=0.95,
43
+ num_beams=1,
44
+ temperature=temperature,
45
+ pad_token_id=self.tokenizer.pad_token_id,
46
+ eos_token_id=self.tokenizer.eos_token_id,
47
+ length_penalty=1.0,
48
+ no_repeat_ngram_size=3,
49
+ early_stopping=True
50
+ )[0]
51
+
52
+ return self.tokenizer.decode(output_ids, skip_special_tokens=True)
app/services/story_refinement.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import unicodedata
3
+ import google.generativeai as genai
4
+ from fastapi import HTTPException
5
+ from app.core.config import settings
6
+
7
+ # Configure Gemini API
8
+ genai.configure(api_key=settings.GOOGLE_API_KEY)
9
+ gemini_model = genai.GenerativeModel('gemini-1.5-flash')
10
+
11
+ def clean_text(story: str) -> str:
12
+ """Clean and normalize the generated text"""
13
+ cleaned_story = unicodedata.normalize("NFKD", story)
14
+ cleaned_story = re.sub(r'[\n\\]+', ' ', cleaned_story)
15
+ cleaned_story = re.sub(r'\s+', ' ', cleaned_story)
16
+ cleaned_story = (
17
+ cleaned_story.replace("“", "\"").replace("â€", "\"").replace("’", "'")
18
+ .replace("â€TMs", "'s").replace("“", "\"").replace("Ó", "O")
19
+ .replace("â", "").replace("�", "")
20
+ )
21
+ cleaned_story = cleaned_story.replace("\\", "")
22
+ return cleaned_story.strip()
23
+
24
+ async def refine_story(story: str) -> str:
25
+ """Refine the story using the Gemini API with two-step refinement"""
26
+ try:
27
+ # First refinement
28
+ first_prompt = f"""
29
+ Refine the following story to make it coherent, grammatically correct, and fluent.
30
+ Maintain the original plot and ending, but enhance readability, fluency, and consistency:
31
+
32
+ {story}
33
+ """
34
+
35
+ first_response = gemini_model.generate_content(first_prompt)
36
+ first_refined = first_response.text if hasattr(first_response, 'text') else str(first_response)
37
+
38
+ # Second refinement for final polishing
39
+ final_prompt = f"""
40
+ Please perform a final polish on this story to ensure perfect coherence,
41
+ flow, and narrative structure while maintaining the essence of the story:
42
+
43
+ {first_refined}
44
+ """
45
+
46
+ final_response = gemini_model.generate_content(final_prompt)
47
+ final_refined = final_response.text if hasattr(final_response, 'text') else str(final_response)
48
+
49
+ return final_refined if final_refined else "No refined story generated."
50
+
51
+ except Exception as e:
52
+ print(f"Error in story refinement: {str(e)}")
53
+ return story # Return original story if refinement fails
best_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e56be320b521adf85965adbfd542e981a492ce11870306f61d03a9f161e53b7
3
+ size 64385826
main.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from app.api.routes import router
4
+
5
+ app = FastAPI(title="Story Generator API")
6
+
7
+ # Add CORS middleware
8
+ app.add_middleware(
9
+ CORSMiddleware,
10
+ allow_origins=["http://localhost:3000"],
11
+ allow_credentials=True,
12
+ allow_methods=["*"],
13
+ allow_headers=["*"],
14
+ )
15
+
16
+ # Include the router
17
+ app.include_router(router)
18
+
19
+ if __name__ == "__main__":
20
+ import uvicorn
21
+ uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi==0.115.5
2
+ protobuf==5.28.3
3
+ pydantic==2.9.2
4
+ python-dotenv==1.0.1
5
+ torch==2.4.1
6
+ transformers==4.44.2
7
+ uvicorn==0.32.0