|
1
|
|
|
|
|
2
|
|
|
from typing import List |
|
3
|
|
|
import tensorflow as tf |
|
4
|
|
|
|
|
5
|
|
|
from .utils.proxy import RealSubject, Proxy |
|
6
|
|
|
|
|
7
|
|
|
|
|
8
|
|
|
class TensorflowSessionRunnerSubject(RealSubject): |
|
9
|
|
|
def __init__(self, interactive_session) -> None: |
|
10
|
|
|
self.interactive_session = interactive_session |
|
11
|
|
|
|
|
12
|
|
|
def request(self, *args, **kwargs): |
|
13
|
|
|
return self.interactive_session.run(*args, **kwargs) |
|
14
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
class TensorflowSessionRunner(Proxy): |
|
17
|
|
|
def __init__(self, real_subject) -> None: |
|
18
|
|
|
super().__init__(real_subject) |
|
19
|
|
|
self.args_history: List[str] = [] |
|
20
|
|
|
|
|
21
|
|
|
def request(self, *args, **kwargs): |
|
22
|
|
|
self.args_history.append(f"ARGS: [{', '.join((str(_) for _ in args))}], KWARGS: [{', '.join((f'{k}={v}' for k, v in kwargs.items()))}]") |
|
23
|
|
|
try: |
|
24
|
|
|
# We know that Proxy executes request by executing the request method on the subject |
|
25
|
|
|
return super().request(*args, **kwargs) |
|
26
|
|
|
except Exception as e: |
|
27
|
|
|
raise e |
|
28
|
|
|
|
|
29
|
|
|
@property |
|
30
|
|
|
def session(self): |
|
31
|
|
|
return self._real_subject.interactive_session |
|
32
|
|
|
|
|
33
|
|
|
def run(self, *args, **kwargs): |
|
34
|
|
|
return self.request(*args, **kwargs) |
|
35
|
|
|
|
|
36
|
|
|
@classmethod |
|
37
|
|
|
def with_default_graph_reset(cls): |
|
38
|
|
|
tf.compat.v1.reset_default_graph() |
|
39
|
|
|
tf.compat.v1.disable_eager_execution() |
|
40
|
|
|
return TensorflowSessionRunner(TensorflowSessionRunnerSubject( |
|
41
|
|
|
tf.compat.v1.InteractiveSession())) |
|
42
|
|
|
|